1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This class implements the parser for assembly files.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/ADT/APFloat.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/BinaryFormat/Dwarf.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCCodeView.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCDirectives.h"
29 #include "llvm/MC/MCDwarf.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/MC/MCInstPrinter.h"
32 #include "llvm/MC/MCInstrDesc.h"
33 #include "llvm/MC/MCInstrInfo.h"
34 #include "llvm/MC/MCObjectFileInfo.h"
35 #include "llvm/MC/MCParser/AsmCond.h"
36 #include "llvm/MC/MCParser/AsmLexer.h"
37 #include "llvm/MC/MCParser/MCAsmLexer.h"
38 #include "llvm/MC/MCParser/MCAsmParser.h"
39 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
40 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
41 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
42 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
43 #include "llvm/MC/MCRegisterInfo.h"
44 #include "llvm/MC/MCSection.h"
45 #include "llvm/MC/MCStreamer.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/MC/MCTargetOptions.h"
48 #include "llvm/MC/MCValue.h"
49 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MD5.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/MemoryBuffer.h"
55 #include "llvm/Support/SMLoc.h"
56 #include "llvm/Support/SourceMgr.h"
57 #include "llvm/Support/raw_ostream.h"
74 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
76 static cl::opt<unsigned> AsmMacroMaxNestingDepth(
77 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
78 cl::desc("The maximum nesting depth allowed for assembly macros."));
82 /// Helper types for tracking macro definitions.
83 typedef std::vector<AsmToken> MCAsmMacroArgument;
84 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
86 /// Helper class for storing information about an active macro
88 struct MacroInstantiation {
89 /// The location of the instantiation.
90 SMLoc InstantiationLoc;
92 /// The buffer where parsing should resume upon instantiation completion.
95 /// The location where parsing should resume upon instantiation completion.
98 /// The depth of TheCondStack at the start of the instantiation.
99 size_t CondStackDepth;
102 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
105 struct ParseStatementInfo {
106 /// The parsed operands from the last parsed statement.
107 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
109 /// The opcode from the last parsed instruction.
110 unsigned Opcode = ~0U;
112 /// Was there an error parsing the inline assembly?
113 bool ParseError = false;
115 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
117 ParseStatementInfo() = delete;
118 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
119 : AsmRewrites(rewrites) {}
122 /// The concrete assembly parser instance.
123 class AsmParser : public MCAsmParser {
128 const MCAsmInfo &MAI;
130 SourceMgr::DiagHandlerTy SavedDiagHandler;
131 void *SavedDiagContext;
132 std::unique_ptr<MCAsmParserExtension> PlatformParser;
134 /// This is the current buffer index we're lexing from as managed by the
135 /// SourceMgr object.
138 AsmCond TheCondState;
139 std::vector<AsmCond> TheCondStack;
141 /// maps directive names to handler methods in parser
142 /// extensions. Extensions register themselves in this map by calling
143 /// addDirectiveHandler.
144 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
146 /// Stack of active macro instantiations.
147 std::vector<MacroInstantiation*> ActiveMacros;
149 /// List of bodies of anonymous macros.
150 std::deque<MCAsmMacro> MacroLikeBodies;
152 /// Boolean tracking whether macro substitution is enabled.
153 unsigned MacrosEnabledFlag : 1;
155 /// Keeps track of how many .macro's have been instantiated.
156 unsigned NumOfMacroInstantiations;
158 /// The values from the last parsed cpp hash file line comment if any.
159 struct CppHashInfoTy {
164 CppHashInfoTy() : Filename(), LineNumber(0), Loc(), Buf(0) {}
166 CppHashInfoTy CppHashInfo;
168 /// The filename from the first cpp hash file line comment, if any.
169 StringRef FirstCppHashFilename;
171 /// List of forward directional labels for diagnosis at the end.
172 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
174 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
175 unsigned AssemblerDialect = ~0U;
177 /// is Darwin compatibility enabled?
178 bool IsDarwin = false;
180 /// Are we parsing ms-style inline assembly?
181 bool ParsingInlineAsm = false;
183 /// Did we already inform the user about inconsistent MD5 usage?
184 bool ReportedInconsistentMD5 = false;
186 // Is alt macro mode enabled.
187 bool AltMacroMode = false;
190 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
191 const MCAsmInfo &MAI, unsigned CB);
192 AsmParser(const AsmParser &) = delete;
193 AsmParser &operator=(const AsmParser &) = delete;
194 ~AsmParser() override;
196 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
198 void addDirectiveHandler(StringRef Directive,
199 ExtensionDirectiveHandler Handler) override {
200 ExtensionDirectiveMap[Directive] = Handler;
203 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
204 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
207 /// @name MCAsmParser Interface
210 SourceMgr &getSourceManager() override { return SrcMgr; }
211 MCAsmLexer &getLexer() override { return Lexer; }
212 MCContext &getContext() override { return Ctx; }
213 MCStreamer &getStreamer() override { return Out; }
215 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
217 unsigned getAssemblerDialect() override {
218 if (AssemblerDialect == ~0U)
219 return MAI.getAssemblerDialect();
221 return AssemblerDialect;
223 void setAssemblerDialect(unsigned i) override {
224 AssemblerDialect = i;
227 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
228 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
229 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
231 const AsmToken &Lex() override;
233 void setParsingInlineAsm(bool V) override {
234 ParsingInlineAsm = V;
235 // When parsing MS inline asm, we must lex 0b1101 and 0ABCH as binary and
236 // hex integer literals.
237 Lexer.setLexMasmIntegers(V);
239 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
241 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
242 unsigned &NumOutputs, unsigned &NumInputs,
243 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
244 SmallVectorImpl<std::string> &Constraints,
245 SmallVectorImpl<std::string> &Clobbers,
246 const MCInstrInfo *MII, const MCInstPrinter *IP,
247 MCAsmParserSemaCallback &SI) override;
249 bool parseExpression(const MCExpr *&Res);
250 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
251 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
252 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
253 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
254 SMLoc &EndLoc) override;
255 bool parseAbsoluteExpression(int64_t &Res) override;
257 /// Parse a floating point expression using the float \p Semantics
258 /// and set \p Res to the value.
259 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
261 /// Parse an identifier or string (as a quoted identifier)
262 /// and set \p Res to the identifier contents.
263 bool parseIdentifier(StringRef &Res) override;
264 void eatToEndOfStatement() override;
266 bool checkForValidSection() override;
271 bool parseStatement(ParseStatementInfo &Info,
272 MCAsmParserSemaCallback *SI);
273 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
274 bool parseCppHashLineFilenameComment(SMLoc L);
276 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
277 ArrayRef<MCAsmMacroParameter> Parameters);
278 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
279 ArrayRef<MCAsmMacroParameter> Parameters,
280 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
283 /// Are macros enabled in the parser?
284 bool areMacrosEnabled() {return MacrosEnabledFlag;}
286 /// Control a flag in the parser that enables or disables macros.
287 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
289 /// Are we inside a macro instantiation?
290 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
292 /// Handle entry to macro instantiation.
294 /// \param M The macro.
295 /// \param NameLoc Instantiation location.
296 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
298 /// Handle exit from macro instantiation.
299 void handleMacroExit();
301 /// Extract AsmTokens for a macro argument.
302 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
304 /// Parse all macro arguments for a given macro.
305 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
307 void printMacroInstantiations();
308 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
309 SMRange Range = None) const {
310 ArrayRef<SMRange> Ranges(Range);
311 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
313 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
315 /// Should we emit DWARF describing this assembler source? (Returns false if
316 /// the source has .file directives, which means we don't want to generate
317 /// info describing the assembler source itself.)
318 bool enabledGenDwarfForAssembly();
320 /// Enter the specified file. This returns true on failure.
321 bool enterIncludeFile(const std::string &Filename);
323 /// Process the specified file for the .incbin directive.
324 /// This returns true on failure.
325 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
326 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
328 /// Reset the current lexer position to that given by \p Loc. The
329 /// current token is not set; clients should ensure Lex() is called
332 /// \param InBuffer If not 0, should be the known buffer id that contains the
334 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
336 /// Parse up to the end of statement and a return the contents from the
337 /// current token until the end of the statement; the current token on exit
338 /// will be either the EndOfStatement or EOF.
339 StringRef parseStringToEndOfStatement() override;
341 /// Parse until the end of a statement or a comma is encountered,
342 /// return the contents from the current token up to the end or comma.
343 StringRef parseStringToComma();
345 bool parseAssignment(StringRef Name, bool allow_redef,
346 bool NoDeadStrip = false);
348 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
349 MCBinaryExpr::Opcode &Kind);
351 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
352 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
353 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
355 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
357 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
358 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
360 // Generic (target and platform independent) directive parsing.
362 DK_NO_DIRECTIVE, // Placeholder
417 DK_BUNDLE_ALIGN_MODE,
431 DK_WEAK_DEF_CAN_BE_HIDDEN,
471 DK_CV_INLINE_SITE_ID,
474 DK_CV_INLINE_LINETABLE,
479 DK_CV_FILECHECKSUM_OFFSET,
485 DK_CFI_DEF_CFA_OFFSET,
486 DK_CFI_ADJUST_CFA_OFFSET,
487 DK_CFI_DEF_CFA_REGISTER,
492 DK_CFI_REMEMBER_STATE,
493 DK_CFI_RESTORE_STATE,
497 DK_CFI_RETURN_COLUMN,
523 /// Maps directive name --> DirectiveKind enum, for
524 /// directives parsed by this class.
525 StringMap<DirectiveKind> DirectiveKindMap;
527 // ".ascii", ".asciz", ".string"
528 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
529 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
530 bool parseDirectiveValue(StringRef IDVal,
531 unsigned Size); // ".byte", ".long", ...
532 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
533 bool parseDirectiveRealValue(StringRef IDVal,
534 const fltSemantics &); // ".single", ...
535 bool parseDirectiveFill(); // ".fill"
536 bool parseDirectiveZero(); // ".zero"
537 // ".set", ".equ", ".equiv"
538 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
539 bool parseDirectiveOrg(); // ".org"
540 // ".align{,32}", ".p2align{,w,l}"
541 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
543 // ".file", ".line", ".loc", ".stabs"
544 bool parseDirectiveFile(SMLoc DirectiveLoc);
545 bool parseDirectiveLine();
546 bool parseDirectiveLoc();
547 bool parseDirectiveStabs();
549 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
550 // ".cv_inline_linetable", ".cv_def_range", ".cv_string"
551 bool parseDirectiveCVFile();
552 bool parseDirectiveCVFuncId();
553 bool parseDirectiveCVInlineSiteId();
554 bool parseDirectiveCVLoc();
555 bool parseDirectiveCVLinetable();
556 bool parseDirectiveCVInlineLinetable();
557 bool parseDirectiveCVDefRange();
558 bool parseDirectiveCVString();
559 bool parseDirectiveCVStringTable();
560 bool parseDirectiveCVFileChecksums();
561 bool parseDirectiveCVFileChecksumOffset();
562 bool parseDirectiveCVFPOData();
565 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
566 bool parseDirectiveCFIWindowSave();
567 bool parseDirectiveCFISections();
568 bool parseDirectiveCFIStartProc();
569 bool parseDirectiveCFIEndProc();
570 bool parseDirectiveCFIDefCfaOffset();
571 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
572 bool parseDirectiveCFIAdjustCfaOffset();
573 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
574 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
575 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
576 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
577 bool parseDirectiveCFIRememberState();
578 bool parseDirectiveCFIRestoreState();
579 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
580 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
581 bool parseDirectiveCFIEscape();
582 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
583 bool parseDirectiveCFISignalFrame();
584 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
587 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
588 bool parseDirectiveExitMacro(StringRef Directive);
589 bool parseDirectiveEndMacro(StringRef Directive);
590 bool parseDirectiveMacro(SMLoc DirectiveLoc);
591 bool parseDirectiveMacrosOnOff(StringRef Directive);
592 // alternate macro mode directives
593 bool parseDirectiveAltmacro(StringRef Directive);
594 // ".bundle_align_mode"
595 bool parseDirectiveBundleAlignMode();
597 bool parseDirectiveBundleLock();
599 bool parseDirectiveBundleUnlock();
602 bool parseDirectiveSpace(StringRef IDVal);
605 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
606 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
608 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
610 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
611 bool parseDirectiveLEB128(bool Signed);
613 /// Parse a directive like ".globl" which
614 /// accepts a single symbol (which should be a label or an external).
615 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
617 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
619 bool parseDirectiveAbort(); // ".abort"
620 bool parseDirectiveInclude(); // ".include"
621 bool parseDirectiveIncbin(); // ".incbin"
623 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
624 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
625 // ".ifb" or ".ifnb", depending on ExpectBlank.
626 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
627 // ".ifc" or ".ifnc", depending on ExpectEqual.
628 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
629 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
630 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
631 // ".ifdef" or ".ifndef", depending on expect_defined
632 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
633 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
634 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
635 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
636 bool parseEscapedString(std::string &Data) override;
638 const MCExpr *applyModifierToExpr(const MCExpr *E,
639 MCSymbolRefExpr::VariantKind Variant);
641 // Macro-like directives
642 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
643 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
644 raw_svector_ostream &OS);
645 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
646 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
647 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
648 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
650 // "_emit" or "__emit"
651 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
655 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
658 bool parseDirectiveEnd(SMLoc DirectiveLoc);
660 // ".err" or ".error"
661 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
664 bool parseDirectiveWarning(SMLoc DirectiveLoc);
666 // .print <double-quotes-string>
667 bool parseDirectivePrint(SMLoc DirectiveLoc);
669 // Directives to support address-significance tables.
670 bool parseDirectiveAddrsig();
671 bool parseDirectiveAddrsigSym();
673 void initializeDirectiveKindMap();
676 } // end anonymous namespace
680 extern MCAsmParserExtension *createDarwinAsmParser();
681 extern MCAsmParserExtension *createELFAsmParser();
682 extern MCAsmParserExtension *createCOFFAsmParser();
683 extern MCAsmParserExtension *createWasmAsmParser();
685 } // end namespace llvm
687 enum { DEFAULT_ADDRSPACE = 0 };
689 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
690 const MCAsmInfo &MAI, unsigned CB = 0)
691 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
692 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
694 // Save the old handler.
695 SavedDiagHandler = SrcMgr.getDiagHandler();
696 SavedDiagContext = SrcMgr.getDiagContext();
697 // Set our own handler which calls the saved handler.
698 SrcMgr.setDiagHandler(DiagHandler, this);
699 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
701 // Initialize the platform / file format parser.
702 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
703 case MCObjectFileInfo::IsCOFF:
704 PlatformParser.reset(createCOFFAsmParser());
706 case MCObjectFileInfo::IsMachO:
707 PlatformParser.reset(createDarwinAsmParser());
710 case MCObjectFileInfo::IsELF:
711 PlatformParser.reset(createELFAsmParser());
713 case MCObjectFileInfo::IsWasm:
714 PlatformParser.reset(createWasmAsmParser());
716 case MCObjectFileInfo::IsXCOFF:
717 // TODO: Need to implement createXCOFFAsmParser for XCOFF format.
721 PlatformParser->Initialize(*this);
722 initializeDirectiveKindMap();
724 NumOfMacroInstantiations = 0;
727 AsmParser::~AsmParser() {
728 assert((HadError || ActiveMacros.empty()) &&
729 "Unexpected active macro instantiation!");
731 // Restore the saved diagnostics handler and context for use during
733 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
736 void AsmParser::printMacroInstantiations() {
737 // Print the active macro instantiation stack.
738 for (std::vector<MacroInstantiation *>::const_reverse_iterator
739 it = ActiveMacros.rbegin(),
740 ie = ActiveMacros.rend();
742 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
743 "while in macro instantiation");
746 void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
747 printPendingErrors();
748 printMessage(L, SourceMgr::DK_Note, Msg, Range);
749 printMacroInstantiations();
752 bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
753 if(getTargetParser().getTargetOptions().MCNoWarn)
755 if (getTargetParser().getTargetOptions().MCFatalWarnings)
756 return Error(L, Msg, Range);
757 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
758 printMacroInstantiations();
762 bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
764 printMessage(L, SourceMgr::DK_Error, Msg, Range);
765 printMacroInstantiations();
769 bool AsmParser::enterIncludeFile(const std::string &Filename) {
770 std::string IncludedFile;
772 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
777 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
781 /// Process the specified .incbin file by searching for it in the include paths
782 /// then just emitting the byte contents of the file to the streamer. This
783 /// returns true on failure.
784 bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
785 const MCExpr *Count, SMLoc Loc) {
786 std::string IncludedFile;
788 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
792 // Pick up the bytes from the file and emit them.
793 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
794 Bytes = Bytes.drop_front(Skip);
797 if (!Count->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
798 return Error(Loc, "expected absolute expression");
800 return Warning(Loc, "negative count has no effect");
801 Bytes = Bytes.take_front(Res);
803 getStreamer().EmitBytes(Bytes);
807 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
808 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
809 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
813 const AsmToken &AsmParser::Lex() {
814 if (Lexer.getTok().is(AsmToken::Error))
815 Error(Lexer.getErrLoc(), Lexer.getErr());
817 // if it's a end of statement with a comment in it
818 if (getTok().is(AsmToken::EndOfStatement)) {
819 // if this is a line comment output it.
820 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
821 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
822 Out.addExplicitComment(Twine(getTok().getString()));
825 const AsmToken *tok = &Lexer.Lex();
827 // Parse comments here to be deferred until end of next statement.
828 while (tok->is(AsmToken::Comment)) {
829 if (MAI.preserveAsmComments())
830 Out.addExplicitComment(Twine(tok->getString()));
834 if (tok->is(AsmToken::Eof)) {
835 // If this is the end of an included file, pop the parent file off the
837 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
838 if (ParentIncludeLoc != SMLoc()) {
839 jumpToLoc(ParentIncludeLoc);
847 bool AsmParser::enabledGenDwarfForAssembly() {
848 // Check whether the user specified -g.
849 if (!getContext().getGenDwarfForAssembly())
851 // If we haven't encountered any .file directives (which would imply that
852 // the assembler source was produced with debug info already) then emit one
853 // describing the assembler source file itself.
854 if (getContext().getGenDwarfFileNumber() == 0) {
855 // Use the first #line directive for this, if any. It's preprocessed, so
856 // there is no checksum, and of course no source directive.
857 if (!FirstCppHashFilename.empty())
858 getContext().setMCLineTableRootFile(/*CUID=*/0,
859 getContext().getCompilationDir(),
860 FirstCppHashFilename,
861 /*Cksum=*/None, /*Source=*/None);
862 const MCDwarfFile &RootFile =
863 getContext().getMCDwarfLineTable(/*CUID=*/0).getRootFile();
864 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
865 /*CUID=*/0, getContext().getCompilationDir(), RootFile.Name,
866 RootFile.Checksum, RootFile.Source));
871 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
872 // Create the initial section, if requested.
873 if (!NoInitialTextSection)
874 Out.InitSections(false);
880 AsmCond StartingCondState = TheCondState;
881 SmallVector<AsmRewrite, 4> AsmStrRewrites;
883 // If we are generating dwarf for assembly source files save the initial text
884 // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't
885 // emitting any actual debug info yet and haven't had a chance to parse any
886 // embedded .file directives.)
887 if (getContext().getGenDwarfForAssembly()) {
888 MCSection *Sec = getStreamer().getCurrentSectionOnly();
889 if (!Sec->getBeginSymbol()) {
890 MCSymbol *SectionStartSym = getContext().createTempSymbol();
891 getStreamer().EmitLabel(SectionStartSym);
892 Sec->setBeginSymbol(SectionStartSym);
894 bool InsertResult = getContext().addGenDwarfSection(Sec);
895 assert(InsertResult && ".text section should not have debug info yet");
899 // While we have input, parse each statement.
900 while (Lexer.isNot(AsmToken::Eof)) {
901 ParseStatementInfo Info(&AsmStrRewrites);
902 if (!parseStatement(Info, nullptr))
905 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
906 // for printing ErrMsg via Lex() only if no (presumably better) parser error
908 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
912 // parseStatement returned true so may need to emit an error.
913 printPendingErrors();
915 // Skipping to the next line if needed.
916 if (!getLexer().isAtStartOfStatement())
917 eatToEndOfStatement();
920 getTargetParser().onEndOfFile();
921 printPendingErrors();
923 // All errors should have been emitted.
924 assert(!hasPendingError() && "unexpected error from parseStatement");
926 getTargetParser().flushPendingInstructions(getStreamer());
928 if (TheCondState.TheCond != StartingCondState.TheCond ||
929 TheCondState.Ignore != StartingCondState.Ignore)
930 printError(getTok().getLoc(), "unmatched .ifs or .elses");
931 // Check to see there are no empty DwarfFile slots.
932 const auto &LineTables = getContext().getMCDwarfLineTables();
933 if (!LineTables.empty()) {
935 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
936 if (File.Name.empty() && Index != 0)
937 printError(getTok().getLoc(), "unassigned file number: " +
939 " for .file directives");
944 // Check to see that all assembler local symbols were actually defined.
945 // Targets that don't do subsections via symbols may not want this, though,
946 // so conservatively exclude them. Only do this if we're finalizing, though,
947 // as otherwise we won't necessarilly have seen everything yet.
949 if (MAI.hasSubsectionsViaSymbols()) {
950 for (const auto &TableEntry : getContext().getSymbols()) {
951 MCSymbol *Sym = TableEntry.getValue();
952 // Variable symbols may not be marked as defined, so check those
953 // explicitly. If we know it's a variable, we have a definition for
954 // the purposes of this check.
955 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
956 // FIXME: We would really like to refer back to where the symbol was
957 // first referenced for a source location. We need to add something
958 // to track that. Currently, we just point to the end of the file.
959 printError(getTok().getLoc(), "assembler local symbol '" +
960 Sym->getName() + "' not defined");
964 // Temporary symbols like the ones for directional jumps don't go in the
965 // symbol table. They also need to be diagnosed in all (final) cases.
966 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
967 if (std::get<2>(LocSym)->isUndefined()) {
968 // Reset the state of any "# line file" directives we've seen to the
969 // context as it was at the diagnostic site.
970 CppHashInfo = std::get<1>(LocSym);
971 printError(std::get<0>(LocSym), "directional label undefined");
976 // Finalize the output stream if there are no errors and if the client wants
978 if (!HadError && !NoFinalize)
981 return HadError || getContext().hadError();
984 bool AsmParser::checkForValidSection() {
985 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
986 Out.InitSections(false);
987 return Error(getTok().getLoc(),
988 "expected section directive before assembly directive");
993 /// Throw away the rest of the line for testing purposes.
994 void AsmParser::eatToEndOfStatement() {
995 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
999 if (Lexer.is(AsmToken::EndOfStatement))
1003 StringRef AsmParser::parseStringToEndOfStatement() {
1004 const char *Start = getTok().getLoc().getPointer();
1006 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
1009 const char *End = getTok().getLoc().getPointer();
1010 return StringRef(Start, End - Start);
1013 StringRef AsmParser::parseStringToComma() {
1014 const char *Start = getTok().getLoc().getPointer();
1016 while (Lexer.isNot(AsmToken::EndOfStatement) &&
1017 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
1020 const char *End = getTok().getLoc().getPointer();
1021 return StringRef(Start, End - Start);
1024 /// Parse a paren expression and return it.
1025 /// NOTE: This assumes the leading '(' has already been consumed.
1027 /// parenexpr ::= expr)
1029 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1030 if (parseExpression(Res))
1032 if (Lexer.isNot(AsmToken::RParen))
1033 return TokError("expected ')' in parentheses expression");
1034 EndLoc = Lexer.getTok().getEndLoc();
1039 /// Parse a bracket expression and return it.
1040 /// NOTE: This assumes the leading '[' has already been consumed.
1042 /// bracketexpr ::= expr]
1044 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1045 if (parseExpression(Res))
1047 EndLoc = getTok().getEndLoc();
1048 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
1053 /// Parse a primary expression and return it.
1054 /// primaryexpr ::= (parenexpr
1055 /// primaryexpr ::= symbol
1056 /// primaryexpr ::= number
1057 /// primaryexpr ::= '.'
1058 /// primaryexpr ::= ~,+,- primaryexpr
1059 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1060 SMLoc FirstTokenLoc = getLexer().getLoc();
1061 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
1062 switch (FirstTokenKind) {
1064 return TokError("unknown token in expression");
1065 // If we have an error assume that we've already handled it.
1066 case AsmToken::Error:
1068 case AsmToken::Exclaim:
1069 Lex(); // Eat the operator.
1070 if (parsePrimaryExpr(Res, EndLoc))
1072 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
1074 case AsmToken::Dollar:
1076 case AsmToken::String:
1077 case AsmToken::Identifier: {
1078 StringRef Identifier;
1079 if (parseIdentifier(Identifier)) {
1080 // We may have failed but $ may be a valid token.
1081 if (getTok().is(AsmToken::Dollar)) {
1082 if (Lexer.getMAI().getDollarIsPC()) {
1084 // This is a '$' reference, which references the current PC. Emit a
1085 // temporary label to the streamer and refer to it.
1086 MCSymbol *Sym = Ctx.createTempSymbol();
1088 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
1090 EndLoc = FirstTokenLoc;
1093 return Error(FirstTokenLoc, "invalid token in expression");
1096 // Parse symbol variant
1097 std::pair<StringRef, StringRef> Split;
1098 if (!MAI.useParensForSymbolVariant()) {
1099 if (FirstTokenKind == AsmToken::String) {
1100 if (Lexer.is(AsmToken::At)) {
1102 SMLoc AtLoc = getLexer().getLoc();
1104 if (parseIdentifier(VName))
1105 return Error(AtLoc, "expected symbol variant after '@'");
1107 Split = std::make_pair(Identifier, VName);
1110 Split = Identifier.split('@');
1112 } else if (Lexer.is(AsmToken::LParen)) {
1115 parseIdentifier(VName);
1117 if (parseToken(AsmToken::RParen,
1118 "unexpected token in variant, expected ')'"))
1120 Split = std::make_pair(Identifier, VName);
1123 EndLoc = SMLoc::getFromPointer(Identifier.end());
1125 // This is a symbol reference.
1126 StringRef SymbolName = Identifier;
1127 if (SymbolName.empty())
1128 return Error(getLexer().getLoc(), "expected a symbol reference");
1130 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1132 // Lookup the symbol variant if used.
1133 if (!Split.second.empty()) {
1134 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
1135 if (Variant != MCSymbolRefExpr::VK_Invalid) {
1136 SymbolName = Split.first;
1137 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
1138 Variant = MCSymbolRefExpr::VK_None;
1140 return Error(SMLoc::getFromPointer(Split.second.begin()),
1141 "invalid variant '" + Split.second + "'");
1145 MCSymbol *Sym = getContext().getInlineAsmLabel(SymbolName);
1147 Sym = getContext().getOrCreateSymbol(SymbolName);
1149 // If this is an absolute variable reference, substitute it now to preserve
1150 // semantics in the face of reassignment.
1151 if (Sym->isVariable()) {
1152 auto V = Sym->getVariableValue(/*SetUsed*/ false);
1153 bool DoInline = isa<MCConstantExpr>(V) && !Variant;
1154 if (auto TV = dyn_cast<MCTargetExpr>(V))
1155 DoInline = TV->inlineAssignedExpr();
1158 return Error(EndLoc, "unexpected modifier on variable reference");
1159 Res = Sym->getVariableValue(/*SetUsed*/ false);
1164 // Otherwise create a symbol ref.
1165 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
1168 case AsmToken::BigNum:
1169 return TokError("literal value out of range for directive");
1170 case AsmToken::Integer: {
1171 SMLoc Loc = getTok().getLoc();
1172 int64_t IntVal = getTok().getIntVal();
1173 Res = MCConstantExpr::create(IntVal, getContext());
1174 EndLoc = Lexer.getTok().getEndLoc();
1175 Lex(); // Eat token.
1176 // Look for 'b' or 'f' following an Integer as a directional label
1177 if (Lexer.getKind() == AsmToken::Identifier) {
1178 StringRef IDVal = getTok().getString();
1179 // Lookup the symbol variant if used.
1180 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1181 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1182 if (Split.first.size() != IDVal.size()) {
1183 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
1184 if (Variant == MCSymbolRefExpr::VK_Invalid)
1185 return TokError("invalid variant '" + Split.second + "'");
1186 IDVal = Split.first;
1188 if (IDVal == "f" || IDVal == "b") {
1190 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
1191 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
1192 if (IDVal == "b" && Sym->isUndefined())
1193 return Error(Loc, "directional label undefined");
1194 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
1195 EndLoc = Lexer.getTok().getEndLoc();
1196 Lex(); // Eat identifier.
1201 case AsmToken::Real: {
1202 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
1203 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
1204 Res = MCConstantExpr::create(IntVal, getContext());
1205 EndLoc = Lexer.getTok().getEndLoc();
1206 Lex(); // Eat token.
1209 case AsmToken::Dot: {
1210 // This is a '.' reference, which references the current PC. Emit a
1211 // temporary label to the streamer and refer to it.
1212 MCSymbol *Sym = Ctx.createTempSymbol();
1214 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
1215 EndLoc = Lexer.getTok().getEndLoc();
1216 Lex(); // Eat identifier.
1219 case AsmToken::LParen:
1220 Lex(); // Eat the '('.
1221 return parseParenExpr(Res, EndLoc);
1222 case AsmToken::LBrac:
1223 if (!PlatformParser->HasBracketExpressions())
1224 return TokError("brackets expression not supported on this target");
1225 Lex(); // Eat the '['.
1226 return parseBracketExpr(Res, EndLoc);
1227 case AsmToken::Minus:
1228 Lex(); // Eat the operator.
1229 if (parsePrimaryExpr(Res, EndLoc))
1231 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
1233 case AsmToken::Plus:
1234 Lex(); // Eat the operator.
1235 if (parsePrimaryExpr(Res, EndLoc))
1237 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
1239 case AsmToken::Tilde:
1240 Lex(); // Eat the operator.
1241 if (parsePrimaryExpr(Res, EndLoc))
1243 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
1245 // MIPS unary expression operators. The lexer won't generate these tokens if
1246 // MCAsmInfo::HasMipsExpressions is false for the target.
1247 case AsmToken::PercentCall16:
1248 case AsmToken::PercentCall_Hi:
1249 case AsmToken::PercentCall_Lo:
1250 case AsmToken::PercentDtprel_Hi:
1251 case AsmToken::PercentDtprel_Lo:
1252 case AsmToken::PercentGot:
1253 case AsmToken::PercentGot_Disp:
1254 case AsmToken::PercentGot_Hi:
1255 case AsmToken::PercentGot_Lo:
1256 case AsmToken::PercentGot_Ofst:
1257 case AsmToken::PercentGot_Page:
1258 case AsmToken::PercentGottprel:
1259 case AsmToken::PercentGp_Rel:
1260 case AsmToken::PercentHi:
1261 case AsmToken::PercentHigher:
1262 case AsmToken::PercentHighest:
1263 case AsmToken::PercentLo:
1264 case AsmToken::PercentNeg:
1265 case AsmToken::PercentPcrel_Hi:
1266 case AsmToken::PercentPcrel_Lo:
1267 case AsmToken::PercentTlsgd:
1268 case AsmToken::PercentTlsldm:
1269 case AsmToken::PercentTprel_Hi:
1270 case AsmToken::PercentTprel_Lo:
1271 Lex(); // Eat the operator.
1272 if (Lexer.isNot(AsmToken::LParen))
1273 return TokError("expected '(' after operator");
1274 Lex(); // Eat the operator.
1275 if (parseExpression(Res, EndLoc))
1277 if (Lexer.isNot(AsmToken::RParen))
1278 return TokError("expected ')'");
1279 Lex(); // Eat the operator.
1280 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1285 bool AsmParser::parseExpression(const MCExpr *&Res) {
1287 return parseExpression(Res, EndLoc);
1291 AsmParser::applyModifierToExpr(const MCExpr *E,
1292 MCSymbolRefExpr::VariantKind Variant) {
1293 // Ask the target implementation about this expression first.
1294 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1297 // Recurse over the given expression, rebuilding it to apply the given variant
1298 // if there is exactly one symbol.
1299 switch (E->getKind()) {
1300 case MCExpr::Target:
1301 case MCExpr::Constant:
1304 case MCExpr::SymbolRef: {
1305 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1307 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
1308 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1309 "' (already modified)");
1313 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
1316 case MCExpr::Unary: {
1317 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
1318 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
1321 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
1324 case MCExpr::Binary: {
1325 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1326 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1327 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1337 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1341 llvm_unreachable("Invalid expression kind!");
1344 /// This function checks if the next token is <string> type or arithmetic.
1345 /// string that begin with character '<' must end with character '>'.
1346 /// otherwise it is arithmetics.
1347 /// If the function returns a 'true' value,
1348 /// the End argument will be filled with the last location pointed to the '>'
1351 /// There is a gap between the AltMacro's documentation and the single quote
1352 /// implementation. GCC does not fully support this feature and so we will not
1354 /// TODO: Adding single quote as a string.
1355 static bool isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
1356 assert((StrLoc.getPointer() != nullptr) &&
1357 "Argument to the function cannot be a NULL value");
1358 const char *CharPtr = StrLoc.getPointer();
1359 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') &&
1360 (*CharPtr != '\0')) {
1361 if (*CharPtr == '!')
1365 if (*CharPtr == '>') {
1366 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1372 /// creating a string without the escape characters '!'.
1373 static std::string altMacroString(StringRef AltMacroStr) {
1375 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
1376 if (AltMacroStr[Pos] == '!')
1378 Res += AltMacroStr[Pos];
1383 /// Parse an expression and return it.
1385 /// expr ::= expr &&,|| expr -> lowest.
1386 /// expr ::= expr |,^,&,! expr
1387 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1388 /// expr ::= expr <<,>> expr
1389 /// expr ::= expr +,- expr
1390 /// expr ::= expr *,/,% expr -> highest.
1391 /// expr ::= primaryexpr
1393 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1394 // Parse the expression.
1396 if (getTargetParser().parsePrimaryExpr(Res, EndLoc) ||
1397 parseBinOpRHS(1, Res, EndLoc))
1400 // As a special case, we support 'a op b @ modifier' by rewriting the
1401 // expression to include the modifier. This is inefficient, but in general we
1402 // expect users to use 'a@modifier op b'.
1403 if (Lexer.getKind() == AsmToken::At) {
1406 if (Lexer.isNot(AsmToken::Identifier))
1407 return TokError("unexpected symbol modifier following '@'");
1409 MCSymbolRefExpr::VariantKind Variant =
1410 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1411 if (Variant == MCSymbolRefExpr::VK_Invalid)
1412 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1414 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1416 return TokError("invalid modifier '" + getTok().getIdentifier() +
1417 "' (no symbols present)");
1424 // Try to constant fold it up front, if possible. Do not exploit
1427 if (Res->evaluateAsAbsolute(Value))
1428 Res = MCConstantExpr::create(Value, getContext());
1433 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1435 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1438 bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1440 if (parseParenExpr(Res, EndLoc))
1443 for (; ParenDepth > 0; --ParenDepth) {
1444 if (parseBinOpRHS(1, Res, EndLoc))
1447 // We don't Lex() the last RParen.
1448 // This is the same behavior as parseParenExpression().
1449 if (ParenDepth - 1 > 0) {
1450 EndLoc = getTok().getEndLoc();
1451 if (parseToken(AsmToken::RParen,
1452 "expected ')' in parentheses expression"))
1459 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1462 SMLoc StartLoc = Lexer.getLoc();
1463 if (parseExpression(Expr))
1466 if (!Expr->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
1467 return Error(StartLoc, "expected absolute expression");
1472 static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1473 MCBinaryExpr::Opcode &Kind,
1474 bool ShouldUseLogicalShr) {
1477 return 0; // not a binop.
1479 // Lowest Precedence: &&, ||
1480 case AsmToken::AmpAmp:
1481 Kind = MCBinaryExpr::LAnd;
1483 case AsmToken::PipePipe:
1484 Kind = MCBinaryExpr::LOr;
1487 // Low Precedence: |, &, ^
1489 // FIXME: gas seems to support '!' as an infix operator?
1490 case AsmToken::Pipe:
1491 Kind = MCBinaryExpr::Or;
1493 case AsmToken::Caret:
1494 Kind = MCBinaryExpr::Xor;
1497 Kind = MCBinaryExpr::And;
1500 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1501 case AsmToken::EqualEqual:
1502 Kind = MCBinaryExpr::EQ;
1504 case AsmToken::ExclaimEqual:
1505 case AsmToken::LessGreater:
1506 Kind = MCBinaryExpr::NE;
1508 case AsmToken::Less:
1509 Kind = MCBinaryExpr::LT;
1511 case AsmToken::LessEqual:
1512 Kind = MCBinaryExpr::LTE;
1514 case AsmToken::Greater:
1515 Kind = MCBinaryExpr::GT;
1517 case AsmToken::GreaterEqual:
1518 Kind = MCBinaryExpr::GTE;
1521 // Intermediate Precedence: <<, >>
1522 case AsmToken::LessLess:
1523 Kind = MCBinaryExpr::Shl;
1525 case AsmToken::GreaterGreater:
1526 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1529 // High Intermediate Precedence: +, -
1530 case AsmToken::Plus:
1531 Kind = MCBinaryExpr::Add;
1533 case AsmToken::Minus:
1534 Kind = MCBinaryExpr::Sub;
1537 // Highest Precedence: *, /, %
1538 case AsmToken::Star:
1539 Kind = MCBinaryExpr::Mul;
1541 case AsmToken::Slash:
1542 Kind = MCBinaryExpr::Div;
1544 case AsmToken::Percent:
1545 Kind = MCBinaryExpr::Mod;
1550 static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1551 MCBinaryExpr::Opcode &Kind,
1552 bool ShouldUseLogicalShr) {
1555 return 0; // not a binop.
1557 // Lowest Precedence: &&, ||
1558 case AsmToken::AmpAmp:
1559 Kind = MCBinaryExpr::LAnd;
1561 case AsmToken::PipePipe:
1562 Kind = MCBinaryExpr::LOr;
1565 // Low Precedence: ==, !=, <>, <, <=, >, >=
1566 case AsmToken::EqualEqual:
1567 Kind = MCBinaryExpr::EQ;
1569 case AsmToken::ExclaimEqual:
1570 case AsmToken::LessGreater:
1571 Kind = MCBinaryExpr::NE;
1573 case AsmToken::Less:
1574 Kind = MCBinaryExpr::LT;
1576 case AsmToken::LessEqual:
1577 Kind = MCBinaryExpr::LTE;
1579 case AsmToken::Greater:
1580 Kind = MCBinaryExpr::GT;
1582 case AsmToken::GreaterEqual:
1583 Kind = MCBinaryExpr::GTE;
1586 // Low Intermediate Precedence: +, -
1587 case AsmToken::Plus:
1588 Kind = MCBinaryExpr::Add;
1590 case AsmToken::Minus:
1591 Kind = MCBinaryExpr::Sub;
1594 // High Intermediate Precedence: |, &, ^
1596 // FIXME: gas seems to support '!' as an infix operator?
1597 case AsmToken::Pipe:
1598 Kind = MCBinaryExpr::Or;
1600 case AsmToken::Caret:
1601 Kind = MCBinaryExpr::Xor;
1604 Kind = MCBinaryExpr::And;
1607 // Highest Precedence: *, /, %, <<, >>
1608 case AsmToken::Star:
1609 Kind = MCBinaryExpr::Mul;
1611 case AsmToken::Slash:
1612 Kind = MCBinaryExpr::Div;
1614 case AsmToken::Percent:
1615 Kind = MCBinaryExpr::Mod;
1617 case AsmToken::LessLess:
1618 Kind = MCBinaryExpr::Shl;
1620 case AsmToken::GreaterGreater:
1621 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1626 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1627 MCBinaryExpr::Opcode &Kind) {
1628 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1629 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1630 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1633 /// Parse all binary operators with precedence >= 'Precedence'.
1634 /// Res contains the LHS of the expression on input.
1635 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1637 SMLoc StartLoc = Lexer.getLoc();
1639 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1640 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1642 // If the next token is lower precedence than we are allowed to eat, return
1643 // successfully with what we ate already.
1644 if (TokPrec < Precedence)
1649 // Eat the next primary expression.
1651 if (getTargetParser().parsePrimaryExpr(RHS, EndLoc))
1654 // If BinOp binds less tightly with RHS than the operator after RHS, let
1655 // the pending operator take RHS as its LHS.
1656 MCBinaryExpr::Opcode Dummy;
1657 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1658 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1661 // Merge LHS and RHS according to operator.
1662 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
1667 /// ::= EndOfStatement
1668 /// ::= Label* Directive ...Operands... EndOfStatement
1669 /// ::= Label* Identifier OperandList* EndOfStatement
1670 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1671 MCAsmParserSemaCallback *SI) {
1672 assert(!hasPendingError() && "parseStatement started with pending error");
1673 // Eat initial spaces and comments
1674 while (Lexer.is(AsmToken::Space))
1676 if (Lexer.is(AsmToken::EndOfStatement)) {
1677 // if this is a line comment we can drop it safely
1678 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
1679 getTok().getString().front() == '\n')
1684 // Statements always start with an identifier.
1685 AsmToken ID = getTok();
1686 SMLoc IDLoc = ID.getLoc();
1688 int64_t LocalLabelVal = -1;
1689 if (Lexer.is(AsmToken::HashDirective))
1690 return parseCppHashLineFilenameComment(IDLoc);
1691 // Allow an integer followed by a ':' as a directional local label.
1692 if (Lexer.is(AsmToken::Integer)) {
1693 LocalLabelVal = getTok().getIntVal();
1694 if (LocalLabelVal < 0) {
1695 if (!TheCondState.Ignore) {
1696 Lex(); // always eat a token
1697 return Error(IDLoc, "unexpected token at start of statement");
1701 IDVal = getTok().getString();
1702 Lex(); // Consume the integer token to be used as an identifier token.
1703 if (Lexer.getKind() != AsmToken::Colon) {
1704 if (!TheCondState.Ignore) {
1705 Lex(); // always eat a token
1706 return Error(IDLoc, "unexpected token at start of statement");
1710 } else if (Lexer.is(AsmToken::Dot)) {
1711 // Treat '.' as a valid identifier in this context.
1714 } else if (Lexer.is(AsmToken::LCurly)) {
1715 // Treat '{' as a valid identifier in this context.
1719 } else if (Lexer.is(AsmToken::RCurly)) {
1720 // Treat '}' as a valid identifier in this context.
1723 } else if (Lexer.is(AsmToken::Star) &&
1724 getTargetParser().starIsStartOfStatement()) {
1725 // Accept '*' as a valid start of statement.
1728 } else if (parseIdentifier(IDVal)) {
1729 if (!TheCondState.Ignore) {
1730 Lex(); // always eat a token
1731 return Error(IDLoc, "unexpected token at start of statement");
1736 // Handle conditional assembly here before checking for skipping. We
1737 // have to do this so that .endif isn't skipped in a ".if 0" block for
1739 StringMap<DirectiveKind>::const_iterator DirKindIt =
1740 DirectiveKindMap.find(IDVal);
1741 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1743 : DirKindIt->getValue();
1754 return parseDirectiveIf(IDLoc, DirKind);
1756 return parseDirectiveIfb(IDLoc, true);
1758 return parseDirectiveIfb(IDLoc, false);
1760 return parseDirectiveIfc(IDLoc, true);
1762 return parseDirectiveIfeqs(IDLoc, true);
1764 return parseDirectiveIfc(IDLoc, false);
1766 return parseDirectiveIfeqs(IDLoc, false);
1768 return parseDirectiveIfdef(IDLoc, true);
1771 return parseDirectiveIfdef(IDLoc, false);
1773 return parseDirectiveElseIf(IDLoc);
1775 return parseDirectiveElse(IDLoc);
1777 return parseDirectiveEndIf(IDLoc);
1780 // Ignore the statement if in the middle of inactive conditional
1782 if (TheCondState.Ignore) {
1783 eatToEndOfStatement();
1787 // FIXME: Recurse on local labels?
1789 // See what kind of statement we have.
1790 switch (Lexer.getKind()) {
1791 case AsmToken::Colon: {
1792 if (!getTargetParser().isLabel(ID))
1794 if (checkForValidSection())
1797 // identifier ':' -> Label.
1800 // Diagnose attempt to use '.' as a label.
1802 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1804 // Diagnose attempt to use a variable as a label.
1806 // FIXME: Diagnostics. Note the location of the definition as a label.
1807 // FIXME: This doesn't diagnose assignment to a symbol which has been
1808 // implicitly marked as external.
1810 if (LocalLabelVal == -1) {
1811 if (ParsingInlineAsm && SI) {
1812 StringRef RewrittenLabel =
1813 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1814 assert(!RewrittenLabel.empty() &&
1815 "We should have an internal name here.");
1816 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1818 IDVal = RewrittenLabel;
1820 Sym = getContext().getOrCreateSymbol(IDVal);
1822 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1823 // End of Labels should be treated as end of line for lexing
1824 // purposes but that information is not available to the Lexer who
1825 // does not understand Labels. This may cause us to see a Hash
1826 // here instead of a preprocessor line comment.
1827 if (getTok().is(AsmToken::Hash)) {
1828 StringRef CommentStr = parseStringToEndOfStatement();
1830 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1833 // Consume any end of statement token, if present, to avoid spurious
1834 // AddBlankLine calls().
1835 if (getTok().is(AsmToken::EndOfStatement)) {
1839 getTargetParser().doBeforeLabelEmit(Sym);
1842 if (!getTargetParser().isParsingInlineAsm())
1843 Out.EmitLabel(Sym, IDLoc);
1845 // If we are generating dwarf for assembly source files then gather the
1846 // info to make a dwarf label entry for this label if needed.
1847 if (enabledGenDwarfForAssembly())
1848 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1851 getTargetParser().onLabelParsed(Sym);
1856 case AsmToken::Equal:
1857 if (!getTargetParser().equalIsAsmAssignment())
1859 // identifier '=' ... -> assignment statement
1862 return parseAssignment(IDVal, true);
1864 default: // Normal instruction or directive.
1868 // If macros are enabled, check to see if this is a macro instantiation.
1869 if (areMacrosEnabled())
1870 if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) {
1871 return handleMacroEntry(M, IDLoc);
1874 // Otherwise, we have a normal instruction or directive.
1876 // Directives start with "."
1877 if (IDVal.startswith(".") && IDVal != ".") {
1878 // There are several entities interested in parsing directives:
1880 // 1. The target-specific assembly parser. Some directives are target
1881 // specific or may potentially behave differently on certain targets.
1882 // 2. Asm parser extensions. For example, platform-specific parsers
1883 // (like the ELF parser) register themselves as extensions.
1884 // 3. The generic directive parser implemented by this class. These are
1885 // all the directives that behave in a target and platform independent
1886 // manner, or at least have a default behavior that's shared between
1887 // all targets and platforms.
1889 getTargetParser().flushPendingInstructions(getStreamer());
1891 SMLoc StartTokLoc = getTok().getLoc();
1892 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1894 if (hasPendingError())
1896 // Currently the return value should be true if we are
1897 // uninterested but as this is at odds with the standard parsing
1898 // convention (return true = error) we have instances of a parsed
1899 // directive that fails returning true as an error. Catch these
1900 // cases as best as possible errors here.
1901 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1903 // Return if we did some parsing or believe we succeeded.
1904 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
1907 // Next, check the extension directive map to see if any extension has
1908 // registered itself to parse this directive.
1909 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1910 ExtensionDirectiveMap.lookup(IDVal);
1912 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1914 // Finally, if no one else is interested in this directive, it must be
1915 // generic and familiar to this class.
1921 return parseDirectiveSet(IDVal, true);
1923 return parseDirectiveSet(IDVal, false);
1925 return parseDirectiveAscii(IDVal, false);
1928 return parseDirectiveAscii(IDVal, true);
1931 return parseDirectiveValue(IDVal, 1);
1937 return parseDirectiveValue(IDVal, 2);
1942 return parseDirectiveValue(IDVal, 4);
1945 return parseDirectiveValue(IDVal, 8);
1947 return parseDirectiveValue(
1948 IDVal, getContext().getAsmInfo()->getCodePointerSize());
1950 return parseDirectiveOctaValue(IDVal);
1954 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
1957 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
1959 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1960 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1963 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1964 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1967 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1969 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1971 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1973 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1975 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1977 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1979 return parseDirectiveOrg();
1981 return parseDirectiveFill();
1983 return parseDirectiveZero();
1985 eatToEndOfStatement(); // .extern is the default, ignore it.
1989 return parseDirectiveSymbolAttribute(MCSA_Global);
1990 case DK_LAZY_REFERENCE:
1991 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1992 case DK_NO_DEAD_STRIP:
1993 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1994 case DK_SYMBOL_RESOLVER:
1995 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1996 case DK_PRIVATE_EXTERN:
1997 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1999 return parseDirectiveSymbolAttribute(MCSA_Reference);
2000 case DK_WEAK_DEFINITION:
2001 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
2002 case DK_WEAK_REFERENCE:
2003 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
2004 case DK_WEAK_DEF_CAN_BE_HIDDEN:
2005 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
2007 return parseDirectiveSymbolAttribute(MCSA_Cold);
2010 return parseDirectiveComm(/*IsLocal=*/false);
2012 return parseDirectiveComm(/*IsLocal=*/true);
2014 return parseDirectiveAbort();
2016 return parseDirectiveInclude();
2018 return parseDirectiveIncbin();
2021 return TokError(Twine(IDVal) +
2022 " not currently supported for this target");
2024 return parseDirectiveRept(IDLoc, IDVal);
2026 return parseDirectiveIrp(IDLoc);
2028 return parseDirectiveIrpc(IDLoc);
2030 return parseDirectiveEndr(IDLoc);
2031 case DK_BUNDLE_ALIGN_MODE:
2032 return parseDirectiveBundleAlignMode();
2033 case DK_BUNDLE_LOCK:
2034 return parseDirectiveBundleLock();
2035 case DK_BUNDLE_UNLOCK:
2036 return parseDirectiveBundleUnlock();
2038 return parseDirectiveLEB128(true);
2040 return parseDirectiveLEB128(false);
2043 return parseDirectiveSpace(IDVal);
2045 return parseDirectiveFile(IDLoc);
2047 return parseDirectiveLine();
2049 return parseDirectiveLoc();
2051 return parseDirectiveStabs();
2053 return parseDirectiveCVFile();
2055 return parseDirectiveCVFuncId();
2056 case DK_CV_INLINE_SITE_ID:
2057 return parseDirectiveCVInlineSiteId();
2059 return parseDirectiveCVLoc();
2060 case DK_CV_LINETABLE:
2061 return parseDirectiveCVLinetable();
2062 case DK_CV_INLINE_LINETABLE:
2063 return parseDirectiveCVInlineLinetable();
2064 case DK_CV_DEF_RANGE:
2065 return parseDirectiveCVDefRange();
2067 return parseDirectiveCVString();
2068 case DK_CV_STRINGTABLE:
2069 return parseDirectiveCVStringTable();
2070 case DK_CV_FILECHECKSUMS:
2071 return parseDirectiveCVFileChecksums();
2072 case DK_CV_FILECHECKSUM_OFFSET:
2073 return parseDirectiveCVFileChecksumOffset();
2074 case DK_CV_FPO_DATA:
2075 return parseDirectiveCVFPOData();
2076 case DK_CFI_SECTIONS:
2077 return parseDirectiveCFISections();
2078 case DK_CFI_STARTPROC:
2079 return parseDirectiveCFIStartProc();
2080 case DK_CFI_ENDPROC:
2081 return parseDirectiveCFIEndProc();
2082 case DK_CFI_DEF_CFA:
2083 return parseDirectiveCFIDefCfa(IDLoc);
2084 case DK_CFI_DEF_CFA_OFFSET:
2085 return parseDirectiveCFIDefCfaOffset();
2086 case DK_CFI_ADJUST_CFA_OFFSET:
2087 return parseDirectiveCFIAdjustCfaOffset();
2088 case DK_CFI_DEF_CFA_REGISTER:
2089 return parseDirectiveCFIDefCfaRegister(IDLoc);
2091 return parseDirectiveCFIOffset(IDLoc);
2092 case DK_CFI_REL_OFFSET:
2093 return parseDirectiveCFIRelOffset(IDLoc);
2094 case DK_CFI_PERSONALITY:
2095 return parseDirectiveCFIPersonalityOrLsda(true);
2097 return parseDirectiveCFIPersonalityOrLsda(false);
2098 case DK_CFI_REMEMBER_STATE:
2099 return parseDirectiveCFIRememberState();
2100 case DK_CFI_RESTORE_STATE:
2101 return parseDirectiveCFIRestoreState();
2102 case DK_CFI_SAME_VALUE:
2103 return parseDirectiveCFISameValue(IDLoc);
2104 case DK_CFI_RESTORE:
2105 return parseDirectiveCFIRestore(IDLoc);
2107 return parseDirectiveCFIEscape();
2108 case DK_CFI_RETURN_COLUMN:
2109 return parseDirectiveCFIReturnColumn(IDLoc);
2110 case DK_CFI_SIGNAL_FRAME:
2111 return parseDirectiveCFISignalFrame();
2112 case DK_CFI_UNDEFINED:
2113 return parseDirectiveCFIUndefined(IDLoc);
2114 case DK_CFI_REGISTER:
2115 return parseDirectiveCFIRegister(IDLoc);
2116 case DK_CFI_WINDOW_SAVE:
2117 return parseDirectiveCFIWindowSave();
2120 return parseDirectiveMacrosOnOff(IDVal);
2122 return parseDirectiveMacro(IDLoc);
2125 return parseDirectiveAltmacro(IDVal);
2127 return parseDirectiveExitMacro(IDVal);
2130 return parseDirectiveEndMacro(IDVal);
2132 return parseDirectivePurgeMacro(IDLoc);
2134 return parseDirectiveEnd(IDLoc);
2136 return parseDirectiveError(IDLoc, false);
2138 return parseDirectiveError(IDLoc, true);
2140 return parseDirectiveWarning(IDLoc);
2142 return parseDirectiveReloc(IDLoc);
2145 return parseDirectiveDCB(IDVal, 2);
2147 return parseDirectiveDCB(IDVal, 1);
2149 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
2151 return parseDirectiveDCB(IDVal, 4);
2153 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
2156 return TokError(Twine(IDVal) +
2157 " not currently supported for this target");
2160 return parseDirectiveDS(IDVal, 2);
2162 return parseDirectiveDS(IDVal, 1);
2164 return parseDirectiveDS(IDVal, 8);
2167 return parseDirectiveDS(IDVal, 4);
2170 return parseDirectiveDS(IDVal, 12);
2172 return parseDirectivePrint(IDLoc);
2174 return parseDirectiveAddrsig();
2175 case DK_ADDRSIG_SYM:
2176 return parseDirectiveAddrsigSym();
2179 return Error(IDLoc, "unknown directive");
2182 // __asm _emit or __asm __emit
2183 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2184 IDVal == "_EMIT" || IDVal == "__EMIT"))
2185 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
2188 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
2189 return parseDirectiveMSAlign(IDLoc, Info);
2191 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
2192 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
2193 if (checkForValidSection())
2196 // Canonicalize the opcode to lower case.
2197 std::string OpcodeStr = IDVal.lower();
2198 ParseInstructionInfo IInfo(Info.AsmRewrites);
2199 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2200 Info.ParsedOperands);
2201 Info.ParseError = ParseHadError;
2203 // Dump the parsed representation, if requested.
2204 if (getShowParsedOperands()) {
2205 SmallString<256> Str;
2206 raw_svector_ostream OS(Str);
2207 OS << "parsed instruction: [";
2208 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
2211 Info.ParsedOperands[i]->print(OS);
2215 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
2218 // Fail even if ParseInstruction erroneously returns false.
2219 if (hasPendingError() || ParseHadError)
2222 // If we are generating dwarf for the current section then generate a .loc
2223 // directive for the instruction.
2224 if (!ParseHadError && enabledGenDwarfForAssembly() &&
2225 getContext().getGenDwarfSectionSyms().count(
2226 getStreamer().getCurrentSectionOnly())) {
2228 if (ActiveMacros.empty())
2229 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2231 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2232 ActiveMacros.front()->ExitBuffer);
2234 // If we previously parsed a cpp hash file line comment then make sure the
2235 // current Dwarf File is for the CppHashFilename if not then emit the
2236 // Dwarf File table for it and adjust the line number for the .loc.
2237 if (!CppHashInfo.Filename.empty()) {
2238 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
2239 0, StringRef(), CppHashInfo.Filename);
2240 getContext().setGenDwarfFileNumber(FileNumber);
2242 unsigned CppHashLocLineNo =
2243 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
2244 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
2247 getStreamer().EmitDwarfLocDirective(
2248 getContext().getGenDwarfFileNumber(), Line, 0,
2249 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2253 // If parsing succeeded, match the instruction.
2254 if (!ParseHadError) {
2256 if (getTargetParser().MatchAndEmitInstruction(
2257 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2258 getTargetParser().isParsingInlineAsm()))
2264 // Parse and erase curly braces marking block start/end
2266 AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2267 // Identify curly brace marking block start/end
2268 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2271 SMLoc StartLoc = Lexer.getLoc();
2272 Lex(); // Eat the brace
2273 if (Lexer.is(AsmToken::EndOfStatement))
2274 Lex(); // Eat EndOfStatement following the brace
2276 // Erase the block start/end brace from the output asm string
2277 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2278 StartLoc.getPointer());
2282 /// parseCppHashLineFilenameComment as this:
2283 /// ::= # number "filename"
2284 bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
2285 Lex(); // Eat the hash token.
2286 // Lexer only ever emits HashDirective if it fully formed if it's
2287 // done the checking already so this is an internal error.
2288 assert(getTok().is(AsmToken::Integer) &&
2289 "Lexing Cpp line comment: Expected Integer");
2290 int64_t LineNumber = getTok().getIntVal();
2292 assert(getTok().is(AsmToken::String) &&
2293 "Lexing Cpp line comment: Expected String");
2294 StringRef Filename = getTok().getString();
2297 // Get rid of the enclosing quotes.
2298 Filename = Filename.substr(1, Filename.size() - 2);
2300 // Save the SMLoc, Filename and LineNumber for later use by diagnostics
2301 // and possibly DWARF file info.
2302 CppHashInfo.Loc = L;
2303 CppHashInfo.Filename = Filename;
2304 CppHashInfo.LineNumber = LineNumber;
2305 CppHashInfo.Buf = CurBuffer;
2306 if (FirstCppHashFilename.empty())
2307 FirstCppHashFilename = Filename;
2311 /// will use the last parsed cpp hash line filename comment
2312 /// for the Filename and LineNo if any in the diagnostic.
2313 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
2314 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
2315 raw_ostream &OS = errs();
2317 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
2318 SMLoc DiagLoc = Diag.getLoc();
2319 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2320 unsigned CppHashBuf =
2321 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
2323 // Like SourceMgr::printMessage() we need to print the include stack if any
2324 // before printing the message.
2325 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2326 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2327 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
2328 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2329 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
2332 // If we have not parsed a cpp hash line filename comment or the source
2333 // manager changed or buffer changed (like in a nested include) then just
2334 // print the normal diagnostic using its Filename and LineNo.
2335 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
2336 DiagBuf != CppHashBuf) {
2337 if (Parser->SavedDiagHandler)
2338 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2340 Diag.print(nullptr, OS);
2344 // Use the CppHashFilename and calculate a line number based on the
2345 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2346 // for the diagnostic.
2347 const std::string &Filename = Parser->CppHashInfo.Filename;
2349 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2350 int CppHashLocLineNo =
2351 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
2353 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
2355 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2356 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
2357 Diag.getLineContents(), Diag.getRanges());
2359 if (Parser->SavedDiagHandler)
2360 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2362 NewDiag.print(nullptr, OS);
2365 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2366 // difference being that that function accepts '@' as part of identifiers and
2367 // we can't do that. AsmLexer.cpp should probably be changed to handle
2368 // '@' as a special case when needed.
2369 static bool isIdentifierChar(char c) {
2370 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2374 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
2375 ArrayRef<MCAsmMacroParameter> Parameters,
2376 ArrayRef<MCAsmMacroArgument> A,
2377 bool EnableAtPseudoVariable, SMLoc L) {
2378 unsigned NParameters = Parameters.size();
2379 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
2380 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
2381 return Error(L, "Wrong number of arguments");
2383 // A macro without parameters is handled differently on Darwin:
2384 // gas accepts no arguments and does no substitutions
2385 while (!Body.empty()) {
2386 // Scan for the next substitution.
2387 std::size_t End = Body.size(), Pos = 0;
2388 for (; Pos != End; ++Pos) {
2389 // Check for a substitution or escape.
2390 if (IsDarwin && !NParameters) {
2391 // This macro has no parameters, look for $0, $1, etc.
2392 if (Body[Pos] != '$' || Pos + 1 == End)
2395 char Next = Body[Pos + 1];
2396 if (Next == '$' || Next == 'n' ||
2397 isdigit(static_cast<unsigned char>(Next)))
2400 // This macro has parameters, look for \foo, \bar, etc.
2401 if (Body[Pos] == '\\' && Pos + 1 != End)
2407 OS << Body.slice(0, Pos);
2409 // Check if we reached the end.
2413 if (IsDarwin && !NParameters) {
2414 switch (Body[Pos + 1]) {
2420 // $n => number of arguments
2425 // $[0-9] => argument
2427 // Missing arguments are ignored.
2428 unsigned Index = Body[Pos + 1] - '0';
2429 if (Index >= A.size())
2432 // Otherwise substitute with the token values, with spaces eliminated.
2433 for (const AsmToken &Token : A[Index])
2434 OS << Token.getString();
2440 unsigned I = Pos + 1;
2442 // Check for the \@ pseudo-variable.
2443 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
2446 while (isIdentifierChar(Body[I]) && I + 1 != End)
2449 const char *Begin = Body.data() + Pos + 1;
2450 StringRef Argument(Begin, I - (Pos + 1));
2453 if (Argument == "@") {
2454 OS << NumOfMacroInstantiations;
2457 for (; Index < NParameters; ++Index)
2458 if (Parameters[Index].Name == Argument)
2461 if (Index == NParameters) {
2462 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2465 OS << '\\' << Argument;
2469 bool VarargParameter = HasVararg && Index == (NParameters - 1);
2470 for (const AsmToken &Token : A[Index])
2471 // For altmacro mode, you can write '%expr'.
2472 // The prefix '%' evaluates the expression 'expr'
2473 // and uses the result as a string (e.g. replace %(1+2) with the
2475 // Here, we identify the integer token which is the result of the
2476 // absolute expression evaluation and replace it with its string
2478 if (AltMacroMode && Token.getString().front() == '%' &&
2479 Token.is(AsmToken::Integer))
2480 // Emit an integer value to the buffer.
2481 OS << Token.getIntVal();
2482 // Only Token that was validated as a string and begins with '<'
2483 // is considered altMacroString!!!
2484 else if (AltMacroMode && Token.getString().front() == '<' &&
2485 Token.is(AsmToken::String)) {
2486 OS << altMacroString(Token.getStringContents());
2488 // We expect no quotes around the string's contents when
2489 // parsing for varargs.
2490 else if (Token.isNot(AsmToken::String) || VarargParameter)
2491 OS << Token.getString();
2493 OS << Token.getStringContents();
2495 Pos += 1 + Argument.size();
2499 // Update the scan point.
2500 Body = Body.substr(Pos);
2506 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
2507 size_t CondStackDepth)
2508 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
2509 CondStackDepth(CondStackDepth) {}
2511 static bool isOperator(AsmToken::TokenKind kind) {
2515 case AsmToken::Plus:
2516 case AsmToken::Minus:
2517 case AsmToken::Tilde:
2518 case AsmToken::Slash:
2519 case AsmToken::Star:
2521 case AsmToken::Equal:
2522 case AsmToken::EqualEqual:
2523 case AsmToken::Pipe:
2524 case AsmToken::PipePipe:
2525 case AsmToken::Caret:
2527 case AsmToken::AmpAmp:
2528 case AsmToken::Exclaim:
2529 case AsmToken::ExclaimEqual:
2530 case AsmToken::Less:
2531 case AsmToken::LessEqual:
2532 case AsmToken::LessLess:
2533 case AsmToken::LessGreater:
2534 case AsmToken::Greater:
2535 case AsmToken::GreaterEqual:
2536 case AsmToken::GreaterGreater:
2543 class AsmLexerSkipSpaceRAII {
2545 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2546 Lexer.setSkipSpace(SkipSpace);
2549 ~AsmLexerSkipSpaceRAII() {
2550 Lexer.setSkipSpace(true);
2557 } // end anonymous namespace
2559 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2562 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2563 StringRef Str = parseStringToEndOfStatement();
2564 MA.emplace_back(AsmToken::String, Str);
2569 unsigned ParenLevel = 0;
2571 // Darwin doesn't use spaces to delmit arguments.
2572 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
2578 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
2579 return TokError("unexpected token in macro instantiation");
2581 if (ParenLevel == 0) {
2583 if (Lexer.is(AsmToken::Comma))
2586 if (Lexer.is(AsmToken::Space)) {
2588 Lexer.Lex(); // Eat spaces
2591 // Spaces can delimit parameters, but could also be part an expression.
2592 // If the token after a space is an operator, add the token and the next
2593 // one into this argument
2595 if (isOperator(Lexer.getKind())) {
2596 MA.push_back(getTok());
2599 // Whitespace after an operator can be ignored.
2600 if (Lexer.is(AsmToken::Space))
2610 // handleMacroEntry relies on not advancing the lexer here
2611 // to be able to fill in the remaining default parameter values
2612 if (Lexer.is(AsmToken::EndOfStatement))
2615 // Adjust the current parentheses level.
2616 if (Lexer.is(AsmToken::LParen))
2618 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2621 // Append the token to the current argument list.
2622 MA.push_back(getTok());
2626 if (ParenLevel != 0)
2627 return TokError("unbalanced parentheses in macro argument");
2631 // Parse the macro instantiation arguments.
2632 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2633 MCAsmMacroArguments &A) {
2634 const unsigned NParameters = M ? M->Parameters.size() : 0;
2635 bool NamedParametersFound = false;
2636 SmallVector<SMLoc, 4> FALocs;
2638 A.resize(NParameters);
2639 FALocs.resize(NParameters);
2641 // Parse two kinds of macro invocations:
2642 // - macros defined without any parameters accept an arbitrary number of them
2643 // - macros defined with parameters accept at most that many of them
2644 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2645 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2647 SMLoc IDLoc = Lexer.getLoc();
2648 MCAsmMacroParameter FA;
2650 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2651 if (parseIdentifier(FA.Name))
2652 return Error(IDLoc, "invalid argument identifier for formal argument");
2654 if (Lexer.isNot(AsmToken::Equal))
2655 return TokError("expected '=' after formal parameter identifier");
2659 NamedParametersFound = true;
2661 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2663 if (NamedParametersFound && FA.Name.empty())
2664 return Error(IDLoc, "cannot mix positional and keyword arguments");
2666 SMLoc StrLoc = Lexer.getLoc();
2668 if (AltMacroMode && Lexer.is(AsmToken::Percent)) {
2669 const MCExpr *AbsoluteExp;
2673 if (parseExpression(AbsoluteExp, EndLoc))
2675 if (!AbsoluteExp->evaluateAsAbsolute(Value,
2676 getStreamer().getAssemblerPtr()))
2677 return Error(StrLoc, "expected absolute expression");
2678 const char *StrChar = StrLoc.getPointer();
2679 const char *EndChar = EndLoc.getPointer();
2680 AsmToken newToken(AsmToken::Integer,
2681 StringRef(StrChar, EndChar - StrChar), Value);
2682 FA.Value.push_back(newToken);
2683 } else if (AltMacroMode && Lexer.is(AsmToken::Less) &&
2684 isAltmacroString(StrLoc, EndLoc)) {
2685 const char *StrChar = StrLoc.getPointer();
2686 const char *EndChar = EndLoc.getPointer();
2687 jumpToLoc(EndLoc, CurBuffer);
2688 /// Eat from '<' to '>'
2690 AsmToken newToken(AsmToken::String,
2691 StringRef(StrChar, EndChar - StrChar));
2692 FA.Value.push_back(newToken);
2693 } else if(parseMacroArgument(FA.Value, Vararg))
2696 unsigned PI = Parameter;
2697 if (!FA.Name.empty()) {
2699 for (FAI = 0; FAI < NParameters; ++FAI)
2700 if (M->Parameters[FAI].Name == FA.Name)
2703 if (FAI >= NParameters) {
2704 assert(M && "expected macro to be defined");
2705 return Error(IDLoc, "parameter named '" + FA.Name +
2706 "' does not exist for macro '" + M->Name + "'");
2711 if (!FA.Value.empty()) {
2716 if (FALocs.size() <= PI)
2717 FALocs.resize(PI + 1);
2719 FALocs[PI] = Lexer.getLoc();
2722 // At the end of the statement, fill in remaining arguments that have
2723 // default values. If there aren't any, then the next argument is
2724 // required but missing
2725 if (Lexer.is(AsmToken::EndOfStatement)) {
2726 bool Failure = false;
2727 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2728 if (A[FAI].empty()) {
2729 if (M->Parameters[FAI].Required) {
2730 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2731 "missing value for required parameter "
2732 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2736 if (!M->Parameters[FAI].Value.empty())
2737 A[FAI] = M->Parameters[FAI].Value;
2743 if (Lexer.is(AsmToken::Comma))
2747 return TokError("too many positional arguments");
2750 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2751 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2752 // eliminate this, although we should protect against infinite loops.
2753 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2754 if (ActiveMacros.size() == MaxNestingDepth) {
2755 std::ostringstream MaxNestingDepthError;
2756 MaxNestingDepthError << "macros cannot be nested more than "
2757 << MaxNestingDepth << " levels deep."
2758 << " Use -asm-macro-max-nesting-depth to increase "
2760 return TokError(MaxNestingDepthError.str());
2763 MCAsmMacroArguments A;
2764 if (parseMacroArguments(M, A))
2767 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2768 // to hold the macro body with substitutions.
2769 SmallString<256> Buf;
2770 StringRef Body = M->Body;
2771 raw_svector_ostream OS(Buf);
2773 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2776 // We include the .endmacro in the buffer as our cue to exit the macro
2778 OS << ".endmacro\n";
2780 std::unique_ptr<MemoryBuffer> Instantiation =
2781 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2783 // Create the macro instantiation object and add to the current macro
2784 // instantiation stack.
2785 MacroInstantiation *MI = new MacroInstantiation(
2786 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2787 ActiveMacros.push_back(MI);
2789 ++NumOfMacroInstantiations;
2791 // Jump to the macro instantiation and prime the lexer.
2792 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2793 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2799 void AsmParser::handleMacroExit() {
2800 // Jump to the EndOfStatement we should return to, and consume it.
2801 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2804 // Pop the instantiation entry.
2805 delete ActiveMacros.back();
2806 ActiveMacros.pop_back();
2809 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2812 const MCExpr *Value;
2813 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2818 // In the case where we parse an expression starting with a '.', we will
2819 // not generate an error, nor will we create a symbol. In this case we
2820 // should just return out.
2824 // Do the assignment.
2825 Out.EmitAssignment(Sym, Value);
2827 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2832 /// parseIdentifier:
2835 bool AsmParser::parseIdentifier(StringRef &Res) {
2836 // The assembler has relaxed rules for accepting identifiers, in particular we
2837 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2838 // separate tokens. At this level, we have already lexed so we cannot (currently)
2839 // handle this as a context dependent token, instead we detect adjacent tokens
2840 // and return the combined identifier.
2841 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2842 SMLoc PrefixLoc = getLexer().getLoc();
2844 // Consume the prefix character, and check for a following identifier.
2847 Lexer.peekTokens(Buf, false);
2849 if (Buf[0].isNot(AsmToken::Identifier))
2852 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2853 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
2857 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
2858 // Construct the joined identifier and consume the token.
2860 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2861 Lex(); // Parser Lex to maintain invariants.
2865 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2868 Res = getTok().getIdentifier();
2870 Lex(); // Consume the identifier token.
2875 /// parseDirectiveSet:
2876 /// ::= .equ identifier ',' expression
2877 /// ::= .equiv identifier ',' expression
2878 /// ::= .set identifier ',' expression
2879 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2881 if (check(parseIdentifier(Name), "expected identifier") ||
2882 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2883 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2887 bool AsmParser::parseEscapedString(std::string &Data) {
2888 if (check(getTok().isNot(AsmToken::String), "expected string"))
2892 StringRef Str = getTok().getStringContents();
2893 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2894 if (Str[i] != '\\') {
2899 // Recognize escaped characters. Note that this escape semantics currently
2900 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2903 return TokError("unexpected backslash at end of string");
2905 // Recognize octal sequences.
2906 if ((unsigned)(Str[i] - '0') <= 7) {
2907 // Consume up to three octal characters.
2908 unsigned Value = Str[i] - '0';
2910 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2912 Value = Value * 8 + (Str[i] - '0');
2914 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2916 Value = Value * 8 + (Str[i] - '0');
2921 return TokError("invalid octal escape sequence (out of range)");
2923 Data += (unsigned char)Value;
2927 // Otherwise recognize individual escapes.
2930 // Just reject invalid escape sequences for now.
2931 return TokError("invalid escape sequence (unrecognized character)");
2933 case 'b': Data += '\b'; break;
2934 case 'f': Data += '\f'; break;
2935 case 'n': Data += '\n'; break;
2936 case 'r': Data += '\r'; break;
2937 case 't': Data += '\t'; break;
2938 case '"': Data += '"'; break;
2939 case '\\': Data += '\\'; break;
2947 /// parseDirectiveAscii:
2948 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2949 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2950 auto parseOp = [&]() -> bool {
2952 if (checkForValidSection() || parseEscapedString(Data))
2954 getStreamer().EmitBytes(Data);
2956 getStreamer().EmitBytes(StringRef("\0", 1));
2960 if (parseMany(parseOp))
2961 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2965 /// parseDirectiveReloc
2966 /// ::= .reloc expression , identifier [ , expression ]
2967 bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2968 const MCExpr *Offset;
2969 const MCExpr *Expr = nullptr;
2970 int64_t OffsetValue;
2971 SMLoc OffsetLoc = Lexer.getTok().getLoc();
2973 if (parseExpression(Offset))
2976 if ((Offset->evaluateAsAbsolute(OffsetValue,
2977 getStreamer().getAssemblerPtr()) &&
2978 check(OffsetValue < 0, OffsetLoc, "expression is negative")) ||
2979 (check(Offset->getKind() != llvm::MCExpr::Constant &&
2980 Offset->getKind() != llvm::MCExpr::SymbolRef,
2981 OffsetLoc, "expected non-negative number or a label")) ||
2982 (parseToken(AsmToken::Comma, "expected comma") ||
2983 check(getTok().isNot(AsmToken::Identifier), "expected relocation name")))
2986 SMLoc NameLoc = Lexer.getTok().getLoc();
2987 StringRef Name = Lexer.getTok().getIdentifier();
2990 if (Lexer.is(AsmToken::Comma)) {
2992 SMLoc ExprLoc = Lexer.getLoc();
2993 if (parseExpression(Expr))
2997 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2998 return Error(ExprLoc, "expression must be relocatable");
3001 if (parseToken(AsmToken::EndOfStatement,
3002 "unexpected token in .reloc directive"))
3005 const MCTargetAsmParser &MCT = getTargetParser();
3006 const MCSubtargetInfo &STI = MCT.getSTI();
3007 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc, STI))
3008 return Error(NameLoc, "unknown relocation name");
3013 /// parseDirectiveValue
3014 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
3015 bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
3016 auto parseOp = [&]() -> bool {
3017 const MCExpr *Value;
3018 SMLoc ExprLoc = getLexer().getLoc();
3019 if (checkForValidSection() || parseExpression(Value))
3021 // Special case constant expressions to match code generator.
3022 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3023 assert(Size <= 8 && "Invalid size");
3024 uint64_t IntValue = MCE->getValue();
3025 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
3026 return Error(ExprLoc, "out of range literal value");
3027 getStreamer().EmitIntValue(IntValue, Size);
3029 getStreamer().EmitValue(Value, Size, ExprLoc);
3033 if (parseMany(parseOp))
3034 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
3038 static bool parseHexOcta(AsmParser &Asm, uint64_t &hi, uint64_t &lo) {
3039 if (Asm.getTok().isNot(AsmToken::Integer) &&
3040 Asm.getTok().isNot(AsmToken::BigNum))
3041 return Asm.TokError("unknown token in expression");
3042 SMLoc ExprLoc = Asm.getTok().getLoc();
3043 APInt IntValue = Asm.getTok().getAPIntVal();
3045 if (!IntValue.isIntN(128))
3046 return Asm.Error(ExprLoc, "out of range literal value");
3047 if (!IntValue.isIntN(64)) {
3048 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
3049 lo = IntValue.getLoBits(64).getZExtValue();
3052 lo = IntValue.getZExtValue();
3057 /// ParseDirectiveOctaValue
3058 /// ::= .octa [ hexconstant (, hexconstant)* ]
3060 bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
3061 auto parseOp = [&]() -> bool {
3062 if (checkForValidSection())
3065 if (parseHexOcta(*this, hi, lo))
3067 if (MAI.isLittleEndian()) {
3068 getStreamer().EmitIntValue(lo, 8);
3069 getStreamer().EmitIntValue(hi, 8);
3071 getStreamer().EmitIntValue(hi, 8);
3072 getStreamer().EmitIntValue(lo, 8);
3077 if (parseMany(parseOp))
3078 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
3082 bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3083 // We don't truly support arithmetic on floating point expressions, so we
3084 // have to manually parse unary prefixes.
3086 if (getLexer().is(AsmToken::Minus)) {
3089 } else if (getLexer().is(AsmToken::Plus))
3092 if (Lexer.is(AsmToken::Error))
3093 return TokError(Lexer.getErr());
3094 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3095 Lexer.isNot(AsmToken::Identifier))
3096 return TokError("unexpected token in directive");
3098 // Convert to an APFloat.
3099 APFloat Value(Semantics);
3100 StringRef IDVal = getTok().getString();
3101 if (getLexer().is(AsmToken::Identifier)) {
3102 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
3103 Value = APFloat::getInf(Semantics);
3104 else if (!IDVal.compare_lower("nan"))
3105 Value = APFloat::getNaN(Semantics, false, ~0);
3107 return TokError("invalid floating point literal");
3108 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
3109 APFloat::opInvalidOp)
3110 return TokError("invalid floating point literal");
3114 // Consume the numeric token.
3117 Res = Value.bitcastToAPInt();
3122 /// parseDirectiveRealValue
3123 /// ::= (.single | .double) [ expression (, expression)* ]
3124 bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3125 const fltSemantics &Semantics) {
3126 auto parseOp = [&]() -> bool {
3128 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
3130 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
3131 AsInt.getBitWidth() / 8);
3135 if (parseMany(parseOp))
3136 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
3140 /// parseDirectiveZero
3141 /// ::= .zero expression
3142 bool AsmParser::parseDirectiveZero() {
3143 SMLoc NumBytesLoc = Lexer.getLoc();
3144 const MCExpr *NumBytes;
3145 if (checkForValidSection() || parseExpression(NumBytes))
3149 if (getLexer().is(AsmToken::Comma)) {
3151 if (parseAbsoluteExpression(Val))
3155 if (parseToken(AsmToken::EndOfStatement,
3156 "unexpected token in '.zero' directive"))
3158 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
3163 /// parseDirectiveFill
3164 /// ::= .fill expression [ , expression [ , expression ] ]
3165 bool AsmParser::parseDirectiveFill() {
3166 SMLoc NumValuesLoc = Lexer.getLoc();
3167 const MCExpr *NumValues;
3168 if (checkForValidSection() || parseExpression(NumValues))
3171 int64_t FillSize = 1;
3172 int64_t FillExpr = 0;
3174 SMLoc SizeLoc, ExprLoc;
3176 if (parseOptionalToken(AsmToken::Comma)) {
3177 SizeLoc = getTok().getLoc();
3178 if (parseAbsoluteExpression(FillSize))
3180 if (parseOptionalToken(AsmToken::Comma)) {
3181 ExprLoc = getTok().getLoc();
3182 if (parseAbsoluteExpression(FillExpr))
3186 if (parseToken(AsmToken::EndOfStatement,
3187 "unexpected token in '.fill' directive"))
3191 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
3195 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3199 if (!isUInt<32>(FillExpr) && FillSize > 4)
3200 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3202 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
3207 /// parseDirectiveOrg
3208 /// ::= .org expression [ , expression ]
3209 bool AsmParser::parseDirectiveOrg() {
3210 const MCExpr *Offset;
3211 SMLoc OffsetLoc = Lexer.getLoc();
3212 if (checkForValidSection() || parseExpression(Offset))
3215 // Parse optional fill expression.
3216 int64_t FillExpr = 0;
3217 if (parseOptionalToken(AsmToken::Comma))
3218 if (parseAbsoluteExpression(FillExpr))
3219 return addErrorSuffix(" in '.org' directive");
3220 if (parseToken(AsmToken::EndOfStatement))
3221 return addErrorSuffix(" in '.org' directive");
3223 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
3227 /// parseDirectiveAlign
3228 /// ::= {.align, ...} expression [ , expression [ , expression ]]
3229 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
3230 SMLoc AlignmentLoc = getLexer().getLoc();
3233 bool HasFillExpr = false;
3234 int64_t FillExpr = 0;
3235 int64_t MaxBytesToFill = 0;
3237 auto parseAlign = [&]() -> bool {
3238 if (parseAbsoluteExpression(Alignment))
3240 if (parseOptionalToken(AsmToken::Comma)) {
3241 // The fill expression can be omitted while specifying a maximum number of
3242 // alignment bytes, e.g:
3244 if (getTok().isNot(AsmToken::Comma)) {
3246 if (parseAbsoluteExpression(FillExpr))
3249 if (parseOptionalToken(AsmToken::Comma))
3250 if (parseTokenLoc(MaxBytesLoc) ||
3251 parseAbsoluteExpression(MaxBytesToFill))
3254 return parseToken(AsmToken::EndOfStatement);
3257 if (checkForValidSection())
3258 return addErrorSuffix(" in directive");
3259 // Ignore empty '.p2align' directives for GNU-as compatibility
3260 if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
3261 Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
3262 return parseToken(AsmToken::EndOfStatement);
3265 return addErrorSuffix(" in directive");
3267 // Always emit an alignment here even if we thrown an error.
3268 bool ReturnVal = false;
3270 // Compute alignment in bytes.
3272 // FIXME: Diagnose overflow.
3273 if (Alignment >= 32) {
3274 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
3278 Alignment = 1ULL << Alignment;
3280 // Reject alignments that aren't either a power of two or zero,
3281 // for gas compatibility. Alignment of zero is silently rounded
3285 if (!isPowerOf2_64(Alignment))
3286 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
3289 // Diagnose non-sensical max bytes to align.
3290 if (MaxBytesLoc.isValid()) {
3291 if (MaxBytesToFill < 1) {
3292 ReturnVal |= Error(MaxBytesLoc,
3293 "alignment directive can never be satisfied in this "
3294 "many bytes, ignoring maximum bytes expression");
3298 if (MaxBytesToFill >= Alignment) {
3299 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
3305 // Check whether we should use optimal code alignment for this .align
3307 const MCSection *Section = getStreamer().getCurrentSectionOnly();
3308 assert(Section && "must have section to emit alignment");
3309 bool UseCodeAlign = Section->UseCodeAlign();
3310 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3311 ValueSize == 1 && UseCodeAlign) {
3312 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
3314 // FIXME: Target specific behavior about how the "extra" bytes are filled.
3315 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3322 /// parseDirectiveFile
3323 /// ::= .file filename
3324 /// ::= .file number [directory] filename [md5 checksum] [source source-text]
3325 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
3326 // FIXME: I'm not sure what this is.
3327 int64_t FileNumber = -1;
3328 if (getLexer().is(AsmToken::Integer)) {
3329 FileNumber = getTok().getIntVal();
3333 return TokError("negative file number");
3338 // Usually the directory and filename together, otherwise just the directory.
3339 // Allow the strings to have escaped octal character sequence.
3340 if (check(getTok().isNot(AsmToken::String),
3341 "unexpected token in '.file' directive") ||
3342 parseEscapedString(Path))
3345 StringRef Directory;
3347 std::string FilenameData;
3348 if (getLexer().is(AsmToken::String)) {
3349 if (check(FileNumber == -1,
3350 "explicit path specified, but no file number") ||
3351 parseEscapedString(FilenameData))
3353 Filename = FilenameData;
3359 uint64_t MD5Hi, MD5Lo;
3360 bool HasMD5 = false;
3362 Optional<StringRef> Source;
3363 bool HasSource = false;
3364 std::string SourceString;
3366 while (!parseOptionalToken(AsmToken::EndOfStatement)) {
3368 if (check(getTok().isNot(AsmToken::Identifier),
3369 "unexpected token in '.file' directive") ||
3370 parseIdentifier(Keyword))
3372 if (Keyword == "md5") {
3374 if (check(FileNumber == -1,
3375 "MD5 checksum specified, but no file number") ||
3376 parseHexOcta(*this, MD5Hi, MD5Lo))
3378 } else if (Keyword == "source") {
3380 if (check(FileNumber == -1,
3381 "source specified, but no file number") ||
3382 check(getTok().isNot(AsmToken::String),
3383 "unexpected token in '.file' directive") ||
3384 parseEscapedString(SourceString))
3387 return TokError("unexpected token in '.file' directive");
3391 if (FileNumber == -1) {
3392 // Ignore the directive if there is no number and the target doesn't support
3393 // numberless .file directives. This allows some portability of assembler
3394 // between different object file formats.
3395 if (getContext().getAsmInfo()->hasSingleParameterDotFile())
3396 getStreamer().EmitFileDirective(Filename);
3398 // In case there is a -g option as well as debug info from directive .file,
3399 // we turn off the -g option, directly use the existing debug info instead.
3400 // Throw away any implicit file table for the assembler source.
3401 if (Ctx.getGenDwarfForAssembly()) {
3402 Ctx.getMCDwarfLineTable(0).resetFileTable();
3403 Ctx.setGenDwarfForAssembly(false);
3406 Optional<MD5::MD5Result> CKMem;
3409 for (unsigned i = 0; i != 8; ++i) {
3410 Sum.Bytes[i] = uint8_t(MD5Hi >> ((7 - i) * 8));
3411 Sum.Bytes[i + 8] = uint8_t(MD5Lo >> ((7 - i) * 8));
3416 char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size()));
3417 memcpy(SourceBuf, SourceString.data(), SourceString.size());
3418 Source = StringRef(SourceBuf, SourceString.size());
3420 if (FileNumber == 0) {
3421 if (Ctx.getDwarfVersion() < 5)
3422 return Warning(DirectiveLoc, "file 0 not supported prior to DWARF-5");
3423 getStreamer().emitDwarfFile0Directive(Directory, Filename, CKMem, Source);
3425 Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective(
3426 FileNumber, Directory, Filename, CKMem, Source);
3428 return Error(DirectiveLoc, toString(FileNumOrErr.takeError()));
3430 // Alert the user if there are some .file directives with MD5 and some not.
3431 // But only do that once.
3432 if (!ReportedInconsistentMD5 && !Ctx.isDwarfMD5UsageConsistent(0)) {
3433 ReportedInconsistentMD5 = true;
3434 return Warning(DirectiveLoc, "inconsistent use of MD5 checksums");
3441 /// parseDirectiveLine
3442 /// ::= .line [number]
3443 bool AsmParser::parseDirectiveLine() {
3445 if (getLexer().is(AsmToken::Integer)) {
3446 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3449 // FIXME: Do something with the .line.
3451 if (parseToken(AsmToken::EndOfStatement,
3452 "unexpected token in '.line' directive"))
3458 /// parseDirectiveLoc
3459 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3460 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3461 /// The first number is a file number, must have been previously assigned with
3462 /// a .file directive, the second number is the line number and optionally the
3463 /// third number is a column position (zero if not specified). The remaining
3464 /// optional items are .loc sub-directives.
3465 bool AsmParser::parseDirectiveLoc() {
3466 int64_t FileNumber = 0, LineNumber = 0;
3467 SMLoc Loc = getTok().getLoc();
3468 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3469 check(FileNumber < 1 && Ctx.getDwarfVersion() < 5, Loc,
3470 "file number less than one in '.loc' directive") ||
3471 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3472 "unassigned file number in '.loc' directive"))
3476 if (getLexer().is(AsmToken::Integer)) {
3477 LineNumber = getTok().getIntVal();
3479 return TokError("line number less than zero in '.loc' directive");
3483 int64_t ColumnPos = 0;
3484 if (getLexer().is(AsmToken::Integer)) {
3485 ColumnPos = getTok().getIntVal();
3487 return TokError("column position less than zero in '.loc' directive");
3491 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3493 int64_t Discriminator = 0;
3495 auto parseLocOp = [&]() -> bool {
3497 SMLoc Loc = getTok().getLoc();
3498 if (parseIdentifier(Name))
3499 return TokError("unexpected token in '.loc' directive");
3501 if (Name == "basic_block")
3502 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3503 else if (Name == "prologue_end")
3504 Flags |= DWARF2_FLAG_PROLOGUE_END;
3505 else if (Name == "epilogue_begin")
3506 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3507 else if (Name == "is_stmt") {
3508 Loc = getTok().getLoc();
3509 const MCExpr *Value;
3510 if (parseExpression(Value))
3512 // The expression must be the constant 0 or 1.
3513 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3514 int Value = MCE->getValue();
3516 Flags &= ~DWARF2_FLAG_IS_STMT;
3517 else if (Value == 1)
3518 Flags |= DWARF2_FLAG_IS_STMT;
3520 return Error(Loc, "is_stmt value not 0 or 1");
3522 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3524 } else if (Name == "isa") {
3525 Loc = getTok().getLoc();
3526 const MCExpr *Value;
3527 if (parseExpression(Value))
3529 // The expression must be a constant greater or equal to 0.
3530 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3531 int Value = MCE->getValue();
3533 return Error(Loc, "isa number less than zero");
3536 return Error(Loc, "isa number not a constant value");
3538 } else if (Name == "discriminator") {
3539 if (parseAbsoluteExpression(Discriminator))
3542 return Error(Loc, "unknown sub-directive in '.loc' directive");
3547 if (parseMany(parseLocOp, false /*hasComma*/))
3550 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3551 Isa, Discriminator, StringRef());
3556 /// parseDirectiveStabs
3557 /// ::= .stabs string, number, number, number
3558 bool AsmParser::parseDirectiveStabs() {
3559 return TokError("unsupported directive '.stabs'");
3562 /// parseDirectiveCVFile
3563 /// ::= .cv_file number filename [checksum] [checksumkind]
3564 bool AsmParser::parseDirectiveCVFile() {
3565 SMLoc FileNumberLoc = getTok().getLoc();
3567 std::string Filename;
3568 std::string Checksum;
3569 int64_t ChecksumKind = 0;
3571 if (parseIntToken(FileNumber,
3572 "expected file number in '.cv_file' directive") ||
3573 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3574 check(getTok().isNot(AsmToken::String),
3575 "unexpected token in '.cv_file' directive") ||
3576 parseEscapedString(Filename))
3578 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3579 if (check(getTok().isNot(AsmToken::String),
3580 "unexpected token in '.cv_file' directive") ||
3581 parseEscapedString(Checksum) ||
3582 parseIntToken(ChecksumKind,
3583 "expected checksum kind in '.cv_file' directive") ||
3584 parseToken(AsmToken::EndOfStatement,
3585 "unexpected token in '.cv_file' directive"))
3589 Checksum = fromHex(Checksum);
3590 void *CKMem = Ctx.allocate(Checksum.size(), 1);
3591 memcpy(CKMem, Checksum.data(), Checksum.size());
3592 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
3595 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
3596 static_cast<uint8_t>(ChecksumKind)))
3597 return Error(FileNumberLoc, "file number already allocated");
3602 bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3603 StringRef DirectiveName) {
3605 return parseTokenLoc(Loc) ||
3606 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3608 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3609 "expected function id within range [0, UINT_MAX)");
3612 bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3614 return parseTokenLoc(Loc) ||
3615 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3617 check(FileNumber < 1, Loc, "file number less than one in '" +
3618 DirectiveName + "' directive") ||
3619 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3620 "unassigned file number in '" + DirectiveName + "' directive");
3623 /// parseDirectiveCVFuncId
3624 /// ::= .cv_func_id FunctionId
3626 /// Introduces a function ID that can be used with .cv_loc.
3627 bool AsmParser::parseDirectiveCVFuncId() {
3628 SMLoc FunctionIdLoc = getTok().getLoc();
3631 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3632 parseToken(AsmToken::EndOfStatement,
3633 "unexpected token in '.cv_func_id' directive"))
3636 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
3637 return Error(FunctionIdLoc, "function id already allocated");
3642 /// parseDirectiveCVInlineSiteId
3643 /// ::= .cv_inline_site_id FunctionId
3645 /// "inlined_at" IAFile IALine [IACol]
3647 /// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3648 /// at" source location information for use in the line table of the caller,
3649 /// whether the caller is a real function or another inlined call site.
3650 bool AsmParser::parseDirectiveCVInlineSiteId() {
3651 SMLoc FunctionIdLoc = getTok().getLoc();
3659 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3663 if (check((getLexer().isNot(AsmToken::Identifier) ||
3664 getTok().getIdentifier() != "within"),
3665 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3670 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3674 if (check((getLexer().isNot(AsmToken::Identifier) ||
3675 getTok().getIdentifier() != "inlined_at"),
3676 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3682 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3683 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3687 if (getLexer().is(AsmToken::Integer)) {
3688 IACol = getTok().getIntVal();
3692 if (parseToken(AsmToken::EndOfStatement,
3693 "unexpected token in '.cv_inline_site_id' directive"))
3696 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3697 IALine, IACol, FunctionIdLoc))
3698 return Error(FunctionIdLoc, "function id already allocated");
3703 /// parseDirectiveCVLoc
3704 /// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3706 /// The first number is a file number, must have been previously assigned with
3707 /// a .file directive, the second number is the line number and optionally the
3708 /// third number is a column position (zero if not specified). The remaining
3709 /// optional items are .loc sub-directives.
3710 bool AsmParser::parseDirectiveCVLoc() {
3711 SMLoc DirectiveLoc = getTok().getLoc();
3712 int64_t FunctionId, FileNumber;
3713 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3714 parseCVFileId(FileNumber, ".cv_loc"))
3717 int64_t LineNumber = 0;
3718 if (getLexer().is(AsmToken::Integer)) {
3719 LineNumber = getTok().getIntVal();
3721 return TokError("line number less than zero in '.cv_loc' directive");
3725 int64_t ColumnPos = 0;
3726 if (getLexer().is(AsmToken::Integer)) {
3727 ColumnPos = getTok().getIntVal();
3729 return TokError("column position less than zero in '.cv_loc' directive");
3733 bool PrologueEnd = false;
3734 uint64_t IsStmt = 0;
3736 auto parseOp = [&]() -> bool {
3738 SMLoc Loc = getTok().getLoc();
3739 if (parseIdentifier(Name))
3740 return TokError("unexpected token in '.cv_loc' directive");
3741 if (Name == "prologue_end")
3743 else if (Name == "is_stmt") {
3744 Loc = getTok().getLoc();
3745 const MCExpr *Value;
3746 if (parseExpression(Value))
3748 // The expression must be the constant 0 or 1.
3750 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3751 IsStmt = MCE->getValue();
3754 return Error(Loc, "is_stmt value not 0 or 1");
3756 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3761 if (parseMany(parseOp, false /*hasComma*/))
3764 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
3765 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3770 /// parseDirectiveCVLinetable
3771 /// ::= .cv_linetable FunctionId, FnStart, FnEnd
3772 bool AsmParser::parseDirectiveCVLinetable() {
3774 StringRef FnStartName, FnEndName;
3775 SMLoc Loc = getTok().getLoc();
3776 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
3777 parseToken(AsmToken::Comma,
3778 "unexpected token in '.cv_linetable' directive") ||
3779 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3780 "expected identifier in directive") ||
3781 parseToken(AsmToken::Comma,
3782 "unexpected token in '.cv_linetable' directive") ||
3783 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3784 "expected identifier in directive"))
3787 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3788 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3790 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3794 /// parseDirectiveCVInlineLinetable
3795 /// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
3796 bool AsmParser::parseDirectiveCVInlineLinetable() {
3797 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3798 StringRef FnStartName, FnEndName;
3799 SMLoc Loc = getTok().getLoc();
3800 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
3801 parseTokenLoc(Loc) ||
3804 "expected SourceField in '.cv_inline_linetable' directive") ||
3805 check(SourceFileId <= 0, Loc,
3806 "File id less than zero in '.cv_inline_linetable' directive") ||
3807 parseTokenLoc(Loc) ||
3810 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3811 check(SourceLineNum < 0, Loc,
3812 "Line number less than zero in '.cv_inline_linetable' directive") ||
3813 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3814 "expected identifier in directive") ||
3815 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3816 "expected identifier in directive"))
3819 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3822 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3823 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3824 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3825 SourceLineNum, FnStartSym,
3830 /// parseDirectiveCVDefRange
3831 /// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3832 bool AsmParser::parseDirectiveCVDefRange() {
3834 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3835 while (getLexer().is(AsmToken::Identifier)) {
3836 Loc = getLexer().getLoc();
3837 StringRef GapStartName;
3838 if (parseIdentifier(GapStartName))
3839 return Error(Loc, "expected identifier in directive");
3840 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3842 Loc = getLexer().getLoc();
3843 StringRef GapEndName;
3844 if (parseIdentifier(GapEndName))
3845 return Error(Loc, "expected identifier in directive");
3846 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3848 Ranges.push_back({GapStartSym, GapEndSym});
3851 std::string FixedSizePortion;
3852 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3853 parseEscapedString(FixedSizePortion))
3856 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3860 /// parseDirectiveCVString
3861 /// ::= .cv_stringtable "string"
3862 bool AsmParser::parseDirectiveCVString() {
3864 if (checkForValidSection() || parseEscapedString(Data))
3865 return addErrorSuffix(" in '.cv_string' directive");
3867 // Put the string in the table and emit the offset.
3868 std::pair<StringRef, unsigned> Insertion =
3869 getCVContext().addToStringTable(Data);
3870 getStreamer().EmitIntValue(Insertion.second, 4);
3874 /// parseDirectiveCVStringTable
3875 /// ::= .cv_stringtable
3876 bool AsmParser::parseDirectiveCVStringTable() {
3877 getStreamer().EmitCVStringTableDirective();
3881 /// parseDirectiveCVFileChecksums
3882 /// ::= .cv_filechecksums
3883 bool AsmParser::parseDirectiveCVFileChecksums() {
3884 getStreamer().EmitCVFileChecksumsDirective();
3888 /// parseDirectiveCVFileChecksumOffset
3889 /// ::= .cv_filechecksumoffset fileno
3890 bool AsmParser::parseDirectiveCVFileChecksumOffset() {
3892 if (parseIntToken(FileNo, "expected identifier in directive"))
3894 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3896 getStreamer().EmitCVFileChecksumOffsetDirective(FileNo);
3900 /// parseDirectiveCVFPOData
3901 /// ::= .cv_fpo_data procsym
3902 bool AsmParser::parseDirectiveCVFPOData() {
3903 SMLoc DirLoc = getLexer().getLoc();
3905 if (parseIdentifier(ProcName))
3906 return TokError("expected symbol name");
3907 if (parseEOL("unexpected tokens"))
3908 return addErrorSuffix(" in '.cv_fpo_data' directive");
3909 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
3910 getStreamer().EmitCVFPOData(ProcSym, DirLoc);
3914 /// parseDirectiveCFISections
3915 /// ::= .cfi_sections section [, section]
3916 bool AsmParser::parseDirectiveCFISections() {
3921 if (parseIdentifier(Name))
3922 return TokError("Expected an identifier");
3924 if (Name == ".eh_frame")
3926 else if (Name == ".debug_frame")
3929 if (getLexer().is(AsmToken::Comma)) {
3932 if (parseIdentifier(Name))
3933 return TokError("Expected an identifier");
3935 if (Name == ".eh_frame")
3937 else if (Name == ".debug_frame")
3941 getStreamer().EmitCFISections(EH, Debug);
3945 /// parseDirectiveCFIStartProc
3946 /// ::= .cfi_startproc [simple]
3947 bool AsmParser::parseDirectiveCFIStartProc() {
3949 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3950 if (check(parseIdentifier(Simple) || Simple != "simple",
3951 "unexpected token") ||
3952 parseToken(AsmToken::EndOfStatement))
3953 return addErrorSuffix(" in '.cfi_startproc' directive");
3956 // TODO(kristina): Deal with a corner case of incorrect diagnostic context
3957 // being produced if this directive is emitted as part of preprocessor macro
3958 // expansion which can *ONLY* happen if Clang's cc1as is the API consumer.
3959 // Tools like llvm-mc on the other hand are not affected by it, and report
3960 // correct context information.
3961 getStreamer().EmitCFIStartProc(!Simple.empty(), Lexer.getLoc());
3965 /// parseDirectiveCFIEndProc
3966 /// ::= .cfi_endproc
3967 bool AsmParser::parseDirectiveCFIEndProc() {
3968 getStreamer().EmitCFIEndProc();
3972 /// parse register name or number.
3973 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
3974 SMLoc DirectiveLoc) {
3977 if (getLexer().isNot(AsmToken::Integer)) {
3978 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3980 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
3982 return parseAbsoluteExpression(Register);
3987 /// parseDirectiveCFIDefCfa
3988 /// ::= .cfi_def_cfa register, offset
3989 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3990 int64_t Register = 0, Offset = 0;
3991 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3992 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3993 parseAbsoluteExpression(Offset))
3996 getStreamer().EmitCFIDefCfa(Register, Offset);
4000 /// parseDirectiveCFIDefCfaOffset
4001 /// ::= .cfi_def_cfa_offset offset
4002 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
4004 if (parseAbsoluteExpression(Offset))
4007 getStreamer().EmitCFIDefCfaOffset(Offset);
4011 /// parseDirectiveCFIRegister
4012 /// ::= .cfi_register register, register
4013 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
4014 int64_t Register1 = 0, Register2 = 0;
4015 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
4016 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4017 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
4020 getStreamer().EmitCFIRegister(Register1, Register2);
4024 /// parseDirectiveCFIWindowSave
4025 /// ::= .cfi_window_save
4026 bool AsmParser::parseDirectiveCFIWindowSave() {
4027 getStreamer().EmitCFIWindowSave();
4031 /// parseDirectiveCFIAdjustCfaOffset
4032 /// ::= .cfi_adjust_cfa_offset adjustment
4033 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
4034 int64_t Adjustment = 0;
4035 if (parseAbsoluteExpression(Adjustment))
4038 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
4042 /// parseDirectiveCFIDefCfaRegister
4043 /// ::= .cfi_def_cfa_register register
4044 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
4045 int64_t Register = 0;
4046 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4049 getStreamer().EmitCFIDefCfaRegister(Register);
4053 /// parseDirectiveCFIOffset
4054 /// ::= .cfi_offset register, offset
4055 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
4056 int64_t Register = 0;
4059 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4060 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4061 parseAbsoluteExpression(Offset))
4064 getStreamer().EmitCFIOffset(Register, Offset);
4068 /// parseDirectiveCFIRelOffset
4069 /// ::= .cfi_rel_offset register, offset
4070 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
4071 int64_t Register = 0, Offset = 0;
4073 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4074 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4075 parseAbsoluteExpression(Offset))
4078 getStreamer().EmitCFIRelOffset(Register, Offset);
4082 static bool isValidEncoding(int64_t Encoding) {
4083 if (Encoding & ~0xff)
4086 if (Encoding == dwarf::DW_EH_PE_omit)
4089 const unsigned Format = Encoding & 0xf;
4090 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
4091 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
4092 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
4093 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
4096 const unsigned Application = Encoding & 0x70;
4097 if (Application != dwarf::DW_EH_PE_absptr &&
4098 Application != dwarf::DW_EH_PE_pcrel)
4104 /// parseDirectiveCFIPersonalityOrLsda
4105 /// IsPersonality true for cfi_personality, false for cfi_lsda
4106 /// ::= .cfi_personality encoding, [symbol_name]
4107 /// ::= .cfi_lsda encoding, [symbol_name]
4108 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
4109 int64_t Encoding = 0;
4110 if (parseAbsoluteExpression(Encoding))
4112 if (Encoding == dwarf::DW_EH_PE_omit)
4116 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
4117 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4118 check(parseIdentifier(Name), "expected identifier in directive"))
4121 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4124 getStreamer().EmitCFIPersonality(Sym, Encoding);
4126 getStreamer().EmitCFILsda(Sym, Encoding);
4130 /// parseDirectiveCFIRememberState
4131 /// ::= .cfi_remember_state
4132 bool AsmParser::parseDirectiveCFIRememberState() {
4133 getStreamer().EmitCFIRememberState();
4137 /// parseDirectiveCFIRestoreState
4138 /// ::= .cfi_remember_state
4139 bool AsmParser::parseDirectiveCFIRestoreState() {
4140 getStreamer().EmitCFIRestoreState();
4144 /// parseDirectiveCFISameValue
4145 /// ::= .cfi_same_value register
4146 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
4147 int64_t Register = 0;
4149 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4152 getStreamer().EmitCFISameValue(Register);
4156 /// parseDirectiveCFIRestore
4157 /// ::= .cfi_restore register
4158 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
4159 int64_t Register = 0;
4160 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4163 getStreamer().EmitCFIRestore(Register);
4167 /// parseDirectiveCFIEscape
4168 /// ::= .cfi_escape expression[,...]
4169 bool AsmParser::parseDirectiveCFIEscape() {
4172 if (parseAbsoluteExpression(CurrValue))
4175 Values.push_back((uint8_t)CurrValue);
4177 while (getLexer().is(AsmToken::Comma)) {
4180 if (parseAbsoluteExpression(CurrValue))
4183 Values.push_back((uint8_t)CurrValue);
4186 getStreamer().EmitCFIEscape(Values);
4190 /// parseDirectiveCFIReturnColumn
4191 /// ::= .cfi_return_column register
4192 bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4193 int64_t Register = 0;
4194 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4196 getStreamer().EmitCFIReturnColumn(Register);
4200 /// parseDirectiveCFISignalFrame
4201 /// ::= .cfi_signal_frame
4202 bool AsmParser::parseDirectiveCFISignalFrame() {
4203 if (parseToken(AsmToken::EndOfStatement,
4204 "unexpected token in '.cfi_signal_frame'"))
4207 getStreamer().EmitCFISignalFrame();
4211 /// parseDirectiveCFIUndefined
4212 /// ::= .cfi_undefined register
4213 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
4214 int64_t Register = 0;
4216 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4219 getStreamer().EmitCFIUndefined(Register);
4223 /// parseDirectiveAltmacro
4226 bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4227 if (getLexer().isNot(AsmToken::EndOfStatement))
4228 return TokError("unexpected token in '" + Directive + "' directive");
4229 AltMacroMode = (Directive == ".altmacro");
4233 /// parseDirectiveMacrosOnOff
4236 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
4237 if (parseToken(AsmToken::EndOfStatement,
4238 "unexpected token in '" + Directive + "' directive"))
4241 setMacrosEnabled(Directive == ".macros_on");
4245 /// parseDirectiveMacro
4246 /// ::= .macro name[,] [parameters]
4247 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
4249 if (parseIdentifier(Name))
4250 return TokError("expected identifier in '.macro' directive");
4252 if (getLexer().is(AsmToken::Comma))
4255 MCAsmMacroParameters Parameters;
4256 while (getLexer().isNot(AsmToken::EndOfStatement)) {
4258 if (!Parameters.empty() && Parameters.back().Vararg)
4259 return Error(Lexer.getLoc(),
4260 "Vararg parameter '" + Parameters.back().Name +
4261 "' should be last one in the list of parameters.");
4263 MCAsmMacroParameter Parameter;
4264 if (parseIdentifier(Parameter.Name))
4265 return TokError("expected identifier in '.macro' directive");
4267 // Emit an error if two (or more) named parameters share the same name
4268 for (const MCAsmMacroParameter& CurrParam : Parameters)
4269 if (CurrParam.Name.equals(Parameter.Name))
4270 return TokError("macro '" + Name + "' has multiple parameters"
4271 " named '" + Parameter.Name + "'");
4273 if (Lexer.is(AsmToken::Colon)) {
4274 Lex(); // consume ':'
4277 StringRef Qualifier;
4279 QualLoc = Lexer.getLoc();
4280 if (parseIdentifier(Qualifier))
4281 return Error(QualLoc, "missing parameter qualifier for "
4282 "'" + Parameter.Name + "' in macro '" + Name + "'");
4284 if (Qualifier == "req")
4285 Parameter.Required = true;
4286 else if (Qualifier == "vararg")
4287 Parameter.Vararg = true;
4289 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4290 "for '" + Parameter.Name + "' in macro '" + Name + "'");
4293 if (getLexer().is(AsmToken::Equal)) {
4298 ParamLoc = Lexer.getLoc();
4299 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
4302 if (Parameter.Required)
4303 Warning(ParamLoc, "pointless default value for required parameter "
4304 "'" + Parameter.Name + "' in macro '" + Name + "'");
4307 Parameters.push_back(std::move(Parameter));
4309 if (getLexer().is(AsmToken::Comma))
4313 // Eat just the end of statement.
4316 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
4317 AsmToken EndToken, StartToken = getTok();
4318 unsigned MacroDepth = 0;
4319 // Lex the macro definition.
4321 // Ignore Lexing errors in macros.
4322 while (Lexer.is(AsmToken::Error)) {
4326 // Check whether we have reached the end of the file.
4327 if (getLexer().is(AsmToken::Eof))
4328 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4330 // Otherwise, check whether we have reach the .endmacro.
4331 if (getLexer().is(AsmToken::Identifier)) {
4332 if (getTok().getIdentifier() == ".endm" ||
4333 getTok().getIdentifier() == ".endmacro") {
4334 if (MacroDepth == 0) { // Outermost macro.
4335 EndToken = getTok();
4337 if (getLexer().isNot(AsmToken::EndOfStatement))
4338 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4342 // Otherwise we just found the end of an inner macro.
4345 } else if (getTok().getIdentifier() == ".macro") {
4346 // We allow nested macros. Those aren't instantiated until the outermost
4347 // macro is expanded so just ignore them for now.
4352 // Otherwise, scan til the end of the statement.
4353 eatToEndOfStatement();
4356 if (getContext().lookupMacro(Name)) {
4357 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4360 const char *BodyStart = StartToken.getLoc().getPointer();
4361 const char *BodyEnd = EndToken.getLoc().getPointer();
4362 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4363 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
4364 MCAsmMacro Macro(Name, Body, std::move(Parameters));
4365 DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n";
4367 getContext().defineMacro(Name, std::move(Macro));
4371 /// checkForBadMacro
4373 /// With the support added for named parameters there may be code out there that
4374 /// is transitioning from positional parameters. In versions of gas that did
4375 /// not support named parameters they would be ignored on the macro definition.
4376 /// But to support both styles of parameters this is not possible so if a macro
4377 /// definition has named parameters but does not use them and has what appears
4378 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4379 /// warning that the positional parameter found in body which have no effect.
4380 /// Hoping the developer will either remove the named parameters from the macro
4381 /// definition so the positional parameters get used if that was what was
4382 /// intended or change the macro to use the named parameters. It is possible
4383 /// this warning will trigger when the none of the named parameters are used
4384 /// and the strings like $1 are infact to simply to be passed trough unchanged.
4385 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
4387 ArrayRef<MCAsmMacroParameter> Parameters) {
4388 // If this macro is not defined with named parameters the warning we are
4389 // checking for here doesn't apply.
4390 unsigned NParameters = Parameters.size();
4391 if (NParameters == 0)
4394 bool NamedParametersFound = false;
4395 bool PositionalParametersFound = false;
4397 // Look at the body of the macro for use of both the named parameters and what
4398 // are likely to be positional parameters. This is what expandMacro() is
4399 // doing when it finds the parameters in the body.
4400 while (!Body.empty()) {
4401 // Scan for the next possible parameter.
4402 std::size_t End = Body.size(), Pos = 0;
4403 for (; Pos != End; ++Pos) {
4404 // Check for a substitution or escape.
4405 // This macro is defined with parameters, look for \foo, \bar, etc.
4406 if (Body[Pos] == '\\' && Pos + 1 != End)
4409 // This macro should have parameters, but look for $0, $1, ..., $n too.
4410 if (Body[Pos] != '$' || Pos + 1 == End)
4412 char Next = Body[Pos + 1];
4413 if (Next == '$' || Next == 'n' ||
4414 isdigit(static_cast<unsigned char>(Next)))
4418 // Check if we reached the end.
4422 if (Body[Pos] == '$') {
4423 switch (Body[Pos + 1]) {
4428 // $n => number of arguments
4430 PositionalParametersFound = true;
4433 // $[0-9] => argument
4435 PositionalParametersFound = true;
4441 unsigned I = Pos + 1;
4442 while (isIdentifierChar(Body[I]) && I + 1 != End)
4445 const char *Begin = Body.data() + Pos + 1;
4446 StringRef Argument(Begin, I - (Pos + 1));
4448 for (; Index < NParameters; ++Index)
4449 if (Parameters[Index].Name == Argument)
4452 if (Index == NParameters) {
4453 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4459 NamedParametersFound = true;
4460 Pos += 1 + Argument.size();
4463 // Update the scan point.
4464 Body = Body.substr(Pos);
4467 if (!NamedParametersFound && PositionalParametersFound)
4468 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4469 "used in macro body, possible positional parameter "
4470 "found in body which will have no effect");
4473 /// parseDirectiveExitMacro
4475 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
4476 if (parseToken(AsmToken::EndOfStatement,
4477 "unexpected token in '" + Directive + "' directive"))
4480 if (!isInsideMacroInstantiation())
4481 return TokError("unexpected '" + Directive + "' in file, "
4482 "no current macro definition");
4484 // Exit all conditionals that are active in the current macro.
4485 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4486 TheCondState = TheCondStack.back();
4487 TheCondStack.pop_back();
4494 /// parseDirectiveEndMacro
4497 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
4498 if (getLexer().isNot(AsmToken::EndOfStatement))
4499 return TokError("unexpected token in '" + Directive + "' directive");
4501 // If we are inside a macro instantiation, terminate the current
4503 if (isInsideMacroInstantiation()) {
4508 // Otherwise, this .endmacro is a stray entry in the file; well formed
4509 // .endmacro directives are handled during the macro definition parsing.
4510 return TokError("unexpected '" + Directive + "' in file, "
4511 "no current macro definition");
4514 /// parseDirectivePurgeMacro
4516 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
4519 if (parseTokenLoc(Loc) ||
4520 check(parseIdentifier(Name), Loc,
4521 "expected identifier in '.purgem' directive") ||
4522 parseToken(AsmToken::EndOfStatement,
4523 "unexpected token in '.purgem' directive"))
4526 if (!getContext().lookupMacro(Name))
4527 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4529 getContext().undefineMacro(Name);
4530 DEBUG_WITH_TYPE("asm-macros", dbgs()
4531 << "Un-defining macro: " << Name << "\n");
4535 /// parseDirectiveBundleAlignMode
4536 /// ::= {.bundle_align_mode} expression
4537 bool AsmParser::parseDirectiveBundleAlignMode() {
4538 // Expect a single argument: an expression that evaluates to a constant
4539 // in the inclusive range 0-30.
4540 SMLoc ExprLoc = getLexer().getLoc();
4541 int64_t AlignSizePow2;
4542 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
4543 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4544 "in '.bundle_align_mode' "
4546 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4547 "invalid bundle alignment size (expected between 0 and 30)"))
4550 // Because of AlignSizePow2's verified range we can safely truncate it to
4552 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4556 /// parseDirectiveBundleLock
4557 /// ::= {.bundle_lock} [align_to_end]
4558 bool AsmParser::parseDirectiveBundleLock() {
4559 if (checkForValidSection())
4561 bool AlignToEnd = false;
4564 SMLoc Loc = getTok().getLoc();
4565 const char *kInvalidOptionError =
4566 "invalid option for '.bundle_lock' directive";
4568 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4569 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4570 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
4571 parseToken(AsmToken::EndOfStatement,
4572 "unexpected token after '.bundle_lock' directive option"))
4577 getStreamer().EmitBundleLock(AlignToEnd);
4581 /// parseDirectiveBundleLock
4582 /// ::= {.bundle_lock}
4583 bool AsmParser::parseDirectiveBundleUnlock() {
4584 if (checkForValidSection() ||
4585 parseToken(AsmToken::EndOfStatement,
4586 "unexpected token in '.bundle_unlock' directive"))
4589 getStreamer().EmitBundleUnlock();
4593 /// parseDirectiveSpace
4594 /// ::= (.skip | .space) expression [ , expression ]
4595 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
4596 SMLoc NumBytesLoc = Lexer.getLoc();
4597 const MCExpr *NumBytes;
4598 if (checkForValidSection() || parseExpression(NumBytes))
4601 int64_t FillExpr = 0;
4602 if (parseOptionalToken(AsmToken::Comma))
4603 if (parseAbsoluteExpression(FillExpr))
4604 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4605 if (parseToken(AsmToken::EndOfStatement))
4606 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4608 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
4609 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
4614 /// parseDirectiveDCB
4615 /// ::= .dcb.{b, l, w} expression, expression
4616 bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
4617 SMLoc NumValuesLoc = Lexer.getLoc();
4619 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4622 if (NumValues < 0) {
4623 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4627 if (parseToken(AsmToken::Comma,
4628 "unexpected token in '" + Twine(IDVal) + "' directive"))
4631 const MCExpr *Value;
4632 SMLoc ExprLoc = getLexer().getLoc();
4633 if (parseExpression(Value))
4636 // Special case constant expressions to match code generator.
4637 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4638 assert(Size <= 8 && "Invalid size");
4639 uint64_t IntValue = MCE->getValue();
4640 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4641 return Error(ExprLoc, "literal value out of range for directive");
4642 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4643 getStreamer().EmitIntValue(IntValue, Size);
4645 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4646 getStreamer().EmitValue(Value, Size, ExprLoc);
4649 if (parseToken(AsmToken::EndOfStatement,
4650 "unexpected token in '" + Twine(IDVal) + "' directive"))
4656 /// parseDirectiveRealDCB
4657 /// ::= .dcb.{d, s} expression, expression
4658 bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
4659 SMLoc NumValuesLoc = Lexer.getLoc();
4661 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4664 if (NumValues < 0) {
4665 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4669 if (parseToken(AsmToken::Comma,
4670 "unexpected token in '" + Twine(IDVal) + "' directive"))
4674 if (parseRealValue(Semantics, AsInt))
4677 if (parseToken(AsmToken::EndOfStatement,
4678 "unexpected token in '" + Twine(IDVal) + "' directive"))
4681 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4682 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4683 AsInt.getBitWidth() / 8);
4688 /// parseDirectiveDS
4689 /// ::= .ds.{b, d, l, p, s, w, x} expression
4690 bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
4691 SMLoc NumValuesLoc = Lexer.getLoc();
4693 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4696 if (NumValues < 0) {
4697 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4701 if (parseToken(AsmToken::EndOfStatement,
4702 "unexpected token in '" + Twine(IDVal) + "' directive"))
4705 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4706 getStreamer().emitFill(Size, 0);
4711 /// parseDirectiveLEB128
4712 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
4713 bool AsmParser::parseDirectiveLEB128(bool Signed) {
4714 if (checkForValidSection())
4717 auto parseOp = [&]() -> bool {
4718 const MCExpr *Value;
4719 if (parseExpression(Value))
4722 getStreamer().EmitSLEB128Value(Value);
4724 getStreamer().EmitULEB128Value(Value);
4728 if (parseMany(parseOp))
4729 return addErrorSuffix(" in directive");
4734 /// parseDirectiveSymbolAttribute
4735 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
4736 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
4737 auto parseOp = [&]() -> bool {
4739 SMLoc Loc = getTok().getLoc();
4740 if (parseIdentifier(Name))
4741 return Error(Loc, "expected identifier");
4742 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4744 // Assembler local symbols don't make any sense here. Complain loudly.
4745 if (Sym->isTemporary())
4746 return Error(Loc, "non-local symbol required");
4748 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4749 return Error(Loc, "unable to emit symbol attribute");
4753 if (parseMany(parseOp))
4754 return addErrorSuffix(" in directive");
4758 /// parseDirectiveComm
4759 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
4760 bool AsmParser::parseDirectiveComm(bool IsLocal) {
4761 if (checkForValidSection())
4764 SMLoc IDLoc = getLexer().getLoc();
4766 if (parseIdentifier(Name))
4767 return TokError("expected identifier in directive");
4769 // Handle the identifier as the key symbol.
4770 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4772 if (getLexer().isNot(AsmToken::Comma))
4773 return TokError("unexpected token in directive");
4777 SMLoc SizeLoc = getLexer().getLoc();
4778 if (parseAbsoluteExpression(Size))
4781 int64_t Pow2Alignment = 0;
4782 SMLoc Pow2AlignmentLoc;
4783 if (getLexer().is(AsmToken::Comma)) {
4785 Pow2AlignmentLoc = getLexer().getLoc();
4786 if (parseAbsoluteExpression(Pow2Alignment))
4789 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4790 if (IsLocal && LCOMM == LCOMM::NoAlignment)
4791 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4793 // If this target takes alignments in bytes (not log) validate and convert.
4794 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4795 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
4796 if (!isPowerOf2_64(Pow2Alignment))
4797 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4798 Pow2Alignment = Log2_64(Pow2Alignment);
4802 if (parseToken(AsmToken::EndOfStatement,
4803 "unexpected token in '.comm' or '.lcomm' directive"))
4806 // NOTE: a size of zero for a .comm should create a undefined symbol
4807 // but a size of .lcomm creates a bss symbol of size zero.
4809 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
4810 "be less than zero");
4812 // NOTE: The alignment in the directive is a power of 2 value, the assembler
4813 // may internally end up wanting an alignment in bytes.
4814 // FIXME: Diagnose overflow.
4815 if (Pow2Alignment < 0)
4816 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
4817 "alignment, can't be less than zero");
4819 Sym->redefineIfPossible();
4820 if (!Sym->isUndefined())
4821 return Error(IDLoc, "invalid symbol redefinition");
4823 // Create the Symbol as a common or local common with Size and Pow2Alignment
4825 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4829 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4833 /// parseDirectiveAbort
4834 /// ::= .abort [... message ...]
4835 bool AsmParser::parseDirectiveAbort() {
4836 // FIXME: Use loc from directive.
4837 SMLoc Loc = getLexer().getLoc();
4839 StringRef Str = parseStringToEndOfStatement();
4840 if (parseToken(AsmToken::EndOfStatement,
4841 "unexpected token in '.abort' directive"))
4845 return Error(Loc, ".abort detected. Assembly stopping.");
4847 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
4848 // FIXME: Actually abort assembly here.
4853 /// parseDirectiveInclude
4854 /// ::= .include "filename"
4855 bool AsmParser::parseDirectiveInclude() {
4856 // Allow the strings to have escaped octal character sequence.
4857 std::string Filename;
4858 SMLoc IncludeLoc = getTok().getLoc();
4860 if (check(getTok().isNot(AsmToken::String),
4861 "expected string in '.include' directive") ||
4862 parseEscapedString(Filename) ||
4863 check(getTok().isNot(AsmToken::EndOfStatement),
4864 "unexpected token in '.include' directive") ||
4865 // Attempt to switch the lexer to the included file before consuming the
4866 // end of statement to avoid losing it when we switch.
4867 check(enterIncludeFile(Filename), IncludeLoc,
4868 "Could not find include file '" + Filename + "'"))
4874 /// parseDirectiveIncbin
4875 /// ::= .incbin "filename" [ , skip [ , count ] ]
4876 bool AsmParser::parseDirectiveIncbin() {
4877 // Allow the strings to have escaped octal character sequence.
4878 std::string Filename;
4879 SMLoc IncbinLoc = getTok().getLoc();
4880 if (check(getTok().isNot(AsmToken::String),
4881 "expected string in '.incbin' directive") ||
4882 parseEscapedString(Filename))
4886 const MCExpr *Count = nullptr;
4887 SMLoc SkipLoc, CountLoc;
4888 if (parseOptionalToken(AsmToken::Comma)) {
4889 // The skip expression can be omitted while specifying the count, e.g:
4890 // .incbin "filename",,4
4891 if (getTok().isNot(AsmToken::Comma)) {
4892 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4895 if (parseOptionalToken(AsmToken::Comma)) {
4896 CountLoc = getTok().getLoc();
4897 if (parseExpression(Count))
4902 if (parseToken(AsmToken::EndOfStatement,
4903 "unexpected token in '.incbin' directive"))
4906 if (check(Skip < 0, SkipLoc, "skip is negative"))
4909 // Attempt to process the included file.
4910 if (processIncbinFile(Filename, Skip, Count, CountLoc))
4911 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
4915 /// parseDirectiveIf
4916 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
4917 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
4918 TheCondStack.push_back(TheCondState);
4919 TheCondState.TheCond = AsmCond::IfCond;
4920 if (TheCondState.Ignore) {
4921 eatToEndOfStatement();
4924 if (parseAbsoluteExpression(ExprValue) ||
4925 parseToken(AsmToken::EndOfStatement,
4926 "unexpected token in '.if' directive"))
4931 llvm_unreachable("unsupported directive");
4936 ExprValue = ExprValue == 0;
4939 ExprValue = ExprValue >= 0;
4942 ExprValue = ExprValue > 0;
4945 ExprValue = ExprValue <= 0;
4948 ExprValue = ExprValue < 0;
4952 TheCondState.CondMet = ExprValue;
4953 TheCondState.Ignore = !TheCondState.CondMet;
4959 /// parseDirectiveIfb
4961 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
4962 TheCondStack.push_back(TheCondState);
4963 TheCondState.TheCond = AsmCond::IfCond;
4965 if (TheCondState.Ignore) {
4966 eatToEndOfStatement();
4968 StringRef Str = parseStringToEndOfStatement();
4970 if (parseToken(AsmToken::EndOfStatement,
4971 "unexpected token in '.ifb' directive"))
4974 TheCondState.CondMet = ExpectBlank == Str.empty();
4975 TheCondState.Ignore = !TheCondState.CondMet;
4981 /// parseDirectiveIfc
4982 /// ::= .ifc string1, string2
4983 /// ::= .ifnc string1, string2
4984 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
4985 TheCondStack.push_back(TheCondState);
4986 TheCondState.TheCond = AsmCond::IfCond;
4988 if (TheCondState.Ignore) {
4989 eatToEndOfStatement();
4991 StringRef Str1 = parseStringToComma();
4993 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4996 StringRef Str2 = parseStringToEndOfStatement();
4998 if (parseToken(AsmToken::EndOfStatement,
4999 "unexpected token in '.ifc' directive"))
5002 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
5003 TheCondState.Ignore = !TheCondState.CondMet;
5009 /// parseDirectiveIfeqs
5010 /// ::= .ifeqs string1, string2
5011 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
5012 if (Lexer.isNot(AsmToken::String)) {
5014 return TokError("expected string parameter for '.ifeqs' directive");
5015 return TokError("expected string parameter for '.ifnes' directive");
5018 StringRef String1 = getTok().getStringContents();
5021 if (Lexer.isNot(AsmToken::Comma)) {
5024 "expected comma after first string for '.ifeqs' directive");
5025 return TokError("expected comma after first string for '.ifnes' directive");
5030 if (Lexer.isNot(AsmToken::String)) {
5032 return TokError("expected string parameter for '.ifeqs' directive");
5033 return TokError("expected string parameter for '.ifnes' directive");
5036 StringRef String2 = getTok().getStringContents();
5039 TheCondStack.push_back(TheCondState);
5040 TheCondState.TheCond = AsmCond::IfCond;
5041 TheCondState.CondMet = ExpectEqual == (String1 == String2);
5042 TheCondState.Ignore = !TheCondState.CondMet;
5047 /// parseDirectiveIfdef
5048 /// ::= .ifdef symbol
5049 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
5051 TheCondStack.push_back(TheCondState);
5052 TheCondState.TheCond = AsmCond::IfCond;
5054 if (TheCondState.Ignore) {
5055 eatToEndOfStatement();
5057 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
5058 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
5061 MCSymbol *Sym = getContext().lookupSymbol(Name);
5064 TheCondState.CondMet = (Sym && !Sym->isUndefined(false));
5066 TheCondState.CondMet = (!Sym || Sym->isUndefined(false));
5067 TheCondState.Ignore = !TheCondState.CondMet;
5073 /// parseDirectiveElseIf
5074 /// ::= .elseif expression
5075 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
5076 if (TheCondState.TheCond != AsmCond::IfCond &&
5077 TheCondState.TheCond != AsmCond::ElseIfCond)
5078 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
5079 " .if or an .elseif");
5080 TheCondState.TheCond = AsmCond::ElseIfCond;
5082 bool LastIgnoreState = false;
5083 if (!TheCondStack.empty())
5084 LastIgnoreState = TheCondStack.back().Ignore;
5085 if (LastIgnoreState || TheCondState.CondMet) {
5086 TheCondState.Ignore = true;
5087 eatToEndOfStatement();
5090 if (parseAbsoluteExpression(ExprValue))
5093 if (parseToken(AsmToken::EndOfStatement,
5094 "unexpected token in '.elseif' directive"))
5097 TheCondState.CondMet = ExprValue;
5098 TheCondState.Ignore = !TheCondState.CondMet;
5104 /// parseDirectiveElse
5106 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
5107 if (parseToken(AsmToken::EndOfStatement,
5108 "unexpected token in '.else' directive"))
5111 if (TheCondState.TheCond != AsmCond::IfCond &&
5112 TheCondState.TheCond != AsmCond::ElseIfCond)
5113 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
5114 " an .if or an .elseif");
5115 TheCondState.TheCond = AsmCond::ElseCond;
5116 bool LastIgnoreState = false;
5117 if (!TheCondStack.empty())
5118 LastIgnoreState = TheCondStack.back().Ignore;
5119 if (LastIgnoreState || TheCondState.CondMet)
5120 TheCondState.Ignore = true;
5122 TheCondState.Ignore = false;
5127 /// parseDirectiveEnd
5129 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
5130 if (parseToken(AsmToken::EndOfStatement,
5131 "unexpected token in '.end' directive"))
5134 while (Lexer.isNot(AsmToken::Eof))
5140 /// parseDirectiveError
5142 /// ::= .error [string]
5143 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
5144 if (!TheCondStack.empty()) {
5145 if (TheCondStack.back().Ignore) {
5146 eatToEndOfStatement();
5152 return Error(L, ".err encountered");
5154 StringRef Message = ".error directive invoked in source file";
5155 if (Lexer.isNot(AsmToken::EndOfStatement)) {
5156 if (Lexer.isNot(AsmToken::String))
5157 return TokError(".error argument must be a string");
5159 Message = getTok().getStringContents();
5163 return Error(L, Message);
5166 /// parseDirectiveWarning
5167 /// ::= .warning [string]
5168 bool AsmParser::parseDirectiveWarning(SMLoc L) {
5169 if (!TheCondStack.empty()) {
5170 if (TheCondStack.back().Ignore) {
5171 eatToEndOfStatement();
5176 StringRef Message = ".warning directive invoked in source file";
5178 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
5179 if (Lexer.isNot(AsmToken::String))
5180 return TokError(".warning argument must be a string");
5182 Message = getTok().getStringContents();
5184 if (parseToken(AsmToken::EndOfStatement,
5185 "expected end of statement in '.warning' directive"))
5189 return Warning(L, Message);
5192 /// parseDirectiveEndIf
5194 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
5195 if (parseToken(AsmToken::EndOfStatement,
5196 "unexpected token in '.endif' directive"))
5199 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
5200 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5202 if (!TheCondStack.empty()) {
5203 TheCondState = TheCondStack.back();
5204 TheCondStack.pop_back();
5210 void AsmParser::initializeDirectiveKindMap() {
5211 DirectiveKindMap[".set"] = DK_SET;
5212 DirectiveKindMap[".equ"] = DK_EQU;
5213 DirectiveKindMap[".equiv"] = DK_EQUIV;
5214 DirectiveKindMap[".ascii"] = DK_ASCII;
5215 DirectiveKindMap[".asciz"] = DK_ASCIZ;
5216 DirectiveKindMap[".string"] = DK_STRING;
5217 DirectiveKindMap[".byte"] = DK_BYTE;
5218 DirectiveKindMap[".short"] = DK_SHORT;
5219 DirectiveKindMap[".value"] = DK_VALUE;
5220 DirectiveKindMap[".2byte"] = DK_2BYTE;
5221 DirectiveKindMap[".long"] = DK_LONG;
5222 DirectiveKindMap[".int"] = DK_INT;
5223 DirectiveKindMap[".4byte"] = DK_4BYTE;
5224 DirectiveKindMap[".quad"] = DK_QUAD;
5225 DirectiveKindMap[".8byte"] = DK_8BYTE;
5226 DirectiveKindMap[".octa"] = DK_OCTA;
5227 DirectiveKindMap[".single"] = DK_SINGLE;
5228 DirectiveKindMap[".float"] = DK_FLOAT;
5229 DirectiveKindMap[".double"] = DK_DOUBLE;
5230 DirectiveKindMap[".align"] = DK_ALIGN;
5231 DirectiveKindMap[".align32"] = DK_ALIGN32;
5232 DirectiveKindMap[".balign"] = DK_BALIGN;
5233 DirectiveKindMap[".balignw"] = DK_BALIGNW;
5234 DirectiveKindMap[".balignl"] = DK_BALIGNL;
5235 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5236 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5237 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5238 DirectiveKindMap[".org"] = DK_ORG;
5239 DirectiveKindMap[".fill"] = DK_FILL;
5240 DirectiveKindMap[".zero"] = DK_ZERO;
5241 DirectiveKindMap[".extern"] = DK_EXTERN;
5242 DirectiveKindMap[".globl"] = DK_GLOBL;
5243 DirectiveKindMap[".global"] = DK_GLOBAL;
5244 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5245 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5246 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5247 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5248 DirectiveKindMap[".reference"] = DK_REFERENCE;
5249 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5250 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5251 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
5252 DirectiveKindMap[".cold"] = DK_COLD;
5253 DirectiveKindMap[".comm"] = DK_COMM;
5254 DirectiveKindMap[".common"] = DK_COMMON;
5255 DirectiveKindMap[".lcomm"] = DK_LCOMM;
5256 DirectiveKindMap[".abort"] = DK_ABORT;
5257 DirectiveKindMap[".include"] = DK_INCLUDE;
5258 DirectiveKindMap[".incbin"] = DK_INCBIN;
5259 DirectiveKindMap[".code16"] = DK_CODE16;
5260 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5261 DirectiveKindMap[".rept"] = DK_REPT;
5262 DirectiveKindMap[".rep"] = DK_REPT;
5263 DirectiveKindMap[".irp"] = DK_IRP;
5264 DirectiveKindMap[".irpc"] = DK_IRPC;
5265 DirectiveKindMap[".endr"] = DK_ENDR;
5266 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5267 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5268 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5269 DirectiveKindMap[".if"] = DK_IF;
5270 DirectiveKindMap[".ifeq"] = DK_IFEQ;
5271 DirectiveKindMap[".ifge"] = DK_IFGE;
5272 DirectiveKindMap[".ifgt"] = DK_IFGT;
5273 DirectiveKindMap[".ifle"] = DK_IFLE;
5274 DirectiveKindMap[".iflt"] = DK_IFLT;
5275 DirectiveKindMap[".ifne"] = DK_IFNE;
5276 DirectiveKindMap[".ifb"] = DK_IFB;
5277 DirectiveKindMap[".ifnb"] = DK_IFNB;
5278 DirectiveKindMap[".ifc"] = DK_IFC;
5279 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
5280 DirectiveKindMap[".ifnc"] = DK_IFNC;
5281 DirectiveKindMap[".ifnes"] = DK_IFNES;
5282 DirectiveKindMap[".ifdef"] = DK_IFDEF;
5283 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5284 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5285 DirectiveKindMap[".elseif"] = DK_ELSEIF;
5286 DirectiveKindMap[".else"] = DK_ELSE;
5287 DirectiveKindMap[".end"] = DK_END;
5288 DirectiveKindMap[".endif"] = DK_ENDIF;
5289 DirectiveKindMap[".skip"] = DK_SKIP;
5290 DirectiveKindMap[".space"] = DK_SPACE;
5291 DirectiveKindMap[".file"] = DK_FILE;
5292 DirectiveKindMap[".line"] = DK_LINE;
5293 DirectiveKindMap[".loc"] = DK_LOC;
5294 DirectiveKindMap[".stabs"] = DK_STABS;
5295 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
5296 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
5297 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5298 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
5299 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
5300 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
5301 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
5302 DirectiveKindMap[".cv_string"] = DK_CV_STRING;
5303 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5304 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
5305 DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
5306 DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA;
5307 DirectiveKindMap[".sleb128"] = DK_SLEB128;
5308 DirectiveKindMap[".uleb128"] = DK_ULEB128;
5309 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5310 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5311 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5312 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5313 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5314 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5315 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5316 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5317 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5318 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5319 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5320 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5321 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5322 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5323 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5324 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
5325 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
5326 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5327 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5328 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
5329 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
5330 DirectiveKindMap[".cfi_b_key_frame"] = DK_CFI_B_KEY_FRAME;
5331 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5332 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5333 DirectiveKindMap[".macro"] = DK_MACRO;
5334 DirectiveKindMap[".exitm"] = DK_EXITM;
5335 DirectiveKindMap[".endm"] = DK_ENDM;
5336 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5337 DirectiveKindMap[".purgem"] = DK_PURGEM;
5338 DirectiveKindMap[".err"] = DK_ERR;
5339 DirectiveKindMap[".error"] = DK_ERROR;
5340 DirectiveKindMap[".warning"] = DK_WARNING;
5341 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5342 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
5343 DirectiveKindMap[".reloc"] = DK_RELOC;
5344 DirectiveKindMap[".dc"] = DK_DC;
5345 DirectiveKindMap[".dc.a"] = DK_DC_A;
5346 DirectiveKindMap[".dc.b"] = DK_DC_B;
5347 DirectiveKindMap[".dc.d"] = DK_DC_D;
5348 DirectiveKindMap[".dc.l"] = DK_DC_L;
5349 DirectiveKindMap[".dc.s"] = DK_DC_S;
5350 DirectiveKindMap[".dc.w"] = DK_DC_W;
5351 DirectiveKindMap[".dc.x"] = DK_DC_X;
5352 DirectiveKindMap[".dcb"] = DK_DCB;
5353 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5354 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5355 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5356 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5357 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5358 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
5359 DirectiveKindMap[".ds"] = DK_DS;
5360 DirectiveKindMap[".ds.b"] = DK_DS_B;
5361 DirectiveKindMap[".ds.d"] = DK_DS_D;
5362 DirectiveKindMap[".ds.l"] = DK_DS_L;
5363 DirectiveKindMap[".ds.p"] = DK_DS_P;
5364 DirectiveKindMap[".ds.s"] = DK_DS_S;
5365 DirectiveKindMap[".ds.w"] = DK_DS_W;
5366 DirectiveKindMap[".ds.x"] = DK_DS_X;
5367 DirectiveKindMap[".print"] = DK_PRINT;
5368 DirectiveKindMap[".addrsig"] = DK_ADDRSIG;
5369 DirectiveKindMap[".addrsig_sym"] = DK_ADDRSIG_SYM;
5372 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
5373 AsmToken EndToken, StartToken = getTok();
5375 unsigned NestLevel = 0;
5377 // Check whether we have reached the end of the file.
5378 if (getLexer().is(AsmToken::Eof)) {
5379 printError(DirectiveLoc, "no matching '.endr' in definition");
5383 if (Lexer.is(AsmToken::Identifier) &&
5384 (getTok().getIdentifier() == ".rep" ||
5385 getTok().getIdentifier() == ".rept" ||
5386 getTok().getIdentifier() == ".irp" ||
5387 getTok().getIdentifier() == ".irpc")) {
5391 // Otherwise, check whether we have reached the .endr.
5392 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
5393 if (NestLevel == 0) {
5394 EndToken = getTok();
5396 if (Lexer.isNot(AsmToken::EndOfStatement)) {
5397 printError(getTok().getLoc(),
5398 "unexpected token in '.endr' directive");
5406 // Otherwise, scan till the end of the statement.
5407 eatToEndOfStatement();
5410 const char *BodyStart = StartToken.getLoc().getPointer();
5411 const char *BodyEnd = EndToken.getLoc().getPointer();
5412 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5414 // We Are Anonymous.
5415 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
5416 return &MacroLikeBodies.back();
5419 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
5420 raw_svector_ostream &OS) {
5423 std::unique_ptr<MemoryBuffer> Instantiation =
5424 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
5426 // Create the macro instantiation object and add to the current macro
5427 // instantiation stack.
5428 MacroInstantiation *MI = new MacroInstantiation(
5429 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
5430 ActiveMacros.push_back(MI);
5432 // Jump to the macro instantiation and prime the lexer.
5433 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
5434 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
5438 /// parseDirectiveRept
5439 /// ::= .rep | .rept count
5440 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
5441 const MCExpr *CountExpr;
5442 SMLoc CountLoc = getTok().getLoc();
5443 if (parseExpression(CountExpr))
5447 if (!CountExpr->evaluateAsAbsolute(Count, getStreamer().getAssemblerPtr())) {
5448 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5451 if (check(Count < 0, CountLoc, "Count is negative") ||
5452 parseToken(AsmToken::EndOfStatement,
5453 "unexpected token in '" + Dir + "' directive"))
5456 // Lex the rept definition.
5457 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5461 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5462 // to hold the macro body with substitutions.
5463 SmallString<256> Buf;
5464 raw_svector_ostream OS(Buf);
5466 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5467 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
5470 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5475 /// parseDirectiveIrp
5476 /// ::= .irp symbol,values
5477 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
5478 MCAsmMacroParameter Parameter;
5479 MCAsmMacroArguments A;
5480 if (check(parseIdentifier(Parameter.Name),
5481 "expected identifier in '.irp' directive") ||
5482 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5483 parseMacroArguments(nullptr, A) ||
5484 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
5487 // Lex the irp definition.
5488 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5492 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5493 // to hold the macro body with substitutions.
5494 SmallString<256> Buf;
5495 raw_svector_ostream OS(Buf);
5497 for (const MCAsmMacroArgument &Arg : A) {
5498 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5499 // This is undocumented, but GAS seems to support it.
5500 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5504 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5509 /// parseDirectiveIrpc
5510 /// ::= .irpc symbol,values
5511 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
5512 MCAsmMacroParameter Parameter;
5513 MCAsmMacroArguments A;
5515 if (check(parseIdentifier(Parameter.Name),
5516 "expected identifier in '.irpc' directive") ||
5517 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5518 parseMacroArguments(nullptr, A))
5521 if (A.size() != 1 || A.front().size() != 1)
5522 return TokError("unexpected token in '.irpc' directive");
5524 // Eat the end of statement.
5525 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5528 // Lex the irpc definition.
5529 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5533 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5534 // to hold the macro body with substitutions.
5535 SmallString<256> Buf;
5536 raw_svector_ostream OS(Buf);
5538 StringRef Values = A.front().front().getString();
5539 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
5540 MCAsmMacroArgument Arg;
5541 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
5543 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5544 // This is undocumented, but GAS seems to support it.
5545 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5549 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5554 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
5555 if (ActiveMacros.empty())
5556 return TokError("unmatched '.endr' directive");
5558 // The only .repl that should get here are the ones created by
5559 // instantiateMacroLikeBody.
5560 assert(getLexer().is(AsmToken::EndOfStatement));
5566 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
5568 const MCExpr *Value;
5569 SMLoc ExprLoc = getLexer().getLoc();
5570 if (parseExpression(Value))
5572 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5574 return Error(ExprLoc, "unexpected expression in _emit");
5575 uint64_t IntValue = MCE->getValue();
5576 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
5577 return Error(ExprLoc, "literal value out of range for directive");
5579 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
5583 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
5584 const MCExpr *Value;
5585 SMLoc ExprLoc = getLexer().getLoc();
5586 if (parseExpression(Value))
5588 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5590 return Error(ExprLoc, "unexpected expression in align");
5591 uint64_t IntValue = MCE->getValue();
5592 if (!isPowerOf2_64(IntValue))
5593 return Error(ExprLoc, "literal value not a power of two greater then zero");
5595 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
5599 bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
5600 const AsmToken StrTok = getTok();
5602 if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
5603 return Error(DirectiveLoc, "expected double quoted string after .print");
5604 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5606 llvm::outs() << StrTok.getStringContents() << '\n';
5610 bool AsmParser::parseDirectiveAddrsig() {
5611 getStreamer().EmitAddrsig();
5615 bool AsmParser::parseDirectiveAddrsigSym() {
5617 if (check(parseIdentifier(Name),
5618 "expected identifier in '.addrsig_sym' directive"))
5620 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
5621 getStreamer().EmitAddrsigSym(Sym);
5625 // We are comparing pointers, but the pointers are relative to a single string.
5626 // Thus, this should always be deterministic.
5627 static int rewritesSort(const AsmRewrite *AsmRewriteA,
5628 const AsmRewrite *AsmRewriteB) {
5629 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5631 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5634 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5635 // rewrite to the same location. Make sure the SizeDirective rewrite is
5636 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5637 // ensures the sort algorithm is stable.
5638 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5639 AsmRewritePrecedence[AsmRewriteB->Kind])
5642 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5643 AsmRewritePrecedence[AsmRewriteB->Kind])
5645 llvm_unreachable("Unstable rewrite sort.");
5648 bool AsmParser::parseMSInlineAsm(
5649 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
5650 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
5651 SmallVectorImpl<std::string> &Constraints,
5652 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5653 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
5654 SmallVector<void *, 4> InputDecls;
5655 SmallVector<void *, 4> OutputDecls;
5656 SmallVector<bool, 4> InputDeclsAddressOf;
5657 SmallVector<bool, 4> OutputDeclsAddressOf;
5658 SmallVector<std::string, 4> InputConstraints;
5659 SmallVector<std::string, 4> OutputConstraints;
5660 SmallVector<unsigned, 4> ClobberRegs;
5662 SmallVector<AsmRewrite, 4> AsmStrRewrites;
5667 // While we have input, parse each statement.
5668 unsigned InputIdx = 0;
5669 unsigned OutputIdx = 0;
5670 while (getLexer().isNot(AsmToken::Eof)) {
5671 // Parse curly braces marking block start/end
5672 if (parseCurlyBlockScope(AsmStrRewrites))
5675 ParseStatementInfo Info(&AsmStrRewrites);
5676 bool StatementErr = parseStatement(Info, &SI);
5678 if (StatementErr || Info.ParseError) {
5679 // Emit pending errors if any exist.
5680 printPendingErrors();
5684 // No pending error should exist here.
5685 assert(!hasPendingError() && "unexpected error from parseStatement");
5687 if (Info.Opcode == ~0U)
5690 const MCInstrDesc &Desc = MII->get(Info.Opcode);
5692 // Build the list of clobbers, outputs and inputs.
5693 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
5694 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
5697 if (Operand.isImm())
5700 // Register operand.
5701 if (Operand.isReg() && !Operand.needAddressOf() &&
5702 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
5703 unsigned NumDefs = Desc.getNumDefs();
5705 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5706 ClobberRegs.push_back(Operand.getReg());
5710 // Expr/Input or Output.
5711 StringRef SymName = Operand.getSymName();
5712 if (SymName.empty())
5715 void *OpDecl = Operand.getOpDecl();
5719 bool isOutput = (i == 1) && Desc.mayStore();
5720 SMLoc Start = SMLoc::getFromPointer(SymName.data());
5723 OutputDecls.push_back(OpDecl);
5724 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
5725 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
5726 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
5728 InputDecls.push_back(OpDecl);
5729 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5730 InputConstraints.push_back(Operand.getConstraint().str());
5731 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
5735 // Consider implicit defs to be clobbers. Think of cpuid and push.
5736 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5737 Desc.getNumImplicitDefs());
5738 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
5741 // Set the number of Outputs and Inputs.
5742 NumOutputs = OutputDecls.size();
5743 NumInputs = InputDecls.size();
5745 // Set the unique clobbers.
5746 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5747 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5749 Clobbers.assign(ClobberRegs.size(), std::string());
5750 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5751 raw_string_ostream OS(Clobbers[I]);
5752 IP->printRegName(OS, ClobberRegs[I]);
5755 // Merge the various outputs and inputs. Output are expected first.
5756 if (NumOutputs || NumInputs) {
5757 unsigned NumExprs = NumOutputs + NumInputs;
5758 OpDecls.resize(NumExprs);
5759 Constraints.resize(NumExprs);
5760 for (unsigned i = 0; i < NumOutputs; ++i) {
5761 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
5762 Constraints[i] = OutputConstraints[i];
5764 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
5765 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
5766 Constraints[j] = InputConstraints[i];
5770 // Build the IR assembly string.
5771 std::string AsmStringIR;
5772 raw_string_ostream OS(AsmStringIR);
5773 StringRef ASMString =
5774 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5775 const char *AsmStart = ASMString.begin();
5776 const char *AsmEnd = ASMString.end();
5777 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
5778 for (const AsmRewrite &AR : AsmStrRewrites) {
5779 AsmRewriteKind Kind = AR.Kind;
5781 const char *Loc = AR.Loc.getPointer();
5782 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
5784 // Emit everything up to the immediate/expression.
5785 if (unsigned Len = Loc - AsmStart)
5786 OS << StringRef(AsmStart, Len);
5788 // Skip the original expression.
5789 if (Kind == AOK_Skip) {
5790 AsmStart = Loc + AR.Len;
5794 unsigned AdditionalSkip = 0;
5795 // Rewrite expressions in $N notation.
5800 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression");
5801 if (AR.IntelExp.NeedBracs)
5803 if (AR.IntelExp.hasBaseReg())
5804 OS << AR.IntelExp.BaseReg;
5805 if (AR.IntelExp.hasIndexReg())
5806 OS << (AR.IntelExp.hasBaseReg() ? " + " : "")
5807 << AR.IntelExp.IndexReg;
5808 if (AR.IntelExp.Scale > 1)
5809 OS << " * $$" << AR.IntelExp.Scale;
5810 if (AR.IntelExp.Imm || !AR.IntelExp.hasRegs())
5811 OS << (AR.IntelExp.hasRegs() ? " + $$" : "$$") << AR.IntelExp.Imm;
5812 if (AR.IntelExp.NeedBracs)
5816 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
5819 OS << '$' << InputIdx++;
5822 OS << '$' << OutputIdx++;
5824 case AOK_SizeDirective:
5827 case 8: OS << "byte ptr "; break;
5828 case 16: OS << "word ptr "; break;
5829 case 32: OS << "dword ptr "; break;
5830 case 64: OS << "qword ptr "; break;
5831 case 80: OS << "xword ptr "; break;
5832 case 128: OS << "xmmword ptr "; break;
5833 case 256: OS << "ymmword ptr "; break;
5840 // MS alignment directives are measured in bytes. If the native assembler
5841 // measures alignment in bytes, we can pass it straight through.
5843 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5846 // Alignment is in log2 form, so print that instead and skip the original
5848 unsigned Val = AR.Val;
5850 assert(Val < 10 && "Expected alignment less then 2^10.");
5851 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5857 case AOK_EndOfStatement:
5862 // Skip the original expression.
5863 AsmStart = Loc + AR.Len + AdditionalSkip;
5866 // Emit the remainder of the asm string.
5867 if (AsmStart != AsmEnd)
5868 OS << StringRef(AsmStart, AsmEnd - AsmStart);
5870 AsmString = OS.str();
5875 namespace MCParserUtils {
5877 /// Returns whether the given symbol is used anywhere in the given expression,
5878 /// or subexpressions.
5879 static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5880 switch (Value->getKind()) {
5881 case MCExpr::Binary: {
5882 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5883 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5884 isSymbolUsedInExpression(Sym, BE->getRHS());
5886 case MCExpr::Target:
5887 case MCExpr::Constant:
5889 case MCExpr::SymbolRef: {
5891 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5893 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5897 return isSymbolUsedInExpression(
5898 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5901 llvm_unreachable("Unknown expr kind!");
5904 bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5905 MCAsmParser &Parser, MCSymbol *&Sym,
5906 const MCExpr *&Value) {
5908 // FIXME: Use better location, we should use proper tokens.
5909 SMLoc EqualLoc = Parser.getTok().getLoc();
5910 if (Parser.parseExpression(Value))
5911 return Parser.TokError("missing expression");
5913 // Note: we don't count b as used in "a = b". This is to allow
5917 if (Parser.parseToken(AsmToken::EndOfStatement))
5920 // Validate that the LHS is allowed to be a variable (either it has not been
5921 // used as a symbol, or it is an absolute symbol).
5922 Sym = Parser.getContext().lookupSymbol(Name);
5924 // Diagnose assignment to a label.
5926 // FIXME: Diagnostics. Note the location of the definition as a label.
5927 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5928 if (isSymbolUsedInExpression(Sym, Value))
5929 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
5930 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5932 ; // Allow redefinitions of undefined symbols only used in directives.
5933 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5934 ; // Allow redefinitions of variables that haven't yet been used.
5935 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5936 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5937 else if (!Sym->isVariable())
5938 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5939 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5940 return Parser.Error(EqualLoc,
5941 "invalid reassignment of non-absolute variable '" +
5943 } else if (Name == ".") {
5944 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
5947 Sym = Parser.getContext().getOrCreateSymbol(Name);
5949 Sym->setRedefinable(allow_redef);
5954 } // end namespace MCParserUtils
5955 } // end namespace llvm
5957 /// Create an MCAsmParser instance.
5958 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5959 MCStreamer &Out, const MCAsmInfo &MAI,
5961 return new AsmParser(SM, C, Out, MAI, CB);