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 a parser for assembly files similar to gas syntax.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/ADT/APFloat.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallSet.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/DebugInfo/CodeView/SymbolRecord.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCCodeView.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCDirectives.h"
30 #include "llvm/MC/MCDwarf.h"
31 #include "llvm/MC/MCExpr.h"
32 #include "llvm/MC/MCInstPrinter.h"
33 #include "llvm/MC/MCInstrDesc.h"
34 #include "llvm/MC/MCInstrInfo.h"
35 #include "llvm/MC/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/MCSymbolMachO.h"
48 #include "llvm/MC/MCTargetOptions.h"
49 #include "llvm/MC/MCValue.h"
50 #include "llvm/Support/Casting.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MD5.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/MemoryBuffer.h"
56 #include "llvm/Support/SMLoc.h"
57 #include "llvm/Support/SourceMgr.h"
58 #include "llvm/Support/raw_ostream.h"
76 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
80 /// Helper types for tracking macro definitions.
81 typedef std::vector
<AsmToken
> MCAsmMacroArgument
;
82 typedef std::vector
<MCAsmMacroArgument
> MCAsmMacroArguments
;
84 /// Helper class for storing information about an active macro
86 struct MacroInstantiation
{
87 /// The location of the instantiation.
88 SMLoc InstantiationLoc
;
90 /// The buffer where parsing should resume upon instantiation completion.
93 /// The location where parsing should resume upon instantiation completion.
96 /// The depth of TheCondStack at the start of the instantiation.
97 size_t CondStackDepth
;
100 struct ParseStatementInfo
{
101 /// The parsed operands from the last parsed statement.
102 SmallVector
<std::unique_ptr
<MCParsedAsmOperand
>, 8> ParsedOperands
;
104 /// The opcode from the last parsed instruction.
105 unsigned Opcode
= ~0U;
107 /// Was there an error parsing the inline assembly?
108 bool ParseError
= false;
110 SmallVectorImpl
<AsmRewrite
> *AsmRewrites
= nullptr;
112 ParseStatementInfo() = delete;
113 ParseStatementInfo(SmallVectorImpl
<AsmRewrite
> *rewrites
)
114 : AsmRewrites(rewrites
) {}
117 /// The concrete assembly parser instance.
118 class AsmParser
: public MCAsmParser
{
123 const MCAsmInfo
&MAI
;
125 SourceMgr::DiagHandlerTy SavedDiagHandler
;
126 void *SavedDiagContext
;
127 std::unique_ptr
<MCAsmParserExtension
> PlatformParser
;
129 std::optional
<SMLoc
> CFIStartProcLoc
;
131 /// This is the current buffer index we're lexing from as managed by the
132 /// SourceMgr object.
135 AsmCond TheCondState
;
136 std::vector
<AsmCond
> TheCondStack
;
138 /// maps directive names to handler methods in parser
139 /// extensions. Extensions register themselves in this map by calling
140 /// addDirectiveHandler.
141 StringMap
<ExtensionDirectiveHandler
> ExtensionDirectiveMap
;
143 /// Stack of active macro instantiations.
144 std::vector
<MacroInstantiation
*> ActiveMacros
;
146 /// List of bodies of anonymous macros.
147 std::deque
<MCAsmMacro
> MacroLikeBodies
;
149 /// Boolean tracking whether macro substitution is enabled.
150 unsigned MacrosEnabledFlag
: 1;
152 /// Keeps track of how many .macro's have been instantiated.
153 unsigned NumOfMacroInstantiations
;
155 /// The values from the last parsed cpp hash file line comment if any.
156 struct CppHashInfoTy
{
161 CppHashInfoTy() : LineNumber(0), Buf(0) {}
163 CppHashInfoTy CppHashInfo
;
165 /// Have we seen any file line comment.
166 bool HadCppHashFilename
= false;
168 /// List of forward directional labels for diagnosis at the end.
169 SmallVector
<std::tuple
<SMLoc
, CppHashInfoTy
, MCSymbol
*>, 4> DirLabels
;
171 SmallSet
<StringRef
, 2> LTODiscardSymbols
;
173 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
174 unsigned AssemblerDialect
= ~0U;
176 /// is Darwin compatibility enabled?
177 bool IsDarwin
= false;
179 /// Are we parsing ms-style inline assembly?
180 bool ParsingMSInlineAsm
= false;
182 /// Did we already inform the user about inconsistent MD5 usage?
183 bool ReportedInconsistentMD5
= false;
185 // Is alt macro mode enabled.
186 bool AltMacroMode
= false;
189 virtual bool parseStatement(ParseStatementInfo
&Info
,
190 MCAsmParserSemaCallback
*SI
);
192 /// This routine uses the target specific ParseInstruction function to
193 /// parse an instruction into Operands, and then call the target specific
194 /// MatchAndEmit function to match and emit the instruction.
195 bool parseAndMatchAndEmitTargetInstruction(ParseStatementInfo
&Info
,
196 StringRef IDVal
, AsmToken ID
,
199 /// Should we emit DWARF describing this assembler source? (Returns false if
200 /// the source has .file directives, which means we don't want to generate
201 /// info describing the assembler source itself.)
202 bool enabledGenDwarfForAssembly();
205 AsmParser(SourceMgr
&SM
, MCContext
&Ctx
, MCStreamer
&Out
,
206 const MCAsmInfo
&MAI
, unsigned CB
);
207 AsmParser(const AsmParser
&) = delete;
208 AsmParser
&operator=(const AsmParser
&) = delete;
209 ~AsmParser() override
;
211 bool Run(bool NoInitialTextSection
, bool NoFinalize
= false) override
;
213 void addDirectiveHandler(StringRef Directive
,
214 ExtensionDirectiveHandler Handler
) override
{
215 ExtensionDirectiveMap
[Directive
] = Handler
;
218 void addAliasForDirective(StringRef Directive
, StringRef Alias
) override
{
219 DirectiveKindMap
[Directive
.lower()] = DirectiveKindMap
[Alias
.lower()];
222 /// @name MCAsmParser Interface
225 SourceMgr
&getSourceManager() override
{ return SrcMgr
; }
226 MCAsmLexer
&getLexer() override
{ return Lexer
; }
227 MCContext
&getContext() override
{ return Ctx
; }
228 MCStreamer
&getStreamer() override
{ return Out
; }
230 CodeViewContext
&getCVContext() { return Ctx
.getCVContext(); }
232 unsigned getAssemblerDialect() override
{
233 if (AssemblerDialect
== ~0U)
234 return MAI
.getAssemblerDialect();
236 return AssemblerDialect
;
238 void setAssemblerDialect(unsigned i
) override
{
239 AssemblerDialect
= i
;
242 void Note(SMLoc L
, const Twine
&Msg
, SMRange Range
= std::nullopt
) override
;
243 bool Warning(SMLoc L
, const Twine
&Msg
,
244 SMRange Range
= std::nullopt
) override
;
245 bool printError(SMLoc L
, const Twine
&Msg
,
246 SMRange Range
= std::nullopt
) override
;
248 const AsmToken
&Lex() override
;
250 void setParsingMSInlineAsm(bool V
) override
{
251 ParsingMSInlineAsm
= V
;
252 // When parsing MS inline asm, we must lex 0b1101 and 0ABCH as binary and
253 // hex integer literals.
254 Lexer
.setLexMasmIntegers(V
);
256 bool isParsingMSInlineAsm() override
{ return ParsingMSInlineAsm
; }
258 bool discardLTOSymbol(StringRef Name
) const override
{
259 return LTODiscardSymbols
.contains(Name
);
262 bool parseMSInlineAsm(std::string
&AsmString
, unsigned &NumOutputs
,
264 SmallVectorImpl
<std::pair
<void *, bool>> &OpDecls
,
265 SmallVectorImpl
<std::string
> &Constraints
,
266 SmallVectorImpl
<std::string
> &Clobbers
,
267 const MCInstrInfo
*MII
, MCInstPrinter
*IP
,
268 MCAsmParserSemaCallback
&SI
) override
;
270 bool parseExpression(const MCExpr
*&Res
);
271 bool parseExpression(const MCExpr
*&Res
, SMLoc
&EndLoc
) override
;
272 bool parsePrimaryExpr(const MCExpr
*&Res
, SMLoc
&EndLoc
,
273 AsmTypeInfo
*TypeInfo
) override
;
274 bool parseParenExpression(const MCExpr
*&Res
, SMLoc
&EndLoc
) override
;
275 bool parseParenExprOfDepth(unsigned ParenDepth
, const MCExpr
*&Res
,
276 SMLoc
&EndLoc
) override
;
277 bool parseAbsoluteExpression(int64_t &Res
) override
;
279 /// Parse a floating point expression using the float \p Semantics
280 /// and set \p Res to the value.
281 bool parseRealValue(const fltSemantics
&Semantics
, APInt
&Res
);
283 /// Parse an identifier or string (as a quoted identifier)
284 /// and set \p Res to the identifier contents.
285 bool parseIdentifier(StringRef
&Res
) override
;
286 void eatToEndOfStatement() override
;
288 bool checkForValidSection() override
;
293 bool parseCurlyBlockScope(SmallVectorImpl
<AsmRewrite
>& AsmStrRewrites
);
294 bool parseCppHashLineFilenameComment(SMLoc L
, bool SaveLocInfo
= true);
296 void checkForBadMacro(SMLoc DirectiveLoc
, StringRef Name
, StringRef Body
,
297 ArrayRef
<MCAsmMacroParameter
> Parameters
);
298 bool expandMacro(raw_svector_ostream
&OS
, MCAsmMacro
&Macro
,
299 ArrayRef
<MCAsmMacroParameter
> Parameters
,
300 ArrayRef
<MCAsmMacroArgument
> A
, bool EnableAtPseudoVariable
);
302 /// Are macros enabled in the parser?
303 bool areMacrosEnabled() {return MacrosEnabledFlag
;}
305 /// Control a flag in the parser that enables or disables macros.
306 void setMacrosEnabled(bool Flag
) {MacrosEnabledFlag
= Flag
;}
308 /// Are we inside a macro instantiation?
309 bool isInsideMacroInstantiation() {return !ActiveMacros
.empty();}
311 /// Handle entry to macro instantiation.
313 /// \param M The macro.
314 /// \param NameLoc Instantiation location.
315 bool handleMacroEntry(MCAsmMacro
*M
, SMLoc NameLoc
);
317 /// Handle exit from macro instantiation.
318 void handleMacroExit();
320 /// Extract AsmTokens for a macro argument.
321 bool parseMacroArgument(MCAsmMacroArgument
&MA
, bool Vararg
);
323 /// Parse all macro arguments for a given macro.
324 bool parseMacroArguments(const MCAsmMacro
*M
, MCAsmMacroArguments
&A
);
326 void printMacroInstantiations();
327 void printMessage(SMLoc Loc
, SourceMgr::DiagKind Kind
, const Twine
&Msg
,
328 SMRange Range
= std::nullopt
) const {
329 ArrayRef
<SMRange
> Ranges(Range
);
330 SrcMgr
.PrintMessage(Loc
, Kind
, Msg
, Ranges
);
332 static void DiagHandler(const SMDiagnostic
&Diag
, void *Context
);
334 /// Enter the specified file. This returns true on failure.
335 bool enterIncludeFile(const std::string
&Filename
);
337 /// Process the specified file for the .incbin directive.
338 /// This returns true on failure.
339 bool processIncbinFile(const std::string
&Filename
, int64_t Skip
= 0,
340 const MCExpr
*Count
= nullptr, SMLoc Loc
= SMLoc());
342 /// Reset the current lexer position to that given by \p Loc. The
343 /// current token is not set; clients should ensure Lex() is called
346 /// \param InBuffer If not 0, should be the known buffer id that contains the
348 void jumpToLoc(SMLoc Loc
, unsigned InBuffer
= 0);
350 /// Parse up to the end of statement and a return the contents from the
351 /// current token until the end of the statement; the current token on exit
352 /// will be either the EndOfStatement or EOF.
353 StringRef
parseStringToEndOfStatement() override
;
355 /// Parse until the end of a statement or a comma is encountered,
356 /// return the contents from the current token up to the end or comma.
357 StringRef
parseStringToComma();
359 enum class AssignmentKind
{
366 bool parseAssignment(StringRef Name
, AssignmentKind Kind
);
368 unsigned getBinOpPrecedence(AsmToken::TokenKind K
,
369 MCBinaryExpr::Opcode
&Kind
);
371 bool parseBinOpRHS(unsigned Precedence
, const MCExpr
*&Res
, SMLoc
&EndLoc
);
372 bool parseParenExpr(const MCExpr
*&Res
, SMLoc
&EndLoc
);
373 bool parseBracketExpr(const MCExpr
*&Res
, SMLoc
&EndLoc
);
375 bool parseRegisterOrRegisterNumber(int64_t &Register
, SMLoc DirectiveLoc
);
377 bool parseCVFunctionId(int64_t &FunctionId
, StringRef DirectiveName
);
378 bool parseCVFileId(int64_t &FileId
, StringRef DirectiveName
);
380 // Generic (target and platform independent) directive parsing.
382 DK_NO_DIRECTIVE
, // Placeholder
437 DK_BUNDLE_ALIGN_MODE
,
451 DK_WEAK_DEF_CAN_BE_HIDDEN
,
492 DK_CV_INLINE_SITE_ID
,
495 DK_CV_INLINE_LINETABLE
,
500 DK_CV_FILECHECKSUM_OFFSET
,
506 DK_CFI_DEF_CFA_OFFSET
,
507 DK_CFI_ADJUST_CFA_OFFSET
,
508 DK_CFI_DEF_CFA_REGISTER
,
509 DK_CFI_LLVM_DEF_ASPACE_CFA
,
514 DK_CFI_REMEMBER_STATE
,
515 DK_CFI_RESTORE_STATE
,
519 DK_CFI_RETURN_COLUMN
,
546 DK_LTO_SET_CONDITIONAL
,
547 DK_CFI_MTE_TAGGED_FRAME
,
552 /// Maps directive name --> DirectiveKind enum, for
553 /// directives parsed by this class.
554 StringMap
<DirectiveKind
> DirectiveKindMap
;
556 // Codeview def_range type parsing.
557 enum CVDefRangeType
{
558 CVDR_DEFRANGE
= 0, // Placeholder
559 CVDR_DEFRANGE_REGISTER
,
560 CVDR_DEFRANGE_FRAMEPOINTER_REL
,
561 CVDR_DEFRANGE_SUBFIELD_REGISTER
,
562 CVDR_DEFRANGE_REGISTER_REL
565 /// Maps Codeview def_range types --> CVDefRangeType enum, for
566 /// Codeview def_range types parsed by this class.
567 StringMap
<CVDefRangeType
> CVDefRangeTypeMap
;
569 // ".ascii", ".asciz", ".string"
570 bool parseDirectiveAscii(StringRef IDVal
, bool ZeroTerminated
);
571 bool parseDirectiveReloc(SMLoc DirectiveLoc
); // ".reloc"
572 bool parseDirectiveValue(StringRef IDVal
,
573 unsigned Size
); // ".byte", ".long", ...
574 bool parseDirectiveOctaValue(StringRef IDVal
); // ".octa", ...
575 bool parseDirectiveRealValue(StringRef IDVal
,
576 const fltSemantics
&); // ".single", ...
577 bool parseDirectiveFill(); // ".fill"
578 bool parseDirectiveZero(); // ".zero"
579 // ".set", ".equ", ".equiv", ".lto_set_conditional"
580 bool parseDirectiveSet(StringRef IDVal
, AssignmentKind Kind
);
581 bool parseDirectiveOrg(); // ".org"
582 // ".align{,32}", ".p2align{,w,l}"
583 bool parseDirectiveAlign(bool IsPow2
, unsigned ValueSize
);
585 // ".file", ".line", ".loc", ".loc_label", ".stabs"
586 bool parseDirectiveFile(SMLoc DirectiveLoc
);
587 bool parseDirectiveLine();
588 bool parseDirectiveLoc();
589 bool parseDirectiveLocLabel(SMLoc DirectiveLoc
);
590 bool parseDirectiveStabs();
592 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
593 // ".cv_inline_linetable", ".cv_def_range", ".cv_string"
594 bool parseDirectiveCVFile();
595 bool parseDirectiveCVFuncId();
596 bool parseDirectiveCVInlineSiteId();
597 bool parseDirectiveCVLoc();
598 bool parseDirectiveCVLinetable();
599 bool parseDirectiveCVInlineLinetable();
600 bool parseDirectiveCVDefRange();
601 bool parseDirectiveCVString();
602 bool parseDirectiveCVStringTable();
603 bool parseDirectiveCVFileChecksums();
604 bool parseDirectiveCVFileChecksumOffset();
605 bool parseDirectiveCVFPOData();
608 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc
);
609 bool parseDirectiveCFIWindowSave(SMLoc DirectiveLoc
);
610 bool parseDirectiveCFISections();
611 bool parseDirectiveCFIStartProc();
612 bool parseDirectiveCFIEndProc();
613 bool parseDirectiveCFIDefCfaOffset(SMLoc DirectiveLoc
);
614 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc
);
615 bool parseDirectiveCFIAdjustCfaOffset(SMLoc DirectiveLoc
);
616 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc
);
617 bool parseDirectiveCFILLVMDefAspaceCfa(SMLoc DirectiveLoc
);
618 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc
);
619 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc
);
620 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality
);
621 bool parseDirectiveCFIRememberState(SMLoc DirectiveLoc
);
622 bool parseDirectiveCFIRestoreState(SMLoc DirectiveLoc
);
623 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc
);
624 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc
);
625 bool parseDirectiveCFIEscape(SMLoc DirectiveLoc
);
626 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc
);
627 bool parseDirectiveCFISignalFrame(SMLoc DirectiveLoc
);
628 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc
);
629 bool parseDirectiveCFILabel(SMLoc DirectiveLoc
);
630 bool parseDirectiveCFIValOffset(SMLoc DirectiveLoc
);
633 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc
);
634 bool parseDirectiveExitMacro(StringRef Directive
);
635 bool parseDirectiveEndMacro(StringRef Directive
);
636 bool parseDirectiveMacro(SMLoc DirectiveLoc
);
637 bool parseDirectiveMacrosOnOff(StringRef Directive
);
638 // alternate macro mode directives
639 bool parseDirectiveAltmacro(StringRef Directive
);
640 // ".bundle_align_mode"
641 bool parseDirectiveBundleAlignMode();
643 bool parseDirectiveBundleLock();
645 bool parseDirectiveBundleUnlock();
648 bool parseDirectiveSpace(StringRef IDVal
);
651 bool parseDirectiveDCB(StringRef IDVal
, unsigned Size
);
652 bool parseDirectiveRealDCB(StringRef IDVal
, const fltSemantics
&);
654 bool parseDirectiveDS(StringRef IDVal
, unsigned Size
);
656 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
657 bool parseDirectiveLEB128(bool Signed
);
659 /// Parse a directive like ".globl" which
660 /// accepts a single symbol (which should be a label or an external).
661 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr
);
663 bool parseDirectiveComm(bool IsLocal
); // ".comm" and ".lcomm"
665 bool parseDirectiveAbort(SMLoc DirectiveLoc
); // ".abort"
666 bool parseDirectiveInclude(); // ".include"
667 bool parseDirectiveIncbin(); // ".incbin"
669 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
670 bool parseDirectiveIf(SMLoc DirectiveLoc
, DirectiveKind DirKind
);
671 // ".ifb" or ".ifnb", depending on ExpectBlank.
672 bool parseDirectiveIfb(SMLoc DirectiveLoc
, bool ExpectBlank
);
673 // ".ifc" or ".ifnc", depending on ExpectEqual.
674 bool parseDirectiveIfc(SMLoc DirectiveLoc
, bool ExpectEqual
);
675 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
676 bool parseDirectiveIfeqs(SMLoc DirectiveLoc
, bool ExpectEqual
);
677 // ".ifdef" or ".ifndef", depending on expect_defined
678 bool parseDirectiveIfdef(SMLoc DirectiveLoc
, bool expect_defined
);
679 bool parseDirectiveElseIf(SMLoc DirectiveLoc
); // ".elseif"
680 bool parseDirectiveElse(SMLoc DirectiveLoc
); // ".else"
681 bool parseDirectiveEndIf(SMLoc DirectiveLoc
); // .endif
682 bool parseEscapedString(std::string
&Data
) override
;
683 bool parseAngleBracketString(std::string
&Data
) override
;
685 const MCExpr
*applyModifierToExpr(const MCExpr
*E
,
686 MCSymbolRefExpr::VariantKind Variant
);
688 // Macro-like directives
689 MCAsmMacro
*parseMacroLikeBody(SMLoc DirectiveLoc
);
690 void instantiateMacroLikeBody(MCAsmMacro
*M
, SMLoc DirectiveLoc
,
691 raw_svector_ostream
&OS
);
692 bool parseDirectiveRept(SMLoc DirectiveLoc
, StringRef Directive
);
693 bool parseDirectiveIrp(SMLoc DirectiveLoc
); // ".irp"
694 bool parseDirectiveIrpc(SMLoc DirectiveLoc
); // ".irpc"
695 bool parseDirectiveEndr(SMLoc DirectiveLoc
); // ".endr"
697 // "_emit" or "__emit"
698 bool parseDirectiveMSEmit(SMLoc DirectiveLoc
, ParseStatementInfo
&Info
,
702 bool parseDirectiveMSAlign(SMLoc DirectiveLoc
, ParseStatementInfo
&Info
);
705 bool parseDirectiveEnd(SMLoc DirectiveLoc
);
707 // ".err" or ".error"
708 bool parseDirectiveError(SMLoc DirectiveLoc
, bool WithMessage
);
711 bool parseDirectiveWarning(SMLoc DirectiveLoc
);
713 // .print <double-quotes-string>
714 bool parseDirectivePrint(SMLoc DirectiveLoc
);
717 bool parseDirectivePseudoProbe();
720 bool parseDirectiveLTODiscard();
722 // Directives to support address-significance tables.
723 bool parseDirectiveAddrsig();
724 bool parseDirectiveAddrsigSym();
726 void initializeDirectiveKindMap();
727 void initializeCVDefRangeTypeMap();
730 class HLASMAsmParser final
: public AsmParser
{
735 void lexLeadingSpaces() {
736 while (Lexer
.is(AsmToken::Space
))
740 bool parseAsHLASMLabel(ParseStatementInfo
&Info
, MCAsmParserSemaCallback
*SI
);
741 bool parseAsMachineInstruction(ParseStatementInfo
&Info
,
742 MCAsmParserSemaCallback
*SI
);
745 HLASMAsmParser(SourceMgr
&SM
, MCContext
&Ctx
, MCStreamer
&Out
,
746 const MCAsmInfo
&MAI
, unsigned CB
= 0)
747 : AsmParser(SM
, Ctx
, Out
, MAI
, CB
), Lexer(getLexer()), Out(Out
) {
748 Lexer
.setSkipSpace(false);
749 Lexer
.setAllowHashInIdentifier(true);
750 Lexer
.setLexHLASMIntegers(true);
751 Lexer
.setLexHLASMStrings(true);
754 ~HLASMAsmParser() { Lexer
.setSkipSpace(true); }
756 bool parseStatement(ParseStatementInfo
&Info
,
757 MCAsmParserSemaCallback
*SI
) override
;
760 } // end anonymous namespace
764 extern cl::opt
<unsigned> AsmMacroMaxNestingDepth
;
766 extern MCAsmParserExtension
*createDarwinAsmParser();
767 extern MCAsmParserExtension
*createELFAsmParser();
768 extern MCAsmParserExtension
*createCOFFAsmParser();
769 extern MCAsmParserExtension
*createGOFFAsmParser();
770 extern MCAsmParserExtension
*createXCOFFAsmParser();
771 extern MCAsmParserExtension
*createWasmAsmParser();
773 } // end namespace llvm
775 enum { DEFAULT_ADDRSPACE
= 0 };
777 AsmParser::AsmParser(SourceMgr
&SM
, MCContext
&Ctx
, MCStreamer
&Out
,
778 const MCAsmInfo
&MAI
, unsigned CB
= 0)
779 : Lexer(MAI
), Ctx(Ctx
), Out(Out
), MAI(MAI
), SrcMgr(SM
),
780 CurBuffer(CB
? CB
: SM
.getMainFileID()), MacrosEnabledFlag(true) {
782 // Save the old handler.
783 SavedDiagHandler
= SrcMgr
.getDiagHandler();
784 SavedDiagContext
= SrcMgr
.getDiagContext();
785 // Set our own handler which calls the saved handler.
786 SrcMgr
.setDiagHandler(DiagHandler
, this);
787 Lexer
.setBuffer(SrcMgr
.getMemoryBuffer(CurBuffer
)->getBuffer());
788 // Make MCStreamer aware of the StartTokLoc for locations in diagnostics.
789 Out
.setStartTokLocPtr(&StartTokLoc
);
791 // Initialize the platform / file format parser.
792 switch (Ctx
.getObjectFileType()) {
793 case MCContext::IsCOFF
:
794 PlatformParser
.reset(createCOFFAsmParser());
796 case MCContext::IsMachO
:
797 PlatformParser
.reset(createDarwinAsmParser());
800 case MCContext::IsELF
:
801 PlatformParser
.reset(createELFAsmParser());
803 case MCContext::IsGOFF
:
804 PlatformParser
.reset(createGOFFAsmParser());
806 case MCContext::IsSPIRV
:
808 "Need to implement createSPIRVAsmParser for SPIRV format.");
810 case MCContext::IsWasm
:
811 PlatformParser
.reset(createWasmAsmParser());
813 case MCContext::IsXCOFF
:
814 PlatformParser
.reset(createXCOFFAsmParser());
816 case MCContext::IsDXContainer
:
817 report_fatal_error("DXContainer is not supported yet");
821 PlatformParser
->Initialize(*this);
822 initializeDirectiveKindMap();
823 initializeCVDefRangeTypeMap();
825 NumOfMacroInstantiations
= 0;
828 AsmParser::~AsmParser() {
829 assert((HadError
|| ActiveMacros
.empty()) &&
830 "Unexpected active macro instantiation!");
832 // Remove MCStreamer's reference to the parser SMLoc.
833 Out
.setStartTokLocPtr(nullptr);
834 // Restore the saved diagnostics handler and context for use during
836 SrcMgr
.setDiagHandler(SavedDiagHandler
, SavedDiagContext
);
839 void AsmParser::printMacroInstantiations() {
840 // Print the active macro instantiation stack.
841 for (MacroInstantiation
*M
: reverse(ActiveMacros
))
842 printMessage(M
->InstantiationLoc
, SourceMgr::DK_Note
,
843 "while in macro instantiation");
846 void AsmParser::Note(SMLoc L
, const Twine
&Msg
, SMRange Range
) {
847 printPendingErrors();
848 printMessage(L
, SourceMgr::DK_Note
, Msg
, Range
);
849 printMacroInstantiations();
852 bool AsmParser::Warning(SMLoc L
, const Twine
&Msg
, SMRange Range
) {
853 if(getTargetParser().getTargetOptions().MCNoWarn
)
855 if (getTargetParser().getTargetOptions().MCFatalWarnings
)
856 return Error(L
, Msg
, Range
);
857 printMessage(L
, SourceMgr::DK_Warning
, Msg
, Range
);
858 printMacroInstantiations();
862 bool AsmParser::printError(SMLoc L
, const Twine
&Msg
, SMRange Range
) {
864 printMessage(L
, SourceMgr::DK_Error
, Msg
, Range
);
865 printMacroInstantiations();
869 bool AsmParser::enterIncludeFile(const std::string
&Filename
) {
870 std::string IncludedFile
;
872 SrcMgr
.AddIncludeFile(Filename
, Lexer
.getLoc(), IncludedFile
);
877 Lexer
.setBuffer(SrcMgr
.getMemoryBuffer(CurBuffer
)->getBuffer());
881 /// Process the specified .incbin file by searching for it in the include paths
882 /// then just emitting the byte contents of the file to the streamer. This
883 /// returns true on failure.
884 bool AsmParser::processIncbinFile(const std::string
&Filename
, int64_t Skip
,
885 const MCExpr
*Count
, SMLoc Loc
) {
886 std::string IncludedFile
;
888 SrcMgr
.AddIncludeFile(Filename
, Lexer
.getLoc(), IncludedFile
);
892 // Pick up the bytes from the file and emit them.
893 StringRef Bytes
= SrcMgr
.getMemoryBuffer(NewBuf
)->getBuffer();
894 Bytes
= Bytes
.drop_front(Skip
);
897 if (!Count
->evaluateAsAbsolute(Res
, getStreamer().getAssemblerPtr()))
898 return Error(Loc
, "expected absolute expression");
900 return Warning(Loc
, "negative count has no effect");
901 Bytes
= Bytes
.take_front(Res
);
903 getStreamer().emitBytes(Bytes
);
907 void AsmParser::jumpToLoc(SMLoc Loc
, unsigned InBuffer
) {
908 CurBuffer
= InBuffer
? InBuffer
: SrcMgr
.FindBufferContainingLoc(Loc
);
909 Lexer
.setBuffer(SrcMgr
.getMemoryBuffer(CurBuffer
)->getBuffer(),
913 const AsmToken
&AsmParser::Lex() {
914 if (Lexer
.getTok().is(AsmToken::Error
))
915 Error(Lexer
.getErrLoc(), Lexer
.getErr());
917 // if it's a end of statement with a comment in it
918 if (getTok().is(AsmToken::EndOfStatement
)) {
919 // if this is a line comment output it.
920 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
921 getTok().getString().front() != '\r' && MAI
.preserveAsmComments())
922 Out
.addExplicitComment(Twine(getTok().getString()));
925 const AsmToken
*tok
= &Lexer
.Lex();
927 // Parse comments here to be deferred until end of next statement.
928 while (tok
->is(AsmToken::Comment
)) {
929 if (MAI
.preserveAsmComments())
930 Out
.addExplicitComment(Twine(tok
->getString()));
934 if (tok
->is(AsmToken::Eof
)) {
935 // If this is the end of an included file, pop the parent file off the
937 SMLoc ParentIncludeLoc
= SrcMgr
.getParentIncludeLoc(CurBuffer
);
938 if (ParentIncludeLoc
!= SMLoc()) {
939 jumpToLoc(ParentIncludeLoc
);
947 bool AsmParser::enabledGenDwarfForAssembly() {
948 // Check whether the user specified -g.
949 if (!getContext().getGenDwarfForAssembly())
951 // If we haven't encountered any .file directives (which would imply that
952 // the assembler source was produced with debug info already) then emit one
953 // describing the assembler source file itself.
954 if (getContext().getGenDwarfFileNumber() == 0) {
955 const MCDwarfFile
&RootFile
=
956 getContext().getMCDwarfLineTable(/*CUID=*/0).getRootFile();
957 getContext().setGenDwarfFileNumber(getStreamer().emitDwarfFileDirective(
958 /*CUID=*/0, getContext().getCompilationDir(), RootFile
.Name
,
959 RootFile
.Checksum
, RootFile
.Source
));
964 bool AsmParser::Run(bool NoInitialTextSection
, bool NoFinalize
) {
965 LTODiscardSymbols
.clear();
967 // Create the initial section, if requested.
968 if (!NoInitialTextSection
)
969 Out
.initSections(false, getTargetParser().getSTI());
975 AsmCond StartingCondState
= TheCondState
;
976 SmallVector
<AsmRewrite
, 4> AsmStrRewrites
;
978 // If we are generating dwarf for assembly source files save the initial text
979 // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't
980 // emitting any actual debug info yet and haven't had a chance to parse any
981 // embedded .file directives.)
982 if (getContext().getGenDwarfForAssembly()) {
983 MCSection
*Sec
= getStreamer().getCurrentSectionOnly();
984 if (!Sec
->getBeginSymbol()) {
985 MCSymbol
*SectionStartSym
= getContext().createTempSymbol();
986 getStreamer().emitLabel(SectionStartSym
);
987 Sec
->setBeginSymbol(SectionStartSym
);
989 bool InsertResult
= getContext().addGenDwarfSection(Sec
);
990 assert(InsertResult
&& ".text section should not have debug info yet");
994 getTargetParser().onBeginOfFile();
996 // While we have input, parse each statement.
997 while (Lexer
.isNot(AsmToken::Eof
)) {
998 ParseStatementInfo
Info(&AsmStrRewrites
);
999 bool Parsed
= parseStatement(Info
, nullptr);
1001 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
1002 // for printing ErrMsg via Lex() only if no (presumably better) parser error
1004 if (Parsed
&& !hasPendingError() && Lexer
.getTok().is(AsmToken::Error
)) {
1008 // parseStatement returned true so may need to emit an error.
1009 printPendingErrors();
1011 // Skipping to the next line if needed.
1012 if (Parsed
&& !getLexer().isAtStartOfStatement())
1013 eatToEndOfStatement();
1016 getTargetParser().onEndOfFile();
1017 printPendingErrors();
1019 // All errors should have been emitted.
1020 assert(!hasPendingError() && "unexpected error from parseStatement");
1022 getTargetParser().flushPendingInstructions(getStreamer());
1024 if (TheCondState
.TheCond
!= StartingCondState
.TheCond
||
1025 TheCondState
.Ignore
!= StartingCondState
.Ignore
)
1026 printError(getTok().getLoc(), "unmatched .ifs or .elses");
1027 // Check to see there are no empty DwarfFile slots.
1028 const auto &LineTables
= getContext().getMCDwarfLineTables();
1029 if (!LineTables
.empty()) {
1031 for (const auto &File
: LineTables
.begin()->second
.getMCDwarfFiles()) {
1032 if (File
.Name
.empty() && Index
!= 0)
1033 printError(getTok().getLoc(), "unassigned file number: " +
1035 " for .file directives");
1040 // Check to see that all assembler local symbols were actually defined.
1041 // Targets that don't do subsections via symbols may not want this, though,
1042 // so conservatively exclude them. Only do this if we're finalizing, though,
1043 // as otherwise we won't necessarily have seen everything yet.
1045 if (MAI
.hasSubsectionsViaSymbols()) {
1046 for (const auto &TableEntry
: getContext().getSymbols()) {
1047 MCSymbol
*Sym
= TableEntry
.getValue().Symbol
;
1048 // Variable symbols may not be marked as defined, so check those
1049 // explicitly. If we know it's a variable, we have a definition for
1050 // the purposes of this check.
1051 if (Sym
&& Sym
->isTemporary() && !Sym
->isVariable() &&
1053 // FIXME: We would really like to refer back to where the symbol was
1054 // first referenced for a source location. We need to add something
1055 // to track that. Currently, we just point to the end of the file.
1056 printError(getTok().getLoc(), "assembler local symbol '" +
1057 Sym
->getName() + "' not defined");
1061 // Temporary symbols like the ones for directional jumps don't go in the
1062 // symbol table. They also need to be diagnosed in all (final) cases.
1063 for (std::tuple
<SMLoc
, CppHashInfoTy
, MCSymbol
*> &LocSym
: DirLabels
) {
1064 if (std::get
<2>(LocSym
)->isUndefined()) {
1065 // Reset the state of any "# line file" directives we've seen to the
1066 // context as it was at the diagnostic site.
1067 CppHashInfo
= std::get
<1>(LocSym
);
1068 printError(std::get
<0>(LocSym
), "directional label undefined");
1072 // Finalize the output stream if there are no errors and if the client wants
1074 if (!HadError
&& !NoFinalize
) {
1075 if (auto *TS
= Out
.getTargetStreamer())
1076 TS
->emitConstantPools();
1078 Out
.finish(Lexer
.getLoc());
1081 return HadError
|| getContext().hadError();
1084 bool AsmParser::checkForValidSection() {
1085 if (!ParsingMSInlineAsm
&& !getStreamer().getCurrentFragment()) {
1086 Out
.initSections(false, getTargetParser().getSTI());
1087 return Error(getTok().getLoc(),
1088 "expected section directive before assembly directive");
1093 /// Throw away the rest of the line for testing purposes.
1094 void AsmParser::eatToEndOfStatement() {
1095 while (Lexer
.isNot(AsmToken::EndOfStatement
) && Lexer
.isNot(AsmToken::Eof
))
1099 if (Lexer
.is(AsmToken::EndOfStatement
))
1103 StringRef
AsmParser::parseStringToEndOfStatement() {
1104 const char *Start
= getTok().getLoc().getPointer();
1106 while (Lexer
.isNot(AsmToken::EndOfStatement
) && Lexer
.isNot(AsmToken::Eof
))
1109 const char *End
= getTok().getLoc().getPointer();
1110 return StringRef(Start
, End
- Start
);
1113 StringRef
AsmParser::parseStringToComma() {
1114 const char *Start
= getTok().getLoc().getPointer();
1116 while (Lexer
.isNot(AsmToken::EndOfStatement
) &&
1117 Lexer
.isNot(AsmToken::Comma
) && Lexer
.isNot(AsmToken::Eof
))
1120 const char *End
= getTok().getLoc().getPointer();
1121 return StringRef(Start
, End
- Start
);
1124 /// Parse a paren expression and return it.
1125 /// NOTE: This assumes the leading '(' has already been consumed.
1127 /// parenexpr ::= expr)
1129 bool AsmParser::parseParenExpr(const MCExpr
*&Res
, SMLoc
&EndLoc
) {
1130 if (parseExpression(Res
))
1132 EndLoc
= Lexer
.getTok().getEndLoc();
1133 return parseRParen();
1136 /// Parse a bracket expression and return it.
1137 /// NOTE: This assumes the leading '[' has already been consumed.
1139 /// bracketexpr ::= expr]
1141 bool AsmParser::parseBracketExpr(const MCExpr
*&Res
, SMLoc
&EndLoc
) {
1142 if (parseExpression(Res
))
1144 EndLoc
= getTok().getEndLoc();
1145 if (parseToken(AsmToken::RBrac
, "expected ']' in brackets expression"))
1150 /// Parse a primary expression and return it.
1151 /// primaryexpr ::= (parenexpr
1152 /// primaryexpr ::= symbol
1153 /// primaryexpr ::= number
1154 /// primaryexpr ::= '.'
1155 /// primaryexpr ::= ~,+,- primaryexpr
1156 bool AsmParser::parsePrimaryExpr(const MCExpr
*&Res
, SMLoc
&EndLoc
,
1157 AsmTypeInfo
*TypeInfo
) {
1158 SMLoc FirstTokenLoc
= getLexer().getLoc();
1159 AsmToken::TokenKind FirstTokenKind
= Lexer
.getKind();
1160 switch (FirstTokenKind
) {
1162 return TokError("unknown token in expression");
1163 // If we have an error assume that we've already handled it.
1164 case AsmToken::Error
:
1166 case AsmToken::Exclaim
:
1167 Lex(); // Eat the operator.
1168 if (parsePrimaryExpr(Res
, EndLoc
, TypeInfo
))
1170 Res
= MCUnaryExpr::createLNot(Res
, getContext(), FirstTokenLoc
);
1172 case AsmToken::Dollar
:
1173 case AsmToken::Star
:
1175 case AsmToken::String
:
1176 case AsmToken::Identifier
: {
1177 StringRef Identifier
;
1178 if (parseIdentifier(Identifier
)) {
1179 // We may have failed but '$'|'*' may be a valid token in context of
1181 if (getTok().is(AsmToken::Dollar
) || getTok().is(AsmToken::Star
)) {
1182 bool ShouldGenerateTempSymbol
= false;
1183 if ((getTok().is(AsmToken::Dollar
) && MAI
.getDollarIsPC()) ||
1184 (getTok().is(AsmToken::Star
) && MAI
.getStarIsPC()))
1185 ShouldGenerateTempSymbol
= true;
1187 if (!ShouldGenerateTempSymbol
)
1188 return Error(FirstTokenLoc
, "invalid token in expression");
1190 // Eat the '$'|'*' token.
1192 // This is either a '$'|'*' reference, which references the current PC.
1193 // Emit a temporary label to the streamer and refer to it.
1194 MCSymbol
*Sym
= Ctx
.createTempSymbol();
1196 Res
= MCSymbolRefExpr::create(Sym
, MCSymbolRefExpr::VK_None
,
1198 EndLoc
= FirstTokenLoc
;
1202 // Parse symbol variant
1203 std::pair
<StringRef
, StringRef
> Split
;
1204 if (!MAI
.useParensForSymbolVariant()) {
1205 if (FirstTokenKind
== AsmToken::String
) {
1206 if (Lexer
.is(AsmToken::At
)) {
1208 SMLoc AtLoc
= getLexer().getLoc();
1210 if (parseIdentifier(VName
))
1211 return Error(AtLoc
, "expected symbol variant after '@'");
1213 Split
= std::make_pair(Identifier
, VName
);
1216 Split
= Identifier
.split('@');
1218 } else if (Lexer
.is(AsmToken::LParen
)) {
1221 parseIdentifier(VName
);
1224 Split
= std::make_pair(Identifier
, VName
);
1227 EndLoc
= SMLoc::getFromPointer(Identifier
.end());
1229 // This is a symbol reference.
1230 StringRef SymbolName
= Identifier
;
1231 if (SymbolName
.empty())
1232 return Error(getLexer().getLoc(), "expected a symbol reference");
1234 MCSymbolRefExpr::VariantKind Variant
= MCSymbolRefExpr::VK_None
;
1236 // Lookup the symbol variant if used.
1237 if (!Split
.second
.empty()) {
1238 Variant
= getTargetParser().getVariantKindForName(Split
.second
);
1239 if (Variant
!= MCSymbolRefExpr::VK_Invalid
) {
1240 SymbolName
= Split
.first
;
1241 } else if (MAI
.doesAllowAtInName() && !MAI
.useParensForSymbolVariant()) {
1242 Variant
= MCSymbolRefExpr::VK_None
;
1244 return Error(SMLoc::getFromPointer(Split
.second
.begin()),
1245 "invalid variant '" + Split
.second
+ "'");
1249 MCSymbol
*Sym
= getContext().getInlineAsmLabel(SymbolName
);
1251 Sym
= getContext().getOrCreateSymbol(
1252 MAI
.shouldEmitLabelsInUpperCase() ? SymbolName
.upper() : SymbolName
);
1254 // If this is an absolute variable reference, substitute it now to preserve
1255 // semantics in the face of reassignment.
1256 if (Sym
->isVariable()) {
1257 auto V
= Sym
->getVariableValue(/*SetUsed*/ false);
1258 bool DoInline
= isa
<MCConstantExpr
>(V
) && !Variant
;
1259 if (auto TV
= dyn_cast
<MCTargetExpr
>(V
))
1260 DoInline
= TV
->inlineAssignedExpr();
1263 return Error(EndLoc
, "unexpected modifier on variable reference");
1264 Res
= Sym
->getVariableValue(/*SetUsed*/ false);
1269 // Otherwise create a symbol ref.
1270 Res
= MCSymbolRefExpr::create(Sym
, Variant
, getContext(), FirstTokenLoc
);
1273 case AsmToken::BigNum
:
1274 return TokError("literal value out of range for directive");
1275 case AsmToken::Integer
: {
1276 SMLoc Loc
= getTok().getLoc();
1277 int64_t IntVal
= getTok().getIntVal();
1278 Res
= MCConstantExpr::create(IntVal
, getContext());
1279 EndLoc
= Lexer
.getTok().getEndLoc();
1280 Lex(); // Eat token.
1281 // Look for 'b' or 'f' following an Integer as a directional label
1282 if (Lexer
.getKind() == AsmToken::Identifier
) {
1283 StringRef IDVal
= getTok().getString();
1284 // Lookup the symbol variant if used.
1285 std::pair
<StringRef
, StringRef
> Split
= IDVal
.split('@');
1286 MCSymbolRefExpr::VariantKind Variant
= MCSymbolRefExpr::VK_None
;
1287 if (Split
.first
.size() != IDVal
.size()) {
1288 Variant
= MCSymbolRefExpr::getVariantKindForName(Split
.second
);
1289 if (Variant
== MCSymbolRefExpr::VK_Invalid
)
1290 return TokError("invalid variant '" + Split
.second
+ "'");
1291 IDVal
= Split
.first
;
1293 if (IDVal
== "f" || IDVal
== "b") {
1295 Ctx
.getDirectionalLocalSymbol(IntVal
, IDVal
== "b");
1296 Res
= MCSymbolRefExpr::create(Sym
, Variant
, getContext());
1297 if (IDVal
== "b" && Sym
->isUndefined())
1298 return Error(Loc
, "directional label undefined");
1299 DirLabels
.push_back(std::make_tuple(Loc
, CppHashInfo
, Sym
));
1300 EndLoc
= Lexer
.getTok().getEndLoc();
1301 Lex(); // Eat identifier.
1306 case AsmToken::Real
: {
1307 APFloat
RealVal(APFloat::IEEEdouble(), getTok().getString());
1308 uint64_t IntVal
= RealVal
.bitcastToAPInt().getZExtValue();
1309 Res
= MCConstantExpr::create(IntVal
, getContext());
1310 EndLoc
= Lexer
.getTok().getEndLoc();
1311 Lex(); // Eat token.
1314 case AsmToken::Dot
: {
1315 if (!MAI
.getDotIsPC())
1316 return TokError("cannot use . as current PC");
1318 // This is a '.' reference, which references the current PC. Emit a
1319 // temporary label to the streamer and refer to it.
1320 MCSymbol
*Sym
= Ctx
.createTempSymbol();
1322 Res
= MCSymbolRefExpr::create(Sym
, MCSymbolRefExpr::VK_None
, getContext());
1323 EndLoc
= Lexer
.getTok().getEndLoc();
1324 Lex(); // Eat identifier.
1327 case AsmToken::LParen
:
1328 Lex(); // Eat the '('.
1329 return parseParenExpr(Res
, EndLoc
);
1330 case AsmToken::LBrac
:
1331 if (!PlatformParser
->HasBracketExpressions())
1332 return TokError("brackets expression not supported on this target");
1333 Lex(); // Eat the '['.
1334 return parseBracketExpr(Res
, EndLoc
);
1335 case AsmToken::Minus
:
1336 Lex(); // Eat the operator.
1337 if (parsePrimaryExpr(Res
, EndLoc
, TypeInfo
))
1339 Res
= MCUnaryExpr::createMinus(Res
, getContext(), FirstTokenLoc
);
1341 case AsmToken::Plus
:
1342 Lex(); // Eat the operator.
1343 if (parsePrimaryExpr(Res
, EndLoc
, TypeInfo
))
1345 Res
= MCUnaryExpr::createPlus(Res
, getContext(), FirstTokenLoc
);
1347 case AsmToken::Tilde
:
1348 Lex(); // Eat the operator.
1349 if (parsePrimaryExpr(Res
, EndLoc
, TypeInfo
))
1351 Res
= MCUnaryExpr::createNot(Res
, getContext(), FirstTokenLoc
);
1353 // MIPS unary expression operators. The lexer won't generate these tokens if
1354 // MCAsmInfo::HasMipsExpressions is false for the target.
1355 case AsmToken::PercentCall16
:
1356 case AsmToken::PercentCall_Hi
:
1357 case AsmToken::PercentCall_Lo
:
1358 case AsmToken::PercentDtprel_Hi
:
1359 case AsmToken::PercentDtprel_Lo
:
1360 case AsmToken::PercentGot
:
1361 case AsmToken::PercentGot_Disp
:
1362 case AsmToken::PercentGot_Hi
:
1363 case AsmToken::PercentGot_Lo
:
1364 case AsmToken::PercentGot_Ofst
:
1365 case AsmToken::PercentGot_Page
:
1366 case AsmToken::PercentGottprel
:
1367 case AsmToken::PercentGp_Rel
:
1368 case AsmToken::PercentHi
:
1369 case AsmToken::PercentHigher
:
1370 case AsmToken::PercentHighest
:
1371 case AsmToken::PercentLo
:
1372 case AsmToken::PercentNeg
:
1373 case AsmToken::PercentPcrel_Hi
:
1374 case AsmToken::PercentPcrel_Lo
:
1375 case AsmToken::PercentTlsgd
:
1376 case AsmToken::PercentTlsldm
:
1377 case AsmToken::PercentTprel_Hi
:
1378 case AsmToken::PercentTprel_Lo
:
1379 Lex(); // Eat the operator.
1380 if (Lexer
.isNot(AsmToken::LParen
))
1381 return TokError("expected '(' after operator");
1382 Lex(); // Eat the operator.
1383 if (parseExpression(Res
, EndLoc
))
1387 Res
= getTargetParser().createTargetUnaryExpr(Res
, FirstTokenKind
, Ctx
);
1392 bool AsmParser::parseExpression(const MCExpr
*&Res
) {
1394 return parseExpression(Res
, EndLoc
);
1398 AsmParser::applyModifierToExpr(const MCExpr
*E
,
1399 MCSymbolRefExpr::VariantKind Variant
) {
1400 // Ask the target implementation about this expression first.
1401 const MCExpr
*NewE
= getTargetParser().applyModifierToExpr(E
, Variant
, Ctx
);
1404 // Recurse over the given expression, rebuilding it to apply the given variant
1405 // if there is exactly one symbol.
1406 switch (E
->getKind()) {
1407 case MCExpr::Target
:
1408 case MCExpr::Constant
:
1411 case MCExpr::SymbolRef
: {
1412 const MCSymbolRefExpr
*SRE
= cast
<MCSymbolRefExpr
>(E
);
1414 if (SRE
->getKind() != MCSymbolRefExpr::VK_None
) {
1415 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1416 "' (already modified)");
1420 return MCSymbolRefExpr::create(&SRE
->getSymbol(), Variant
, getContext());
1423 case MCExpr::Unary
: {
1424 const MCUnaryExpr
*UE
= cast
<MCUnaryExpr
>(E
);
1425 const MCExpr
*Sub
= applyModifierToExpr(UE
->getSubExpr(), Variant
);
1428 return MCUnaryExpr::create(UE
->getOpcode(), Sub
, getContext());
1431 case MCExpr::Binary
: {
1432 const MCBinaryExpr
*BE
= cast
<MCBinaryExpr
>(E
);
1433 const MCExpr
*LHS
= applyModifierToExpr(BE
->getLHS(), Variant
);
1434 const MCExpr
*RHS
= applyModifierToExpr(BE
->getRHS(), Variant
);
1444 return MCBinaryExpr::create(BE
->getOpcode(), LHS
, RHS
, getContext());
1448 llvm_unreachable("Invalid expression kind!");
1451 /// This function checks if the next token is <string> type or arithmetic.
1452 /// string that begin with character '<' must end with character '>'.
1453 /// otherwise it is arithmetics.
1454 /// If the function returns a 'true' value,
1455 /// the End argument will be filled with the last location pointed to the '>'
1458 /// There is a gap between the AltMacro's documentation and the single quote
1459 /// implementation. GCC does not fully support this feature and so we will not
1461 /// TODO: Adding single quote as a string.
1462 static bool isAngleBracketString(SMLoc
&StrLoc
, SMLoc
&EndLoc
) {
1463 assert((StrLoc
.getPointer() != nullptr) &&
1464 "Argument to the function cannot be a NULL value");
1465 const char *CharPtr
= StrLoc
.getPointer();
1466 while ((*CharPtr
!= '>') && (*CharPtr
!= '\n') && (*CharPtr
!= '\r') &&
1467 (*CharPtr
!= '\0')) {
1468 if (*CharPtr
== '!')
1472 if (*CharPtr
== '>') {
1473 EndLoc
= StrLoc
.getFromPointer(CharPtr
+ 1);
1479 /// creating a string without the escape characters '!'.
1480 static std::string
angleBracketString(StringRef AltMacroStr
) {
1482 for (size_t Pos
= 0; Pos
< AltMacroStr
.size(); Pos
++) {
1483 if (AltMacroStr
[Pos
] == '!')
1485 Res
+= AltMacroStr
[Pos
];
1490 /// Parse an expression and return it.
1492 /// expr ::= expr &&,|| expr -> lowest.
1493 /// expr ::= expr |,^,&,! expr
1494 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1495 /// expr ::= expr <<,>> expr
1496 /// expr ::= expr +,- expr
1497 /// expr ::= expr *,/,% expr -> highest.
1498 /// expr ::= primaryexpr
1500 bool AsmParser::parseExpression(const MCExpr
*&Res
, SMLoc
&EndLoc
) {
1501 // Parse the expression.
1503 if (getTargetParser().parsePrimaryExpr(Res
, EndLoc
) ||
1504 parseBinOpRHS(1, Res
, EndLoc
))
1507 // As a special case, we support 'a op b @ modifier' by rewriting the
1508 // expression to include the modifier. This is inefficient, but in general we
1509 // expect users to use 'a@modifier op b'.
1510 if (parseOptionalToken(AsmToken::At
)) {
1511 if (Lexer
.isNot(AsmToken::Identifier
))
1512 return TokError("unexpected symbol modifier following '@'");
1514 MCSymbolRefExpr::VariantKind Variant
=
1515 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1516 if (Variant
== MCSymbolRefExpr::VK_Invalid
)
1517 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1519 const MCExpr
*ModifiedRes
= applyModifierToExpr(Res
, Variant
);
1521 return TokError("invalid modifier '" + getTok().getIdentifier() +
1522 "' (no symbols present)");
1529 // Try to constant fold it up front, if possible. Do not exploit
1532 if (Res
->evaluateAsAbsolute(Value
))
1533 Res
= MCConstantExpr::create(Value
, getContext());
1538 bool AsmParser::parseParenExpression(const MCExpr
*&Res
, SMLoc
&EndLoc
) {
1540 return parseParenExpr(Res
, EndLoc
) || parseBinOpRHS(1, Res
, EndLoc
);
1543 bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth
, const MCExpr
*&Res
,
1545 if (parseParenExpr(Res
, EndLoc
))
1548 for (; ParenDepth
> 0; --ParenDepth
) {
1549 if (parseBinOpRHS(1, Res
, EndLoc
))
1552 // We don't Lex() the last RParen.
1553 // This is the same behavior as parseParenExpression().
1554 if (ParenDepth
- 1 > 0) {
1555 EndLoc
= getTok().getEndLoc();
1563 bool AsmParser::parseAbsoluteExpression(int64_t &Res
) {
1566 SMLoc StartLoc
= Lexer
.getLoc();
1567 if (parseExpression(Expr
))
1570 if (!Expr
->evaluateAsAbsolute(Res
, getStreamer().getAssemblerPtr()))
1571 return Error(StartLoc
, "expected absolute expression");
1576 static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K
,
1577 MCBinaryExpr::Opcode
&Kind
,
1578 bool ShouldUseLogicalShr
) {
1581 return 0; // not a binop.
1583 // Lowest Precedence: &&, ||
1584 case AsmToken::AmpAmp
:
1585 Kind
= MCBinaryExpr::LAnd
;
1587 case AsmToken::PipePipe
:
1588 Kind
= MCBinaryExpr::LOr
;
1591 // Low Precedence: |, &, ^
1592 case AsmToken::Pipe
:
1593 Kind
= MCBinaryExpr::Or
;
1595 case AsmToken::Caret
:
1596 Kind
= MCBinaryExpr::Xor
;
1599 Kind
= MCBinaryExpr::And
;
1602 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1603 case AsmToken::EqualEqual
:
1604 Kind
= MCBinaryExpr::EQ
;
1606 case AsmToken::ExclaimEqual
:
1607 case AsmToken::LessGreater
:
1608 Kind
= MCBinaryExpr::NE
;
1610 case AsmToken::Less
:
1611 Kind
= MCBinaryExpr::LT
;
1613 case AsmToken::LessEqual
:
1614 Kind
= MCBinaryExpr::LTE
;
1616 case AsmToken::Greater
:
1617 Kind
= MCBinaryExpr::GT
;
1619 case AsmToken::GreaterEqual
:
1620 Kind
= MCBinaryExpr::GTE
;
1623 // Intermediate Precedence: <<, >>
1624 case AsmToken::LessLess
:
1625 Kind
= MCBinaryExpr::Shl
;
1627 case AsmToken::GreaterGreater
:
1628 Kind
= ShouldUseLogicalShr
? MCBinaryExpr::LShr
: MCBinaryExpr::AShr
;
1631 // High Intermediate Precedence: +, -
1632 case AsmToken::Plus
:
1633 Kind
= MCBinaryExpr::Add
;
1635 case AsmToken::Minus
:
1636 Kind
= MCBinaryExpr::Sub
;
1639 // Highest Precedence: *, /, %
1640 case AsmToken::Star
:
1641 Kind
= MCBinaryExpr::Mul
;
1643 case AsmToken::Slash
:
1644 Kind
= MCBinaryExpr::Div
;
1646 case AsmToken::Percent
:
1647 Kind
= MCBinaryExpr::Mod
;
1652 static unsigned getGNUBinOpPrecedence(const MCAsmInfo
&MAI
,
1653 AsmToken::TokenKind K
,
1654 MCBinaryExpr::Opcode
&Kind
,
1655 bool ShouldUseLogicalShr
) {
1658 return 0; // not a binop.
1660 // Lowest Precedence: &&, ||
1661 case AsmToken::AmpAmp
:
1662 Kind
= MCBinaryExpr::LAnd
;
1664 case AsmToken::PipePipe
:
1665 Kind
= MCBinaryExpr::LOr
;
1668 // Low Precedence: ==, !=, <>, <, <=, >, >=
1669 case AsmToken::EqualEqual
:
1670 Kind
= MCBinaryExpr::EQ
;
1672 case AsmToken::ExclaimEqual
:
1673 case AsmToken::LessGreater
:
1674 Kind
= MCBinaryExpr::NE
;
1676 case AsmToken::Less
:
1677 Kind
= MCBinaryExpr::LT
;
1679 case AsmToken::LessEqual
:
1680 Kind
= MCBinaryExpr::LTE
;
1682 case AsmToken::Greater
:
1683 Kind
= MCBinaryExpr::GT
;
1685 case AsmToken::GreaterEqual
:
1686 Kind
= MCBinaryExpr::GTE
;
1689 // Low Intermediate Precedence: +, -
1690 case AsmToken::Plus
:
1691 Kind
= MCBinaryExpr::Add
;
1693 case AsmToken::Minus
:
1694 Kind
= MCBinaryExpr::Sub
;
1697 // High Intermediate Precedence: |, !, &, ^
1699 case AsmToken::Pipe
:
1700 Kind
= MCBinaryExpr::Or
;
1702 case AsmToken::Exclaim
:
1703 // Hack to support ARM compatible aliases (implied 'sp' operand in 'srs*'
1704 // instructions like 'srsda #31!') and not parse ! as an infix operator.
1705 if (MAI
.getCommentString() == "@")
1707 Kind
= MCBinaryExpr::OrNot
;
1709 case AsmToken::Caret
:
1710 Kind
= MCBinaryExpr::Xor
;
1713 Kind
= MCBinaryExpr::And
;
1716 // Highest Precedence: *, /, %, <<, >>
1717 case AsmToken::Star
:
1718 Kind
= MCBinaryExpr::Mul
;
1720 case AsmToken::Slash
:
1721 Kind
= MCBinaryExpr::Div
;
1723 case AsmToken::Percent
:
1724 Kind
= MCBinaryExpr::Mod
;
1726 case AsmToken::LessLess
:
1727 Kind
= MCBinaryExpr::Shl
;
1729 case AsmToken::GreaterGreater
:
1730 Kind
= ShouldUseLogicalShr
? MCBinaryExpr::LShr
: MCBinaryExpr::AShr
;
1735 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K
,
1736 MCBinaryExpr::Opcode
&Kind
) {
1737 bool ShouldUseLogicalShr
= MAI
.shouldUseLogicalShr();
1738 return IsDarwin
? getDarwinBinOpPrecedence(K
, Kind
, ShouldUseLogicalShr
)
1739 : getGNUBinOpPrecedence(MAI
, K
, Kind
, ShouldUseLogicalShr
);
1742 /// Parse all binary operators with precedence >= 'Precedence'.
1743 /// Res contains the LHS of the expression on input.
1744 bool AsmParser::parseBinOpRHS(unsigned Precedence
, const MCExpr
*&Res
,
1746 SMLoc StartLoc
= Lexer
.getLoc();
1748 MCBinaryExpr::Opcode Kind
= MCBinaryExpr::Add
;
1749 unsigned TokPrec
= getBinOpPrecedence(Lexer
.getKind(), Kind
);
1751 // If the next token is lower precedence than we are allowed to eat, return
1752 // successfully with what we ate already.
1753 if (TokPrec
< Precedence
)
1758 // Eat the next primary expression.
1760 if (getTargetParser().parsePrimaryExpr(RHS
, EndLoc
))
1763 // If BinOp binds less tightly with RHS than the operator after RHS, let
1764 // the pending operator take RHS as its LHS.
1765 MCBinaryExpr::Opcode Dummy
;
1766 unsigned NextTokPrec
= getBinOpPrecedence(Lexer
.getKind(), Dummy
);
1767 if (TokPrec
< NextTokPrec
&& parseBinOpRHS(TokPrec
+ 1, RHS
, EndLoc
))
1770 // Merge LHS and RHS according to operator.
1771 Res
= MCBinaryExpr::create(Kind
, Res
, RHS
, getContext(), StartLoc
);
1776 /// ::= EndOfStatement
1777 /// ::= Label* Directive ...Operands... EndOfStatement
1778 /// ::= Label* Identifier OperandList* EndOfStatement
1779 bool AsmParser::parseStatement(ParseStatementInfo
&Info
,
1780 MCAsmParserSemaCallback
*SI
) {
1781 assert(!hasPendingError() && "parseStatement started with pending error");
1782 // Eat initial spaces and comments
1783 while (Lexer
.is(AsmToken::Space
))
1785 if (Lexer
.is(AsmToken::EndOfStatement
)) {
1786 // if this is a line comment we can drop it safely
1787 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
1788 getTok().getString().front() == '\n')
1793 // Statements always start with an identifier.
1794 AsmToken ID
= getTok();
1795 SMLoc IDLoc
= ID
.getLoc();
1797 int64_t LocalLabelVal
= -1;
1798 StartTokLoc
= ID
.getLoc();
1799 if (Lexer
.is(AsmToken::HashDirective
))
1800 return parseCppHashLineFilenameComment(IDLoc
,
1801 !isInsideMacroInstantiation());
1803 // Allow an integer followed by a ':' as a directional local label.
1804 if (Lexer
.is(AsmToken::Integer
)) {
1805 LocalLabelVal
= getTok().getIntVal();
1806 if (LocalLabelVal
< 0) {
1807 if (!TheCondState
.Ignore
) {
1808 Lex(); // always eat a token
1809 return Error(IDLoc
, "unexpected token at start of statement");
1813 IDVal
= getTok().getString();
1814 Lex(); // Consume the integer token to be used as an identifier token.
1815 if (Lexer
.getKind() != AsmToken::Colon
) {
1816 if (!TheCondState
.Ignore
) {
1817 Lex(); // always eat a token
1818 return Error(IDLoc
, "unexpected token at start of statement");
1822 } else if (Lexer
.is(AsmToken::Dot
)) {
1823 // Treat '.' as a valid identifier in this context.
1826 } else if (Lexer
.is(AsmToken::LCurly
)) {
1827 // Treat '{' as a valid identifier in this context.
1831 } else if (Lexer
.is(AsmToken::RCurly
)) {
1832 // Treat '}' as a valid identifier in this context.
1835 } else if (Lexer
.is(AsmToken::Star
) &&
1836 getTargetParser().starIsStartOfStatement()) {
1837 // Accept '*' as a valid start of statement.
1840 } else if (parseIdentifier(IDVal
)) {
1841 if (!TheCondState
.Ignore
) {
1842 Lex(); // always eat a token
1843 return Error(IDLoc
, "unexpected token at start of statement");
1848 // Handle conditional assembly here before checking for skipping. We
1849 // have to do this so that .endif isn't skipped in a ".if 0" block for
1851 StringMap
<DirectiveKind
>::const_iterator DirKindIt
=
1852 DirectiveKindMap
.find(IDVal
.lower());
1853 DirectiveKind DirKind
= (DirKindIt
== DirectiveKindMap
.end())
1855 : DirKindIt
->getValue();
1866 return parseDirectiveIf(IDLoc
, DirKind
);
1868 return parseDirectiveIfb(IDLoc
, true);
1870 return parseDirectiveIfb(IDLoc
, false);
1872 return parseDirectiveIfc(IDLoc
, true);
1874 return parseDirectiveIfeqs(IDLoc
, true);
1876 return parseDirectiveIfc(IDLoc
, false);
1878 return parseDirectiveIfeqs(IDLoc
, false);
1880 return parseDirectiveIfdef(IDLoc
, true);
1883 return parseDirectiveIfdef(IDLoc
, false);
1885 return parseDirectiveElseIf(IDLoc
);
1887 return parseDirectiveElse(IDLoc
);
1889 return parseDirectiveEndIf(IDLoc
);
1892 // Ignore the statement if in the middle of inactive conditional
1894 if (TheCondState
.Ignore
) {
1895 eatToEndOfStatement();
1899 // FIXME: Recurse on local labels?
1901 // Check for a label.
1902 // ::= identifier ':'
1904 if (Lexer
.is(AsmToken::Colon
) && getTargetParser().isLabel(ID
)) {
1905 if (checkForValidSection())
1908 Lex(); // Consume the ':'.
1910 // Diagnose attempt to use '.' as a label.
1912 return Error(IDLoc
, "invalid use of pseudo-symbol '.' as a label");
1914 // Diagnose attempt to use a variable as a label.
1916 // FIXME: Diagnostics. Note the location of the definition as a label.
1917 // FIXME: This doesn't diagnose assignment to a symbol which has been
1918 // implicitly marked as external.
1920 if (LocalLabelVal
== -1) {
1921 if (ParsingMSInlineAsm
&& SI
) {
1922 StringRef RewrittenLabel
=
1923 SI
->LookupInlineAsmLabel(IDVal
, getSourceManager(), IDLoc
, true);
1924 assert(!RewrittenLabel
.empty() &&
1925 "We should have an internal name here.");
1926 Info
.AsmRewrites
->emplace_back(AOK_Label
, IDLoc
, IDVal
.size(),
1928 IDVal
= RewrittenLabel
;
1930 Sym
= getContext().getOrCreateSymbol(IDVal
);
1932 Sym
= Ctx
.createDirectionalLocalSymbol(LocalLabelVal
);
1933 // End of Labels should be treated as end of line for lexing
1934 // purposes but that information is not available to the Lexer who
1935 // does not understand Labels. This may cause us to see a Hash
1936 // here instead of a preprocessor line comment.
1937 if (getTok().is(AsmToken::Hash
)) {
1938 StringRef CommentStr
= parseStringToEndOfStatement();
1940 Lexer
.UnLex(AsmToken(AsmToken::EndOfStatement
, CommentStr
));
1943 // Consume any end of statement token, if present, to avoid spurious
1944 // addBlankLine calls().
1945 if (getTok().is(AsmToken::EndOfStatement
)) {
1949 if (MAI
.hasSubsectionsViaSymbols() && CFIStartProcLoc
&&
1950 Sym
->isExternal() && !cast
<MCSymbolMachO
>(Sym
)->isAltEntry())
1951 return Error(StartTokLoc
, "non-private labels cannot appear between "
1952 ".cfi_startproc / .cfi_endproc pairs") &&
1953 Error(*CFIStartProcLoc
, "previous .cfi_startproc was here");
1955 if (discardLTOSymbol(IDVal
))
1958 getTargetParser().doBeforeLabelEmit(Sym
, IDLoc
);
1961 if (!getTargetParser().isParsingMSInlineAsm())
1962 Out
.emitLabel(Sym
, IDLoc
);
1964 // If we are generating dwarf for assembly source files then gather the
1965 // info to make a dwarf label entry for this label if needed.
1966 if (enabledGenDwarfForAssembly())
1967 MCGenDwarfLabelEntry::Make(Sym
, &getStreamer(), getSourceManager(),
1970 getTargetParser().onLabelParsed(Sym
);
1975 // Check for an assignment statement.
1976 // ::= identifier '='
1977 if (Lexer
.is(AsmToken::Equal
) && getTargetParser().equalIsAsmAssignment()) {
1979 return parseAssignment(IDVal
, AssignmentKind::Equal
);
1982 // If macros are enabled, check to see if this is a macro instantiation.
1983 if (areMacrosEnabled())
1984 if (MCAsmMacro
*M
= getContext().lookupMacro(IDVal
))
1985 return handleMacroEntry(M
, IDLoc
);
1987 // Otherwise, we have a normal instruction or directive.
1989 // Directives start with "."
1990 if (IDVal
.starts_with(".") && IDVal
!= ".") {
1991 // There are several entities interested in parsing directives:
1993 // 1. The target-specific assembly parser. Some directives are target
1994 // specific or may potentially behave differently on certain targets.
1995 // 2. Asm parser extensions. For example, platform-specific parsers
1996 // (like the ELF parser) register themselves as extensions.
1997 // 3. The generic directive parser implemented by this class. These are
1998 // all the directives that behave in a target and platform independent
1999 // manner, or at least have a default behavior that's shared between
2000 // all targets and platforms.
2002 getTargetParser().flushPendingInstructions(getStreamer());
2004 ParseStatus TPDirectiveReturn
= getTargetParser().parseDirective(ID
);
2005 assert(TPDirectiveReturn
.isFailure() == hasPendingError() &&
2006 "Should only return Failure iff there was an error");
2007 if (TPDirectiveReturn
.isFailure())
2009 if (TPDirectiveReturn
.isSuccess())
2012 // Next, check the extension directive map to see if any extension has
2013 // registered itself to parse this directive.
2014 std::pair
<MCAsmParserExtension
*, DirectiveHandler
> Handler
=
2015 ExtensionDirectiveMap
.lookup(IDVal
);
2017 return (*Handler
.second
)(Handler
.first
, IDVal
, IDLoc
);
2019 // Finally, if no one else is interested in this directive, it must be
2020 // generic and familiar to this class.
2026 return parseDirectiveSet(IDVal
, AssignmentKind::Set
);
2028 return parseDirectiveSet(IDVal
, AssignmentKind::Equiv
);
2029 case DK_LTO_SET_CONDITIONAL
:
2030 return parseDirectiveSet(IDVal
, AssignmentKind::LTOSetConditional
);
2032 return parseDirectiveAscii(IDVal
, false);
2035 return parseDirectiveAscii(IDVal
, true);
2038 return parseDirectiveValue(IDVal
, 1);
2044 return parseDirectiveValue(IDVal
, 2);
2049 return parseDirectiveValue(IDVal
, 4);
2052 return parseDirectiveValue(IDVal
, 8);
2054 return parseDirectiveValue(
2055 IDVal
, getContext().getAsmInfo()->getCodePointerSize());
2057 return parseDirectiveOctaValue(IDVal
);
2061 return parseDirectiveRealValue(IDVal
, APFloat::IEEEsingle());
2064 return parseDirectiveRealValue(IDVal
, APFloat::IEEEdouble());
2066 bool IsPow2
= !getContext().getAsmInfo()->getAlignmentIsInBytes();
2067 return parseDirectiveAlign(IsPow2
, /*ExprSize=*/1);
2070 bool IsPow2
= !getContext().getAsmInfo()->getAlignmentIsInBytes();
2071 return parseDirectiveAlign(IsPow2
, /*ExprSize=*/4);
2074 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
2076 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
2078 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
2080 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
2082 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
2084 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
2086 return parseDirectiveOrg();
2088 return parseDirectiveFill();
2090 return parseDirectiveZero();
2092 eatToEndOfStatement(); // .extern is the default, ignore it.
2096 return parseDirectiveSymbolAttribute(MCSA_Global
);
2097 case DK_LAZY_REFERENCE
:
2098 return parseDirectiveSymbolAttribute(MCSA_LazyReference
);
2099 case DK_NO_DEAD_STRIP
:
2100 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip
);
2101 case DK_SYMBOL_RESOLVER
:
2102 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver
);
2103 case DK_PRIVATE_EXTERN
:
2104 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern
);
2106 return parseDirectiveSymbolAttribute(MCSA_Reference
);
2107 case DK_WEAK_DEFINITION
:
2108 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition
);
2109 case DK_WEAK_REFERENCE
:
2110 return parseDirectiveSymbolAttribute(MCSA_WeakReference
);
2111 case DK_WEAK_DEF_CAN_BE_HIDDEN
:
2112 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate
);
2114 return parseDirectiveSymbolAttribute(MCSA_Cold
);
2117 return parseDirectiveComm(/*IsLocal=*/false);
2119 return parseDirectiveComm(/*IsLocal=*/true);
2121 return parseDirectiveAbort(IDLoc
);
2123 return parseDirectiveInclude();
2125 return parseDirectiveIncbin();
2128 return TokError(Twine(IDVal
) +
2129 " not currently supported for this target");
2131 return parseDirectiveRept(IDLoc
, IDVal
);
2133 return parseDirectiveIrp(IDLoc
);
2135 return parseDirectiveIrpc(IDLoc
);
2137 return parseDirectiveEndr(IDLoc
);
2138 case DK_BUNDLE_ALIGN_MODE
:
2139 return parseDirectiveBundleAlignMode();
2140 case DK_BUNDLE_LOCK
:
2141 return parseDirectiveBundleLock();
2142 case DK_BUNDLE_UNLOCK
:
2143 return parseDirectiveBundleUnlock();
2145 return parseDirectiveLEB128(true);
2147 return parseDirectiveLEB128(false);
2150 return parseDirectiveSpace(IDVal
);
2152 return parseDirectiveFile(IDLoc
);
2154 return parseDirectiveLine();
2156 return parseDirectiveLoc();
2158 return parseDirectiveLocLabel(IDLoc
);
2160 return parseDirectiveStabs();
2162 return parseDirectiveCVFile();
2164 return parseDirectiveCVFuncId();
2165 case DK_CV_INLINE_SITE_ID
:
2166 return parseDirectiveCVInlineSiteId();
2168 return parseDirectiveCVLoc();
2169 case DK_CV_LINETABLE
:
2170 return parseDirectiveCVLinetable();
2171 case DK_CV_INLINE_LINETABLE
:
2172 return parseDirectiveCVInlineLinetable();
2173 case DK_CV_DEF_RANGE
:
2174 return parseDirectiveCVDefRange();
2176 return parseDirectiveCVString();
2177 case DK_CV_STRINGTABLE
:
2178 return parseDirectiveCVStringTable();
2179 case DK_CV_FILECHECKSUMS
:
2180 return parseDirectiveCVFileChecksums();
2181 case DK_CV_FILECHECKSUM_OFFSET
:
2182 return parseDirectiveCVFileChecksumOffset();
2183 case DK_CV_FPO_DATA
:
2184 return parseDirectiveCVFPOData();
2185 case DK_CFI_SECTIONS
:
2186 return parseDirectiveCFISections();
2187 case DK_CFI_STARTPROC
:
2188 return parseDirectiveCFIStartProc();
2189 case DK_CFI_ENDPROC
:
2190 return parseDirectiveCFIEndProc();
2191 case DK_CFI_DEF_CFA
:
2192 return parseDirectiveCFIDefCfa(IDLoc
);
2193 case DK_CFI_DEF_CFA_OFFSET
:
2194 return parseDirectiveCFIDefCfaOffset(IDLoc
);
2195 case DK_CFI_ADJUST_CFA_OFFSET
:
2196 return parseDirectiveCFIAdjustCfaOffset(IDLoc
);
2197 case DK_CFI_DEF_CFA_REGISTER
:
2198 return parseDirectiveCFIDefCfaRegister(IDLoc
);
2199 case DK_CFI_LLVM_DEF_ASPACE_CFA
:
2200 return parseDirectiveCFILLVMDefAspaceCfa(IDLoc
);
2202 return parseDirectiveCFIOffset(IDLoc
);
2203 case DK_CFI_REL_OFFSET
:
2204 return parseDirectiveCFIRelOffset(IDLoc
);
2205 case DK_CFI_PERSONALITY
:
2206 return parseDirectiveCFIPersonalityOrLsda(true);
2208 return parseDirectiveCFIPersonalityOrLsda(false);
2209 case DK_CFI_REMEMBER_STATE
:
2210 return parseDirectiveCFIRememberState(IDLoc
);
2211 case DK_CFI_RESTORE_STATE
:
2212 return parseDirectiveCFIRestoreState(IDLoc
);
2213 case DK_CFI_SAME_VALUE
:
2214 return parseDirectiveCFISameValue(IDLoc
);
2215 case DK_CFI_RESTORE
:
2216 return parseDirectiveCFIRestore(IDLoc
);
2218 return parseDirectiveCFIEscape(IDLoc
);
2219 case DK_CFI_RETURN_COLUMN
:
2220 return parseDirectiveCFIReturnColumn(IDLoc
);
2221 case DK_CFI_SIGNAL_FRAME
:
2222 return parseDirectiveCFISignalFrame(IDLoc
);
2223 case DK_CFI_UNDEFINED
:
2224 return parseDirectiveCFIUndefined(IDLoc
);
2225 case DK_CFI_REGISTER
:
2226 return parseDirectiveCFIRegister(IDLoc
);
2227 case DK_CFI_WINDOW_SAVE
:
2228 return parseDirectiveCFIWindowSave(IDLoc
);
2230 return parseDirectiveCFILabel(IDLoc
);
2231 case DK_CFI_VAL_OFFSET
:
2232 return parseDirectiveCFIValOffset(IDLoc
);
2235 return parseDirectiveMacrosOnOff(IDVal
);
2237 return parseDirectiveMacro(IDLoc
);
2240 return parseDirectiveAltmacro(IDVal
);
2242 return parseDirectiveExitMacro(IDVal
);
2245 return parseDirectiveEndMacro(IDVal
);
2247 return parseDirectivePurgeMacro(IDLoc
);
2249 return parseDirectiveEnd(IDLoc
);
2251 return parseDirectiveError(IDLoc
, false);
2253 return parseDirectiveError(IDLoc
, true);
2255 return parseDirectiveWarning(IDLoc
);
2257 return parseDirectiveReloc(IDLoc
);
2260 return parseDirectiveDCB(IDVal
, 2);
2262 return parseDirectiveDCB(IDVal
, 1);
2264 return parseDirectiveRealDCB(IDVal
, APFloat::IEEEdouble());
2266 return parseDirectiveDCB(IDVal
, 4);
2268 return parseDirectiveRealDCB(IDVal
, APFloat::IEEEsingle());
2271 return TokError(Twine(IDVal
) +
2272 " not currently supported for this target");
2275 return parseDirectiveDS(IDVal
, 2);
2277 return parseDirectiveDS(IDVal
, 1);
2279 return parseDirectiveDS(IDVal
, 8);
2282 return parseDirectiveDS(IDVal
, 4);
2285 return parseDirectiveDS(IDVal
, 12);
2287 return parseDirectivePrint(IDLoc
);
2289 return parseDirectiveAddrsig();
2290 case DK_ADDRSIG_SYM
:
2291 return parseDirectiveAddrsigSym();
2292 case DK_PSEUDO_PROBE
:
2293 return parseDirectivePseudoProbe();
2294 case DK_LTO_DISCARD
:
2295 return parseDirectiveLTODiscard();
2297 return parseDirectiveSymbolAttribute(MCSA_Memtag
);
2300 return Error(IDLoc
, "unknown directive");
2303 // __asm _emit or __asm __emit
2304 if (ParsingMSInlineAsm
&& (IDVal
== "_emit" || IDVal
== "__emit" ||
2305 IDVal
== "_EMIT" || IDVal
== "__EMIT"))
2306 return parseDirectiveMSEmit(IDLoc
, Info
, IDVal
.size());
2309 if (ParsingMSInlineAsm
&& (IDVal
== "align" || IDVal
== "ALIGN"))
2310 return parseDirectiveMSAlign(IDLoc
, Info
);
2312 if (ParsingMSInlineAsm
&& (IDVal
== "even" || IDVal
== "EVEN"))
2313 Info
.AsmRewrites
->emplace_back(AOK_EVEN
, IDLoc
, 4);
2314 if (checkForValidSection())
2317 return parseAndMatchAndEmitTargetInstruction(Info
, IDVal
, ID
, IDLoc
);
2320 bool AsmParser::parseAndMatchAndEmitTargetInstruction(ParseStatementInfo
&Info
,
2324 // Canonicalize the opcode to lower case.
2325 std::string OpcodeStr
= IDVal
.lower();
2326 ParseInstructionInfo
IInfo(Info
.AsmRewrites
);
2327 bool ParseHadError
= getTargetParser().parseInstruction(IInfo
, OpcodeStr
, ID
,
2328 Info
.ParsedOperands
);
2329 Info
.ParseError
= ParseHadError
;
2331 // Dump the parsed representation, if requested.
2332 if (getShowParsedOperands()) {
2333 SmallString
<256> Str
;
2334 raw_svector_ostream
OS(Str
);
2335 OS
<< "parsed instruction: [";
2336 for (unsigned i
= 0; i
!= Info
.ParsedOperands
.size(); ++i
) {
2339 Info
.ParsedOperands
[i
]->print(OS
);
2343 printMessage(IDLoc
, SourceMgr::DK_Note
, OS
.str());
2346 // Fail even if ParseInstruction erroneously returns false.
2347 if (hasPendingError() || ParseHadError
)
2350 // If we are generating dwarf for the current section then generate a .loc
2351 // directive for the instruction.
2352 if (!ParseHadError
&& enabledGenDwarfForAssembly() &&
2353 getContext().getGenDwarfSectionSyms().count(
2354 getStreamer().getCurrentSectionOnly())) {
2356 if (ActiveMacros
.empty())
2357 Line
= SrcMgr
.FindLineNumber(IDLoc
, CurBuffer
);
2359 Line
= SrcMgr
.FindLineNumber(ActiveMacros
.front()->InstantiationLoc
,
2360 ActiveMacros
.front()->ExitBuffer
);
2362 // If we previously parsed a cpp hash file line comment then make sure the
2363 // current Dwarf File is for the CppHashFilename if not then emit the
2364 // Dwarf File table for it and adjust the line number for the .loc.
2365 if (!CppHashInfo
.Filename
.empty()) {
2366 unsigned FileNumber
= getStreamer().emitDwarfFileDirective(
2367 0, StringRef(), CppHashInfo
.Filename
);
2368 getContext().setGenDwarfFileNumber(FileNumber
);
2370 unsigned CppHashLocLineNo
=
2371 SrcMgr
.FindLineNumber(CppHashInfo
.Loc
, CppHashInfo
.Buf
);
2372 Line
= CppHashInfo
.LineNumber
- 1 + (Line
- CppHashLocLineNo
);
2375 getStreamer().emitDwarfLocDirective(
2376 getContext().getGenDwarfFileNumber(), Line
, 0,
2377 DWARF2_LINE_DEFAULT_IS_STMT
? DWARF2_FLAG_IS_STMT
: 0, 0, 0,
2381 // If parsing succeeded, match the instruction.
2382 if (!ParseHadError
) {
2384 if (getTargetParser().matchAndEmitInstruction(
2385 IDLoc
, Info
.Opcode
, Info
.ParsedOperands
, Out
, ErrorInfo
,
2386 getTargetParser().isParsingMSInlineAsm()))
2392 // Parse and erase curly braces marking block start/end
2394 AsmParser::parseCurlyBlockScope(SmallVectorImpl
<AsmRewrite
> &AsmStrRewrites
) {
2395 // Identify curly brace marking block start/end
2396 if (Lexer
.isNot(AsmToken::LCurly
) && Lexer
.isNot(AsmToken::RCurly
))
2399 SMLoc StartLoc
= Lexer
.getLoc();
2400 Lex(); // Eat the brace
2401 if (Lexer
.is(AsmToken::EndOfStatement
))
2402 Lex(); // Eat EndOfStatement following the brace
2404 // Erase the block start/end brace from the output asm string
2405 AsmStrRewrites
.emplace_back(AOK_Skip
, StartLoc
, Lexer
.getLoc().getPointer() -
2406 StartLoc
.getPointer());
2410 /// parseCppHashLineFilenameComment as this:
2411 /// ::= # number "filename"
2412 bool AsmParser::parseCppHashLineFilenameComment(SMLoc L
, bool SaveLocInfo
) {
2413 Lex(); // Eat the hash token.
2414 // Lexer only ever emits HashDirective if it fully formed if it's
2415 // done the checking already so this is an internal error.
2416 assert(getTok().is(AsmToken::Integer
) &&
2417 "Lexing Cpp line comment: Expected Integer");
2418 int64_t LineNumber
= getTok().getIntVal();
2420 assert(getTok().is(AsmToken::String
) &&
2421 "Lexing Cpp line comment: Expected String");
2422 StringRef Filename
= getTok().getString();
2428 // Get rid of the enclosing quotes.
2429 Filename
= Filename
.substr(1, Filename
.size() - 2);
2431 // Save the SMLoc, Filename and LineNumber for later use by diagnostics
2432 // and possibly DWARF file info.
2433 CppHashInfo
.Loc
= L
;
2434 CppHashInfo
.Filename
= Filename
;
2435 CppHashInfo
.LineNumber
= LineNumber
;
2436 CppHashInfo
.Buf
= CurBuffer
;
2437 if (!HadCppHashFilename
) {
2438 HadCppHashFilename
= true;
2439 // If we haven't encountered any .file directives, then the first #line
2440 // directive describes the "root" file and directory of the compilation
2442 if (getContext().getGenDwarfForAssembly() &&
2443 getContext().getGenDwarfFileNumber() == 0) {
2444 // It's preprocessed, so there is no checksum, and of course no source
2446 getContext().setMCLineTableRootFile(
2447 /*CUID=*/0, getContext().getCompilationDir(), Filename
,
2448 /*Cksum=*/std::nullopt
, /*Source=*/std::nullopt
);
2454 /// will use the last parsed cpp hash line filename comment
2455 /// for the Filename and LineNo if any in the diagnostic.
2456 void AsmParser::DiagHandler(const SMDiagnostic
&Diag
, void *Context
) {
2457 auto *Parser
= static_cast<AsmParser
*>(Context
);
2458 raw_ostream
&OS
= errs();
2460 const SourceMgr
&DiagSrcMgr
= *Diag
.getSourceMgr();
2461 SMLoc DiagLoc
= Diag
.getLoc();
2462 unsigned DiagBuf
= DiagSrcMgr
.FindBufferContainingLoc(DiagLoc
);
2463 unsigned CppHashBuf
=
2464 Parser
->SrcMgr
.FindBufferContainingLoc(Parser
->CppHashInfo
.Loc
);
2466 // Like SourceMgr::printMessage() we need to print the include stack if any
2467 // before printing the message.
2468 unsigned DiagCurBuffer
= DiagSrcMgr
.FindBufferContainingLoc(DiagLoc
);
2469 if (!Parser
->SavedDiagHandler
&& DiagCurBuffer
&&
2470 DiagCurBuffer
!= DiagSrcMgr
.getMainFileID()) {
2471 SMLoc ParentIncludeLoc
= DiagSrcMgr
.getParentIncludeLoc(DiagCurBuffer
);
2472 DiagSrcMgr
.PrintIncludeStack(ParentIncludeLoc
, OS
);
2475 // If we have not parsed a cpp hash line filename comment or the source
2476 // manager changed or buffer changed (like in a nested include) then just
2477 // print the normal diagnostic using its Filename and LineNo.
2478 if (!Parser
->CppHashInfo
.LineNumber
|| DiagBuf
!= CppHashBuf
) {
2479 if (Parser
->SavedDiagHandler
)
2480 Parser
->SavedDiagHandler(Diag
, Parser
->SavedDiagContext
);
2482 Parser
->getContext().diagnose(Diag
);
2486 // Use the CppHashFilename and calculate a line number based on the
2487 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2488 // for the diagnostic.
2489 const std::string
&Filename
= std::string(Parser
->CppHashInfo
.Filename
);
2491 int DiagLocLineNo
= DiagSrcMgr
.FindLineNumber(DiagLoc
, DiagBuf
);
2492 int CppHashLocLineNo
=
2493 Parser
->SrcMgr
.FindLineNumber(Parser
->CppHashInfo
.Loc
, CppHashBuf
);
2495 Parser
->CppHashInfo
.LineNumber
- 1 + (DiagLocLineNo
- CppHashLocLineNo
);
2497 SMDiagnostic
NewDiag(*Diag
.getSourceMgr(), Diag
.getLoc(), Filename
, LineNo
,
2498 Diag
.getColumnNo(), Diag
.getKind(), Diag
.getMessage(),
2499 Diag
.getLineContents(), Diag
.getRanges());
2501 if (Parser
->SavedDiagHandler
)
2502 Parser
->SavedDiagHandler(Diag
, Parser
->SavedDiagContext
);
2504 Parser
->getContext().diagnose(NewDiag
);
2507 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2508 // difference being that that function accepts '@' as part of identifiers and
2509 // we can't do that. AsmLexer.cpp should probably be changed to handle
2510 // '@' as a special case when needed.
2511 static bool isIdentifierChar(char c
) {
2512 return isalnum(static_cast<unsigned char>(c
)) || c
== '_' || c
== '$' ||
2516 bool AsmParser::expandMacro(raw_svector_ostream
&OS
, MCAsmMacro
&Macro
,
2517 ArrayRef
<MCAsmMacroParameter
> Parameters
,
2518 ArrayRef
<MCAsmMacroArgument
> A
,
2519 bool EnableAtPseudoVariable
) {
2520 unsigned NParameters
= Parameters
.size();
2521 auto expandArg
= [&](unsigned Index
) {
2522 bool HasVararg
= NParameters
? Parameters
.back().Vararg
: false;
2523 bool VarargParameter
= HasVararg
&& Index
== (NParameters
- 1);
2524 for (const AsmToken
&Token
: A
[Index
])
2525 // For altmacro mode, you can write '%expr'.
2526 // The prefix '%' evaluates the expression 'expr'
2527 // and uses the result as a string (e.g. replace %(1+2) with the
2529 // Here, we identify the integer token which is the result of the
2530 // absolute expression evaluation and replace it with its string
2532 if (AltMacroMode
&& Token
.getString().front() == '%' &&
2533 Token
.is(AsmToken::Integer
))
2534 // Emit an integer value to the buffer.
2535 OS
<< Token
.getIntVal();
2536 // Only Token that was validated as a string and begins with '<'
2537 // is considered altMacroString!!!
2538 else if (AltMacroMode
&& Token
.getString().front() == '<' &&
2539 Token
.is(AsmToken::String
)) {
2540 OS
<< angleBracketString(Token
.getStringContents());
2542 // We expect no quotes around the string's contents when
2543 // parsing for varargs.
2544 else if (Token
.isNot(AsmToken::String
) || VarargParameter
)
2545 OS
<< Token
.getString();
2547 OS
<< Token
.getStringContents();
2550 // A macro without parameters is handled differently on Darwin:
2551 // gas accepts no arguments and does no substitutions
2552 StringRef Body
= Macro
.Body
;
2553 size_t I
= 0, End
= Body
.size();
2555 if (Body
[I
] == '\\' && I
+ 1 != End
) {
2556 // Check for \@ and \+ pseudo variables.
2557 if (EnableAtPseudoVariable
&& Body
[I
+ 1] == '@') {
2558 OS
<< NumOfMacroInstantiations
;
2562 if (Body
[I
+ 1] == '+') {
2567 if (Body
[I
+ 1] == '(' && Body
[I
+ 2] == ')') {
2573 while (I
!= End
&& isIdentifierChar(Body
[I
]))
2575 StringRef
Argument(Body
.data() + Pos
, I
- Pos
);
2576 if (AltMacroMode
&& I
!= End
&& Body
[I
] == '&')
2579 for (; Index
< NParameters
; ++Index
)
2580 if (Parameters
[Index
].Name
== Argument
)
2582 if (Index
== NParameters
)
2583 OS
<< '\\' << Argument
;
2589 // In Darwin mode, $ is used for macro expansion, not considered an
2591 if (Body
[I
] == '$' && I
+ 1 != End
&& IsDarwin
&& !NParameters
) {
2592 // This macro has no parameters, look for $0, $1, etc.
2593 switch (Body
[I
+ 1]) {
2599 // $n => number of arguments
2605 if (!isDigit(Body
[I
+ 1]))
2607 // $[0-9] => argument
2608 // Missing arguments are ignored.
2609 unsigned Index
= Body
[I
+ 1] - '0';
2610 if (Index
< A
.size())
2611 for (const AsmToken
&Token
: A
[Index
])
2612 OS
<< Token
.getString();
2619 if (!isIdentifierChar(Body
[I
]) || IsDarwin
) {
2624 const size_t Start
= I
;
2625 while (++I
&& isIdentifierChar(Body
[I
])) {
2627 StringRef
Token(Body
.data() + Start
, I
- Start
);
2630 for (; Index
!= NParameters
; ++Index
)
2631 if (Parameters
[Index
].Name
== Token
)
2633 if (Index
!= NParameters
) {
2635 if (I
!= End
&& Body
[I
] == '&')
2647 static bool isOperator(AsmToken::TokenKind kind
) {
2651 case AsmToken::Plus
:
2652 case AsmToken::Minus
:
2653 case AsmToken::Tilde
:
2654 case AsmToken::Slash
:
2655 case AsmToken::Star
:
2657 case AsmToken::Equal
:
2658 case AsmToken::EqualEqual
:
2659 case AsmToken::Pipe
:
2660 case AsmToken::PipePipe
:
2661 case AsmToken::Caret
:
2663 case AsmToken::AmpAmp
:
2664 case AsmToken::Exclaim
:
2665 case AsmToken::ExclaimEqual
:
2666 case AsmToken::Less
:
2667 case AsmToken::LessEqual
:
2668 case AsmToken::LessLess
:
2669 case AsmToken::LessGreater
:
2670 case AsmToken::Greater
:
2671 case AsmToken::GreaterEqual
:
2672 case AsmToken::GreaterGreater
:
2679 class AsmLexerSkipSpaceRAII
{
2681 AsmLexerSkipSpaceRAII(AsmLexer
&Lexer
, bool SkipSpace
) : Lexer(Lexer
) {
2682 Lexer
.setSkipSpace(SkipSpace
);
2685 ~AsmLexerSkipSpaceRAII() {
2686 Lexer
.setSkipSpace(true);
2693 } // end anonymous namespace
2695 bool AsmParser::parseMacroArgument(MCAsmMacroArgument
&MA
, bool Vararg
) {
2698 if (Lexer
.isNot(AsmToken::EndOfStatement
)) {
2699 StringRef Str
= parseStringToEndOfStatement();
2700 MA
.emplace_back(AsmToken::String
, Str
);
2705 unsigned ParenLevel
= 0;
2707 // Darwin doesn't use spaces to delmit arguments.
2708 AsmLexerSkipSpaceRAII
ScopedSkipSpace(Lexer
, IsDarwin
);
2714 if (Lexer
.is(AsmToken::Eof
) || Lexer
.is(AsmToken::Equal
))
2715 return TokError("unexpected token in macro instantiation");
2717 if (ParenLevel
== 0) {
2719 if (Lexer
.is(AsmToken::Comma
))
2722 if (parseOptionalToken(AsmToken::Space
))
2725 // Spaces can delimit parameters, but could also be part an expression.
2726 // If the token after a space is an operator, add the token and the next
2727 // one into this argument
2729 if (isOperator(Lexer
.getKind())) {
2730 MA
.push_back(getTok());
2733 // Whitespace after an operator can be ignored.
2734 parseOptionalToken(AsmToken::Space
);
2742 // handleMacroEntry relies on not advancing the lexer here
2743 // to be able to fill in the remaining default parameter values
2744 if (Lexer
.is(AsmToken::EndOfStatement
))
2747 // Adjust the current parentheses level.
2748 if (Lexer
.is(AsmToken::LParen
))
2750 else if (Lexer
.is(AsmToken::RParen
) && ParenLevel
)
2753 // Append the token to the current argument list.
2754 MA
.push_back(getTok());
2758 if (ParenLevel
!= 0)
2759 return TokError("unbalanced parentheses in macro argument");
2763 // Parse the macro instantiation arguments.
2764 bool AsmParser::parseMacroArguments(const MCAsmMacro
*M
,
2765 MCAsmMacroArguments
&A
) {
2766 const unsigned NParameters
= M
? M
->Parameters
.size() : 0;
2767 bool NamedParametersFound
= false;
2768 SmallVector
<SMLoc
, 4> FALocs
;
2770 A
.resize(NParameters
);
2771 FALocs
.resize(NParameters
);
2773 // Parse two kinds of macro invocations:
2774 // - macros defined without any parameters accept an arbitrary number of them
2775 // - macros defined with parameters accept at most that many of them
2776 bool HasVararg
= NParameters
? M
->Parameters
.back().Vararg
: false;
2777 for (unsigned Parameter
= 0; !NParameters
|| Parameter
< NParameters
;
2779 SMLoc IDLoc
= Lexer
.getLoc();
2780 MCAsmMacroParameter FA
;
2782 if (Lexer
.is(AsmToken::Identifier
) && Lexer
.peekTok().is(AsmToken::Equal
)) {
2783 if (parseIdentifier(FA
.Name
))
2784 return Error(IDLoc
, "invalid argument identifier for formal argument");
2786 if (Lexer
.isNot(AsmToken::Equal
))
2787 return TokError("expected '=' after formal parameter identifier");
2791 NamedParametersFound
= true;
2793 bool Vararg
= HasVararg
&& Parameter
== (NParameters
- 1);
2795 if (NamedParametersFound
&& FA
.Name
.empty())
2796 return Error(IDLoc
, "cannot mix positional and keyword arguments");
2798 SMLoc StrLoc
= Lexer
.getLoc();
2800 if (AltMacroMode
&& Lexer
.is(AsmToken::Percent
)) {
2801 const MCExpr
*AbsoluteExp
;
2805 if (parseExpression(AbsoluteExp
, EndLoc
))
2807 if (!AbsoluteExp
->evaluateAsAbsolute(Value
,
2808 getStreamer().getAssemblerPtr()))
2809 return Error(StrLoc
, "expected absolute expression");
2810 const char *StrChar
= StrLoc
.getPointer();
2811 const char *EndChar
= EndLoc
.getPointer();
2812 AsmToken
newToken(AsmToken::Integer
,
2813 StringRef(StrChar
, EndChar
- StrChar
), Value
);
2814 FA
.Value
.push_back(newToken
);
2815 } else if (AltMacroMode
&& Lexer
.is(AsmToken::Less
) &&
2816 isAngleBracketString(StrLoc
, EndLoc
)) {
2817 const char *StrChar
= StrLoc
.getPointer();
2818 const char *EndChar
= EndLoc
.getPointer();
2819 jumpToLoc(EndLoc
, CurBuffer
);
2820 /// Eat from '<' to '>'
2822 AsmToken
newToken(AsmToken::String
,
2823 StringRef(StrChar
, EndChar
- StrChar
));
2824 FA
.Value
.push_back(newToken
);
2825 } else if(parseMacroArgument(FA
.Value
, Vararg
))
2828 unsigned PI
= Parameter
;
2829 if (!FA
.Name
.empty()) {
2831 for (FAI
= 0; FAI
< NParameters
; ++FAI
)
2832 if (M
->Parameters
[FAI
].Name
== FA
.Name
)
2835 if (FAI
>= NParameters
) {
2836 assert(M
&& "expected macro to be defined");
2837 return Error(IDLoc
, "parameter named '" + FA
.Name
+
2838 "' does not exist for macro '" + M
->Name
+ "'");
2843 if (!FA
.Value
.empty()) {
2848 if (FALocs
.size() <= PI
)
2849 FALocs
.resize(PI
+ 1);
2851 FALocs
[PI
] = Lexer
.getLoc();
2854 // At the end of the statement, fill in remaining arguments that have
2855 // default values. If there aren't any, then the next argument is
2856 // required but missing
2857 if (Lexer
.is(AsmToken::EndOfStatement
)) {
2858 bool Failure
= false;
2859 for (unsigned FAI
= 0; FAI
< NParameters
; ++FAI
) {
2860 if (A
[FAI
].empty()) {
2861 if (M
->Parameters
[FAI
].Required
) {
2862 Error(FALocs
[FAI
].isValid() ? FALocs
[FAI
] : Lexer
.getLoc(),
2863 "missing value for required parameter "
2864 "'" + M
->Parameters
[FAI
].Name
+ "' in macro '" + M
->Name
+ "'");
2868 if (!M
->Parameters
[FAI
].Value
.empty())
2869 A
[FAI
] = M
->Parameters
[FAI
].Value
;
2875 parseOptionalToken(AsmToken::Comma
);
2878 return TokError("too many positional arguments");
2881 bool AsmParser::handleMacroEntry(MCAsmMacro
*M
, SMLoc NameLoc
) {
2882 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2883 // eliminate this, although we should protect against infinite loops.
2884 unsigned MaxNestingDepth
= AsmMacroMaxNestingDepth
;
2885 if (ActiveMacros
.size() == MaxNestingDepth
) {
2886 std::ostringstream MaxNestingDepthError
;
2887 MaxNestingDepthError
<< "macros cannot be nested more than "
2888 << MaxNestingDepth
<< " levels deep."
2889 << " Use -asm-macro-max-nesting-depth to increase "
2891 return TokError(MaxNestingDepthError
.str());
2894 MCAsmMacroArguments A
;
2895 if (parseMacroArguments(M
, A
))
2898 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2899 // to hold the macro body with substitutions.
2900 SmallString
<256> Buf
;
2901 raw_svector_ostream
OS(Buf
);
2903 if ((!IsDarwin
|| M
->Parameters
.size()) && M
->Parameters
.size() != A
.size())
2904 return Error(getTok().getLoc(), "Wrong number of arguments");
2905 if (expandMacro(OS
, *M
, M
->Parameters
, A
, true))
2908 // We include the .endmacro in the buffer as our cue to exit the macro
2910 OS
<< ".endmacro\n";
2912 std::unique_ptr
<MemoryBuffer
> Instantiation
=
2913 MemoryBuffer::getMemBufferCopy(OS
.str(), "<instantiation>");
2915 // Create the macro instantiation object and add to the current macro
2916 // instantiation stack.
2917 MacroInstantiation
*MI
= new MacroInstantiation
{
2918 NameLoc
, CurBuffer
, getTok().getLoc(), TheCondStack
.size()};
2919 ActiveMacros
.push_back(MI
);
2921 ++NumOfMacroInstantiations
;
2923 // Jump to the macro instantiation and prime the lexer.
2924 CurBuffer
= SrcMgr
.AddNewSourceBuffer(std::move(Instantiation
), SMLoc());
2925 Lexer
.setBuffer(SrcMgr
.getMemoryBuffer(CurBuffer
)->getBuffer());
2931 void AsmParser::handleMacroExit() {
2932 // Jump to the EndOfStatement we should return to, and consume it.
2933 jumpToLoc(ActiveMacros
.back()->ExitLoc
, ActiveMacros
.back()->ExitBuffer
);
2935 // If .endm/.endr is followed by \n instead of a comment, consume it so that
2936 // we don't print an excess \n.
2937 if (getTok().is(AsmToken::EndOfStatement
))
2940 // Pop the instantiation entry.
2941 delete ActiveMacros
.back();
2942 ActiveMacros
.pop_back();
2945 bool AsmParser::parseAssignment(StringRef Name
, AssignmentKind Kind
) {
2947 const MCExpr
*Value
;
2948 SMLoc ExprLoc
= getTok().getLoc();
2950 Kind
== AssignmentKind::Set
|| Kind
== AssignmentKind::Equal
;
2951 if (MCParserUtils::parseAssignmentExpression(Name
, AllowRedef
, *this, Sym
,
2956 // In the case where we parse an expression starting with a '.', we will
2957 // not generate an error, nor will we create a symbol. In this case we
2958 // should just return out.
2962 if (discardLTOSymbol(Name
))
2965 // Do the assignment.
2967 case AssignmentKind::Equal
:
2968 Out
.emitAssignment(Sym
, Value
);
2970 case AssignmentKind::Set
:
2971 case AssignmentKind::Equiv
:
2972 Out
.emitAssignment(Sym
, Value
);
2973 Out
.emitSymbolAttribute(Sym
, MCSA_NoDeadStrip
);
2975 case AssignmentKind::LTOSetConditional
:
2976 if (Value
->getKind() != MCExpr::SymbolRef
)
2977 return Error(ExprLoc
, "expected identifier");
2979 Out
.emitConditionalAssignment(Sym
, Value
);
2986 /// parseIdentifier:
2989 bool AsmParser::parseIdentifier(StringRef
&Res
) {
2990 // The assembler has relaxed rules for accepting identifiers, in particular we
2991 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2992 // separate tokens. At this level, we have already lexed so we cannot (currently)
2993 // handle this as a context dependent token, instead we detect adjacent tokens
2994 // and return the combined identifier.
2995 if (Lexer
.is(AsmToken::Dollar
) || Lexer
.is(AsmToken::At
)) {
2996 SMLoc PrefixLoc
= getLexer().getLoc();
2998 // Consume the prefix character, and check for a following identifier.
3001 Lexer
.peekTokens(Buf
, false);
3003 if (Buf
[0].isNot(AsmToken::Identifier
) && Buf
[0].isNot(AsmToken::Integer
))
3006 // We have a '$' or '@' followed by an identifier or integer token, make
3007 // sure they are adjacent.
3008 if (PrefixLoc
.getPointer() + 1 != Buf
[0].getLoc().getPointer())
3012 Lexer
.Lex(); // Lexer's Lex guarantees consecutive token.
3013 // Construct the joined identifier and consume the token.
3014 Res
= StringRef(PrefixLoc
.getPointer(), getTok().getString().size() + 1);
3015 Lex(); // Parser Lex to maintain invariants.
3019 if (Lexer
.isNot(AsmToken::Identifier
) && Lexer
.isNot(AsmToken::String
))
3022 Res
= getTok().getIdentifier();
3024 Lex(); // Consume the identifier token.
3029 /// parseDirectiveSet:
3030 /// ::= .equ identifier ',' expression
3031 /// ::= .equiv identifier ',' expression
3032 /// ::= .set identifier ',' expression
3033 /// ::= .lto_set_conditional identifier ',' expression
3034 bool AsmParser::parseDirectiveSet(StringRef IDVal
, AssignmentKind Kind
) {
3036 if (check(parseIdentifier(Name
), "expected identifier") || parseComma() ||
3037 parseAssignment(Name
, Kind
))
3042 bool AsmParser::parseEscapedString(std::string
&Data
) {
3043 if (check(getTok().isNot(AsmToken::String
), "expected string"))
3047 StringRef Str
= getTok().getStringContents();
3048 for (unsigned i
= 0, e
= Str
.size(); i
!= e
; ++i
) {
3049 if (Str
[i
] != '\\') {
3050 if ((Str
[i
] == '\n') || (Str
[i
] == '\r')) {
3051 // Don't double-warn for Windows newlines.
3052 if ((Str
[i
] == '\n') && (i
> 0) && (Str
[i
- 1] == '\r'))
3055 SMLoc NewlineLoc
= SMLoc::getFromPointer(Str
.data() + i
);
3056 if (Warning(NewlineLoc
, "unterminated string; newline inserted"))
3063 // Recognize escaped characters. Note that this escape semantics currently
3064 // loosely follows Darwin 'as'.
3067 return TokError("unexpected backslash at end of string");
3069 // Recognize hex sequences similarly to GNU 'as'.
3070 if (Str
[i
] == 'x' || Str
[i
] == 'X') {
3071 size_t length
= Str
.size();
3072 if (i
+ 1 >= length
|| !isHexDigit(Str
[i
+ 1]))
3073 return TokError("invalid hexadecimal escape sequence");
3075 // Consume hex characters. GNU 'as' reads all hexadecimal characters and
3076 // then truncates to the lower 16 bits. Seems reasonable.
3078 while (i
+ 1 < length
&& isHexDigit(Str
[i
+ 1]))
3079 Value
= Value
* 16 + hexDigitValue(Str
[++i
]);
3081 Data
+= (unsigned char)(Value
& 0xFF);
3085 // Recognize octal sequences.
3086 if ((unsigned)(Str
[i
] - '0') <= 7) {
3087 // Consume up to three octal characters.
3088 unsigned Value
= Str
[i
] - '0';
3090 if (i
+ 1 != e
&& ((unsigned)(Str
[i
+ 1] - '0')) <= 7) {
3092 Value
= Value
* 8 + (Str
[i
] - '0');
3094 if (i
+ 1 != e
&& ((unsigned)(Str
[i
+ 1] - '0')) <= 7) {
3096 Value
= Value
* 8 + (Str
[i
] - '0');
3101 return TokError("invalid octal escape sequence (out of range)");
3103 Data
+= (unsigned char)Value
;
3107 // Otherwise recognize individual escapes.
3110 // Just reject invalid escape sequences for now.
3111 return TokError("invalid escape sequence (unrecognized character)");
3113 case 'b': Data
+= '\b'; break;
3114 case 'f': Data
+= '\f'; break;
3115 case 'n': Data
+= '\n'; break;
3116 case 'r': Data
+= '\r'; break;
3117 case 't': Data
+= '\t'; break;
3118 case '"': Data
+= '"'; break;
3119 case '\\': Data
+= '\\'; break;
3127 bool AsmParser::parseAngleBracketString(std::string
&Data
) {
3128 SMLoc EndLoc
, StartLoc
= getTok().getLoc();
3129 if (isAngleBracketString(StartLoc
, EndLoc
)) {
3130 const char *StartChar
= StartLoc
.getPointer() + 1;
3131 const char *EndChar
= EndLoc
.getPointer() - 1;
3132 jumpToLoc(EndLoc
, CurBuffer
);
3133 /// Eat from '<' to '>'
3136 Data
= angleBracketString(StringRef(StartChar
, EndChar
- StartChar
));
3142 /// parseDirectiveAscii:
3143 // ::= .ascii [ "string"+ ( , "string"+ )* ]
3144 /// ::= ( .asciz | .string ) [ "string" ( , "string" )* ]
3145 bool AsmParser::parseDirectiveAscii(StringRef IDVal
, bool ZeroTerminated
) {
3146 auto parseOp
= [&]() -> bool {
3148 if (checkForValidSection())
3150 // Only support spaces as separators for .ascii directive for now. See the
3151 // discusssion at https://reviews.llvm.org/D91460 for more details.
3153 if (parseEscapedString(Data
))
3155 getStreamer().emitBytes(Data
);
3156 } while (!ZeroTerminated
&& getTok().is(AsmToken::String
));
3158 getStreamer().emitBytes(StringRef("\0", 1));
3162 return parseMany(parseOp
);
3165 /// parseDirectiveReloc
3166 /// ::= .reloc expression , identifier [ , expression ]
3167 bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc
) {
3168 const MCExpr
*Offset
;
3169 const MCExpr
*Expr
= nullptr;
3170 SMLoc OffsetLoc
= Lexer
.getTok().getLoc();
3172 if (parseExpression(Offset
))
3175 check(getTok().isNot(AsmToken::Identifier
), "expected relocation name"))
3178 SMLoc NameLoc
= Lexer
.getTok().getLoc();
3179 StringRef Name
= Lexer
.getTok().getIdentifier();
3182 if (Lexer
.is(AsmToken::Comma
)) {
3184 SMLoc ExprLoc
= Lexer
.getLoc();
3185 if (parseExpression(Expr
))
3189 if (!Expr
->evaluateAsRelocatable(Value
, nullptr, nullptr))
3190 return Error(ExprLoc
, "expression must be relocatable");
3196 const MCTargetAsmParser
&MCT
= getTargetParser();
3197 const MCSubtargetInfo
&STI
= MCT
.getSTI();
3198 if (std::optional
<std::pair
<bool, std::string
>> Err
=
3199 getStreamer().emitRelocDirective(*Offset
, Name
, Expr
, DirectiveLoc
,
3201 return Error(Err
->first
? NameLoc
: OffsetLoc
, Err
->second
);
3206 /// parseDirectiveValue
3207 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
3208 bool AsmParser::parseDirectiveValue(StringRef IDVal
, unsigned Size
) {
3209 auto parseOp
= [&]() -> bool {
3210 const MCExpr
*Value
;
3211 SMLoc ExprLoc
= getLexer().getLoc();
3212 if (checkForValidSection() || parseExpression(Value
))
3214 // Special case constant expressions to match code generator.
3215 if (const MCConstantExpr
*MCE
= dyn_cast
<MCConstantExpr
>(Value
)) {
3216 assert(Size
<= 8 && "Invalid size");
3217 uint64_t IntValue
= MCE
->getValue();
3218 if (!isUIntN(8 * Size
, IntValue
) && !isIntN(8 * Size
, IntValue
))
3219 return Error(ExprLoc
, "out of range literal value");
3220 getStreamer().emitIntValue(IntValue
, Size
);
3222 getStreamer().emitValue(Value
, Size
, ExprLoc
);
3226 return parseMany(parseOp
);
3229 static bool parseHexOcta(AsmParser
&Asm
, uint64_t &hi
, uint64_t &lo
) {
3230 if (Asm
.getTok().isNot(AsmToken::Integer
) &&
3231 Asm
.getTok().isNot(AsmToken::BigNum
))
3232 return Asm
.TokError("unknown token in expression");
3233 SMLoc ExprLoc
= Asm
.getTok().getLoc();
3234 APInt IntValue
= Asm
.getTok().getAPIntVal();
3236 if (!IntValue
.isIntN(128))
3237 return Asm
.Error(ExprLoc
, "out of range literal value");
3238 if (!IntValue
.isIntN(64)) {
3239 hi
= IntValue
.getHiBits(IntValue
.getBitWidth() - 64).getZExtValue();
3240 lo
= IntValue
.getLoBits(64).getZExtValue();
3243 lo
= IntValue
.getZExtValue();
3248 /// ParseDirectiveOctaValue
3249 /// ::= .octa [ hexconstant (, hexconstant)* ]
3251 bool AsmParser::parseDirectiveOctaValue(StringRef IDVal
) {
3252 auto parseOp
= [&]() -> bool {
3253 if (checkForValidSection())
3256 if (parseHexOcta(*this, hi
, lo
))
3258 if (MAI
.isLittleEndian()) {
3259 getStreamer().emitInt64(lo
);
3260 getStreamer().emitInt64(hi
);
3262 getStreamer().emitInt64(hi
);
3263 getStreamer().emitInt64(lo
);
3268 return parseMany(parseOp
);
3271 bool AsmParser::parseRealValue(const fltSemantics
&Semantics
, APInt
&Res
) {
3272 // We don't truly support arithmetic on floating point expressions, so we
3273 // have to manually parse unary prefixes.
3275 if (getLexer().is(AsmToken::Minus
)) {
3278 } else if (getLexer().is(AsmToken::Plus
))
3281 if (Lexer
.is(AsmToken::Error
))
3282 return TokError(Lexer
.getErr());
3283 if (Lexer
.isNot(AsmToken::Integer
) && Lexer
.isNot(AsmToken::Real
) &&
3284 Lexer
.isNot(AsmToken::Identifier
))
3285 return TokError("unexpected token in directive");
3287 // Convert to an APFloat.
3288 APFloat
Value(Semantics
);
3289 StringRef IDVal
= getTok().getString();
3290 if (getLexer().is(AsmToken::Identifier
)) {
3291 if (!IDVal
.compare_insensitive("infinity") ||
3292 !IDVal
.compare_insensitive("inf"))
3293 Value
= APFloat::getInf(Semantics
);
3294 else if (!IDVal
.compare_insensitive("nan"))
3295 Value
= APFloat::getNaN(Semantics
, false, ~0);
3297 return TokError("invalid floating point literal");
3298 } else if (errorToBool(
3299 Value
.convertFromString(IDVal
, APFloat::rmNearestTiesToEven
)
3301 return TokError("invalid floating point literal");
3305 // Consume the numeric token.
3308 Res
= Value
.bitcastToAPInt();
3313 /// parseDirectiveRealValue
3314 /// ::= (.single | .double) [ expression (, expression)* ]
3315 bool AsmParser::parseDirectiveRealValue(StringRef IDVal
,
3316 const fltSemantics
&Semantics
) {
3317 auto parseOp
= [&]() -> bool {
3319 if (checkForValidSection() || parseRealValue(Semantics
, AsInt
))
3321 getStreamer().emitIntValue(AsInt
.getLimitedValue(),
3322 AsInt
.getBitWidth() / 8);
3326 return parseMany(parseOp
);
3329 /// parseDirectiveZero
3330 /// ::= .zero expression
3331 bool AsmParser::parseDirectiveZero() {
3332 SMLoc NumBytesLoc
= Lexer
.getLoc();
3333 const MCExpr
*NumBytes
;
3334 if (checkForValidSection() || parseExpression(NumBytes
))
3338 if (getLexer().is(AsmToken::Comma
)) {
3340 if (parseAbsoluteExpression(Val
))
3346 getStreamer().emitFill(*NumBytes
, Val
, NumBytesLoc
);
3351 /// parseDirectiveFill
3352 /// ::= .fill expression [ , expression [ , expression ] ]
3353 bool AsmParser::parseDirectiveFill() {
3354 SMLoc NumValuesLoc
= Lexer
.getLoc();
3355 const MCExpr
*NumValues
;
3356 if (checkForValidSection() || parseExpression(NumValues
))
3359 int64_t FillSize
= 1;
3360 int64_t FillExpr
= 0;
3362 SMLoc SizeLoc
, ExprLoc
;
3364 if (parseOptionalToken(AsmToken::Comma
)) {
3365 SizeLoc
= getTok().getLoc();
3366 if (parseAbsoluteExpression(FillSize
))
3368 if (parseOptionalToken(AsmToken::Comma
)) {
3369 ExprLoc
= getTok().getLoc();
3370 if (parseAbsoluteExpression(FillExpr
))
3378 Warning(SizeLoc
, "'.fill' directive with negative size has no effect");
3382 Warning(SizeLoc
, "'.fill' directive with size greater than 8 has been truncated to 8");
3386 if (!isUInt
<32>(FillExpr
) && FillSize
> 4)
3387 Warning(ExprLoc
, "'.fill' directive pattern has been truncated to 32-bits");
3389 getStreamer().emitFill(*NumValues
, FillSize
, FillExpr
, NumValuesLoc
);
3394 /// parseDirectiveOrg
3395 /// ::= .org expression [ , expression ]
3396 bool AsmParser::parseDirectiveOrg() {
3397 const MCExpr
*Offset
;
3398 SMLoc OffsetLoc
= Lexer
.getLoc();
3399 if (checkForValidSection() || parseExpression(Offset
))
3402 // Parse optional fill expression.
3403 int64_t FillExpr
= 0;
3404 if (parseOptionalToken(AsmToken::Comma
))
3405 if (parseAbsoluteExpression(FillExpr
))
3410 getStreamer().emitValueToOffset(Offset
, FillExpr
, OffsetLoc
);
3414 /// parseDirectiveAlign
3415 /// ::= {.align, ...} expression [ , expression [ , expression ]]
3416 bool AsmParser::parseDirectiveAlign(bool IsPow2
, unsigned ValueSize
) {
3417 SMLoc AlignmentLoc
= getLexer().getLoc();
3420 bool HasFillExpr
= false;
3421 int64_t FillExpr
= 0;
3422 int64_t MaxBytesToFill
= 0;
3425 auto parseAlign
= [&]() -> bool {
3426 if (parseAbsoluteExpression(Alignment
))
3428 if (parseOptionalToken(AsmToken::Comma
)) {
3429 // The fill expression can be omitted while specifying a maximum number of
3430 // alignment bytes, e.g:
3432 if (getTok().isNot(AsmToken::Comma
)) {
3434 if (parseTokenLoc(FillExprLoc
) || parseAbsoluteExpression(FillExpr
))
3437 if (parseOptionalToken(AsmToken::Comma
))
3438 if (parseTokenLoc(MaxBytesLoc
) ||
3439 parseAbsoluteExpression(MaxBytesToFill
))
3445 if (checkForValidSection())
3447 // Ignore empty '.p2align' directives for GNU-as compatibility
3448 if (IsPow2
&& (ValueSize
== 1) && getTok().is(AsmToken::EndOfStatement
)) {
3449 Warning(AlignmentLoc
, "p2align directive with no operand(s) is ignored");
3455 // Always emit an alignment here even if we thrown an error.
3456 bool ReturnVal
= false;
3458 // Compute alignment in bytes.
3460 // FIXME: Diagnose overflow.
3461 if (Alignment
>= 32) {
3462 ReturnVal
|= Error(AlignmentLoc
, "invalid alignment value");
3466 Alignment
= 1ULL << Alignment
;
3468 // Reject alignments that aren't either a power of two or zero,
3469 // for gas compatibility. Alignment of zero is silently rounded
3473 else if (!isPowerOf2_64(Alignment
)) {
3474 ReturnVal
|= Error(AlignmentLoc
, "alignment must be a power of 2");
3475 Alignment
= llvm::bit_floor
<uint64_t>(Alignment
);
3477 if (!isUInt
<32>(Alignment
)) {
3478 ReturnVal
|= Error(AlignmentLoc
, "alignment must be smaller than 2**32");
3479 Alignment
= 1u << 31;
3483 // Diagnose non-sensical max bytes to align.
3484 if (MaxBytesLoc
.isValid()) {
3485 if (MaxBytesToFill
< 1) {
3486 ReturnVal
|= Error(MaxBytesLoc
,
3487 "alignment directive can never be satisfied in this "
3488 "many bytes, ignoring maximum bytes expression");
3492 if (MaxBytesToFill
>= Alignment
) {
3493 Warning(MaxBytesLoc
, "maximum bytes expression exceeds alignment and "
3499 const MCSection
*Section
= getStreamer().getCurrentSectionOnly();
3500 assert(Section
&& "must have section to emit alignment");
3502 if (HasFillExpr
&& FillExpr
!= 0 && Section
->isVirtualSection()) {
3504 Warning(FillExprLoc
, "ignoring non-zero fill value in " +
3505 Section
->getVirtualSectionKind() +
3506 " section '" + Section
->getName() + "'");
3510 // Check whether we should use optimal code alignment for this .align
3512 if (Section
->useCodeAlign() && !HasFillExpr
) {
3513 getStreamer().emitCodeAlignment(
3514 Align(Alignment
), &getTargetParser().getSTI(), MaxBytesToFill
);
3516 // FIXME: Target specific behavior about how the "extra" bytes are filled.
3517 getStreamer().emitValueToAlignment(Align(Alignment
), FillExpr
, ValueSize
,
3524 /// parseDirectiveFile
3525 /// ::= .file filename
3526 /// ::= .file number [directory] filename [md5 checksum] [source source-text]
3527 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc
) {
3528 // FIXME: I'm not sure what this is.
3529 int64_t FileNumber
= -1;
3530 if (getLexer().is(AsmToken::Integer
)) {
3531 FileNumber
= getTok().getIntVal();
3535 return TokError("negative file number");
3540 // Usually the directory and filename together, otherwise just the directory.
3541 // Allow the strings to have escaped octal character sequence.
3542 if (parseEscapedString(Path
))
3545 StringRef Directory
;
3547 std::string FilenameData
;
3548 if (getLexer().is(AsmToken::String
)) {
3549 if (check(FileNumber
== -1,
3550 "explicit path specified, but no file number") ||
3551 parseEscapedString(FilenameData
))
3553 Filename
= FilenameData
;
3559 uint64_t MD5Hi
, MD5Lo
;
3560 bool HasMD5
= false;
3562 std::optional
<StringRef
> Source
;
3563 bool HasSource
= false;
3564 std::string SourceString
;
3566 while (!parseOptionalToken(AsmToken::EndOfStatement
)) {
3568 if (check(getTok().isNot(AsmToken::Identifier
),
3569 "unexpected token in '.file' directive") ||
3570 parseIdentifier(Keyword
))
3572 if (Keyword
== "md5") {
3574 if (check(FileNumber
== -1,
3575 "MD5 checksum specified, but no file number") ||
3576 parseHexOcta(*this, MD5Hi
, MD5Lo
))
3578 } else if (Keyword
== "source") {
3580 if (check(FileNumber
== -1,
3581 "source specified, but no file number") ||
3582 check(getTok().isNot(AsmToken::String
),
3583 "unexpected token in '.file' directive") ||
3584 parseEscapedString(SourceString
))
3587 return TokError("unexpected token in '.file' directive");
3591 if (FileNumber
== -1) {
3592 // Ignore the directive if there is no number and the target doesn't support
3593 // numberless .file directives. This allows some portability of assembler
3594 // between different object file formats.
3595 if (getContext().getAsmInfo()->hasSingleParameterDotFile())
3596 getStreamer().emitFileDirective(Filename
);
3598 // In case there is a -g option as well as debug info from directive .file,
3599 // we turn off the -g option, directly use the existing debug info instead.
3600 // Throw away any implicit file table for the assembler source.
3601 if (Ctx
.getGenDwarfForAssembly()) {
3602 Ctx
.getMCDwarfLineTable(0).resetFileTable();
3603 Ctx
.setGenDwarfForAssembly(false);
3606 std::optional
<MD5::MD5Result
> CKMem
;
3609 for (unsigned i
= 0; i
!= 8; ++i
) {
3610 Sum
[i
] = uint8_t(MD5Hi
>> ((7 - i
) * 8));
3611 Sum
[i
+ 8] = uint8_t(MD5Lo
>> ((7 - i
) * 8));
3616 char *SourceBuf
= static_cast<char *>(Ctx
.allocate(SourceString
.size()));
3617 memcpy(SourceBuf
, SourceString
.data(), SourceString
.size());
3618 Source
= StringRef(SourceBuf
, SourceString
.size());
3620 if (FileNumber
== 0) {
3621 // Upgrade to Version 5 for assembly actions like clang -c a.s.
3622 if (Ctx
.getDwarfVersion() < 5)
3623 Ctx
.setDwarfVersion(5);
3624 getStreamer().emitDwarfFile0Directive(Directory
, Filename
, CKMem
, Source
);
3626 Expected
<unsigned> FileNumOrErr
= getStreamer().tryEmitDwarfFileDirective(
3627 FileNumber
, Directory
, Filename
, CKMem
, Source
);
3629 return Error(DirectiveLoc
, toString(FileNumOrErr
.takeError()));
3631 // Alert the user if there are some .file directives with MD5 and some not.
3632 // But only do that once.
3633 if (!ReportedInconsistentMD5
&& !Ctx
.isDwarfMD5UsageConsistent(0)) {
3634 ReportedInconsistentMD5
= true;
3635 return Warning(DirectiveLoc
, "inconsistent use of MD5 checksums");
3642 /// parseDirectiveLine
3643 /// ::= .line [number]
3644 bool AsmParser::parseDirectiveLine() {
3646 if (getLexer().is(AsmToken::Integer
)) {
3647 if (parseIntToken(LineNumber
, "unexpected token in '.line' directive"))
3650 // FIXME: Do something with the .line.
3655 /// parseDirectiveLoc
3656 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3657 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3658 /// The first number is a file number, must have been previously assigned with
3659 /// a .file directive, the second number is the line number and optionally the
3660 /// third number is a column position (zero if not specified). The remaining
3661 /// optional items are .loc sub-directives.
3662 bool AsmParser::parseDirectiveLoc() {
3663 int64_t FileNumber
= 0, LineNumber
= 0;
3664 SMLoc Loc
= getTok().getLoc();
3665 if (parseIntToken(FileNumber
, "unexpected token in '.loc' directive") ||
3666 check(FileNumber
< 1 && Ctx
.getDwarfVersion() < 5, Loc
,
3667 "file number less than one in '.loc' directive") ||
3668 check(!getContext().isValidDwarfFileNumber(FileNumber
), Loc
,
3669 "unassigned file number in '.loc' directive"))
3673 if (getLexer().is(AsmToken::Integer
)) {
3674 LineNumber
= getTok().getIntVal();
3676 return TokError("line number less than zero in '.loc' directive");
3680 int64_t ColumnPos
= 0;
3681 if (getLexer().is(AsmToken::Integer
)) {
3682 ColumnPos
= getTok().getIntVal();
3684 return TokError("column position less than zero in '.loc' directive");
3688 auto PrevFlags
= getContext().getCurrentDwarfLoc().getFlags();
3689 unsigned Flags
= PrevFlags
& DWARF2_FLAG_IS_STMT
;
3691 int64_t Discriminator
= 0;
3693 auto parseLocOp
= [&]() -> bool {
3695 SMLoc Loc
= getTok().getLoc();
3696 if (parseIdentifier(Name
))
3697 return TokError("unexpected token in '.loc' directive");
3699 if (Name
== "basic_block")
3700 Flags
|= DWARF2_FLAG_BASIC_BLOCK
;
3701 else if (Name
== "prologue_end")
3702 Flags
|= DWARF2_FLAG_PROLOGUE_END
;
3703 else if (Name
== "epilogue_begin")
3704 Flags
|= DWARF2_FLAG_EPILOGUE_BEGIN
;
3705 else if (Name
== "is_stmt") {
3706 Loc
= getTok().getLoc();
3707 const MCExpr
*Value
;
3708 if (parseExpression(Value
))
3710 // The expression must be the constant 0 or 1.
3711 if (const MCConstantExpr
*MCE
= dyn_cast
<MCConstantExpr
>(Value
)) {
3712 int Value
= MCE
->getValue();
3714 Flags
&= ~DWARF2_FLAG_IS_STMT
;
3715 else if (Value
== 1)
3716 Flags
|= DWARF2_FLAG_IS_STMT
;
3718 return Error(Loc
, "is_stmt value not 0 or 1");
3720 return Error(Loc
, "is_stmt value not the constant value of 0 or 1");
3722 } else if (Name
== "isa") {
3723 Loc
= getTok().getLoc();
3724 const MCExpr
*Value
;
3725 if (parseExpression(Value
))
3727 // The expression must be a constant greater or equal to 0.
3728 if (const MCConstantExpr
*MCE
= dyn_cast
<MCConstantExpr
>(Value
)) {
3729 int Value
= MCE
->getValue();
3731 return Error(Loc
, "isa number less than zero");
3734 return Error(Loc
, "isa number not a constant value");
3736 } else if (Name
== "discriminator") {
3737 if (parseAbsoluteExpression(Discriminator
))
3740 return Error(Loc
, "unknown sub-directive in '.loc' directive");
3745 if (parseMany(parseLocOp
, false /*hasComma*/))
3748 getStreamer().emitDwarfLocDirective(FileNumber
, LineNumber
, ColumnPos
, Flags
,
3749 Isa
, Discriminator
, StringRef());
3754 /// parseDirectiveLoc
3755 /// ::= .loc_label label
3756 bool AsmParser::parseDirectiveLocLabel(SMLoc DirectiveLoc
) {
3758 DirectiveLoc
= Lexer
.getLoc();
3759 if (parseIdentifier(Name
))
3760 return TokError("expected identifier");
3763 getStreamer().emitDwarfLocLabelDirective(DirectiveLoc
, Name
);
3767 /// parseDirectiveStabs
3768 /// ::= .stabs string, number, number, number
3769 bool AsmParser::parseDirectiveStabs() {
3770 return TokError("unsupported directive '.stabs'");
3773 /// parseDirectiveCVFile
3774 /// ::= .cv_file number filename [checksum] [checksumkind]
3775 bool AsmParser::parseDirectiveCVFile() {
3776 SMLoc FileNumberLoc
= getTok().getLoc();
3778 std::string Filename
;
3779 std::string Checksum
;
3780 int64_t ChecksumKind
= 0;
3782 if (parseIntToken(FileNumber
,
3783 "expected file number in '.cv_file' directive") ||
3784 check(FileNumber
< 1, FileNumberLoc
, "file number less than one") ||
3785 check(getTok().isNot(AsmToken::String
),
3786 "unexpected token in '.cv_file' directive") ||
3787 parseEscapedString(Filename
))
3789 if (!parseOptionalToken(AsmToken::EndOfStatement
)) {
3790 if (check(getTok().isNot(AsmToken::String
),
3791 "unexpected token in '.cv_file' directive") ||
3792 parseEscapedString(Checksum
) ||
3793 parseIntToken(ChecksumKind
,
3794 "expected checksum kind in '.cv_file' directive") ||
3799 Checksum
= fromHex(Checksum
);
3800 void *CKMem
= Ctx
.allocate(Checksum
.size(), 1);
3801 memcpy(CKMem
, Checksum
.data(), Checksum
.size());
3802 ArrayRef
<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem
),
3805 if (!getStreamer().emitCVFileDirective(FileNumber
, Filename
, ChecksumAsBytes
,
3806 static_cast<uint8_t>(ChecksumKind
)))
3807 return Error(FileNumberLoc
, "file number already allocated");
3812 bool AsmParser::parseCVFunctionId(int64_t &FunctionId
,
3813 StringRef DirectiveName
) {
3815 return parseTokenLoc(Loc
) ||
3816 parseIntToken(FunctionId
, "expected function id in '" + DirectiveName
+
3818 check(FunctionId
< 0 || FunctionId
>= UINT_MAX
, Loc
,
3819 "expected function id within range [0, UINT_MAX)");
3822 bool AsmParser::parseCVFileId(int64_t &FileNumber
, StringRef DirectiveName
) {
3824 return parseTokenLoc(Loc
) ||
3825 parseIntToken(FileNumber
, "expected integer in '" + DirectiveName
+
3827 check(FileNumber
< 1, Loc
, "file number less than one in '" +
3828 DirectiveName
+ "' directive") ||
3829 check(!getCVContext().isValidFileNumber(FileNumber
), Loc
,
3830 "unassigned file number in '" + DirectiveName
+ "' directive");
3833 /// parseDirectiveCVFuncId
3834 /// ::= .cv_func_id FunctionId
3836 /// Introduces a function ID that can be used with .cv_loc.
3837 bool AsmParser::parseDirectiveCVFuncId() {
3838 SMLoc FunctionIdLoc
= getTok().getLoc();
3841 if (parseCVFunctionId(FunctionId
, ".cv_func_id") || parseEOL())
3844 if (!getStreamer().emitCVFuncIdDirective(FunctionId
))
3845 return Error(FunctionIdLoc
, "function id already allocated");
3850 /// parseDirectiveCVInlineSiteId
3851 /// ::= .cv_inline_site_id FunctionId
3853 /// "inlined_at" IAFile IALine [IACol]
3855 /// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3856 /// at" source location information for use in the line table of the caller,
3857 /// whether the caller is a real function or another inlined call site.
3858 bool AsmParser::parseDirectiveCVInlineSiteId() {
3859 SMLoc FunctionIdLoc
= getTok().getLoc();
3867 if (parseCVFunctionId(FunctionId
, ".cv_inline_site_id"))
3871 if (check((getLexer().isNot(AsmToken::Identifier
) ||
3872 getTok().getIdentifier() != "within"),
3873 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3878 if (parseCVFunctionId(IAFunc
, ".cv_inline_site_id"))
3882 if (check((getLexer().isNot(AsmToken::Identifier
) ||
3883 getTok().getIdentifier() != "inlined_at"),
3884 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3890 if (parseCVFileId(IAFile
, ".cv_inline_site_id") ||
3891 parseIntToken(IALine
, "expected line number after 'inlined_at'"))
3895 if (getLexer().is(AsmToken::Integer
)) {
3896 IACol
= getTok().getIntVal();
3903 if (!getStreamer().emitCVInlineSiteIdDirective(FunctionId
, IAFunc
, IAFile
,
3904 IALine
, IACol
, FunctionIdLoc
))
3905 return Error(FunctionIdLoc
, "function id already allocated");
3910 /// parseDirectiveCVLoc
3911 /// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3913 /// The first number is a file number, must have been previously assigned with
3914 /// a .file directive, the second number is the line number and optionally the
3915 /// third number is a column position (zero if not specified). The remaining
3916 /// optional items are .loc sub-directives.
3917 bool AsmParser::parseDirectiveCVLoc() {
3918 SMLoc DirectiveLoc
= getTok().getLoc();
3919 int64_t FunctionId
, FileNumber
;
3920 if (parseCVFunctionId(FunctionId
, ".cv_loc") ||
3921 parseCVFileId(FileNumber
, ".cv_loc"))
3924 int64_t LineNumber
= 0;
3925 if (getLexer().is(AsmToken::Integer
)) {
3926 LineNumber
= getTok().getIntVal();
3928 return TokError("line number less than zero in '.cv_loc' directive");
3932 int64_t ColumnPos
= 0;
3933 if (getLexer().is(AsmToken::Integer
)) {
3934 ColumnPos
= getTok().getIntVal();
3936 return TokError("column position less than zero in '.cv_loc' directive");
3940 bool PrologueEnd
= false;
3941 uint64_t IsStmt
= 0;
3943 auto parseOp
= [&]() -> bool {
3945 SMLoc Loc
= getTok().getLoc();
3946 if (parseIdentifier(Name
))
3947 return TokError("unexpected token in '.cv_loc' directive");
3948 if (Name
== "prologue_end")
3950 else if (Name
== "is_stmt") {
3951 Loc
= getTok().getLoc();
3952 const MCExpr
*Value
;
3953 if (parseExpression(Value
))
3955 // The expression must be the constant 0 or 1.
3957 if (const auto *MCE
= dyn_cast
<MCConstantExpr
>(Value
))
3958 IsStmt
= MCE
->getValue();
3961 return Error(Loc
, "is_stmt value not 0 or 1");
3963 return Error(Loc
, "unknown sub-directive in '.cv_loc' directive");
3968 if (parseMany(parseOp
, false /*hasComma*/))
3971 getStreamer().emitCVLocDirective(FunctionId
, FileNumber
, LineNumber
,
3972 ColumnPos
, PrologueEnd
, IsStmt
, StringRef(),
3977 /// parseDirectiveCVLinetable
3978 /// ::= .cv_linetable FunctionId, FnStart, FnEnd
3979 bool AsmParser::parseDirectiveCVLinetable() {
3981 StringRef FnStartName
, FnEndName
;
3982 SMLoc Loc
= getTok().getLoc();
3983 if (parseCVFunctionId(FunctionId
, ".cv_linetable") || parseComma() ||
3984 parseTokenLoc(Loc
) ||
3985 check(parseIdentifier(FnStartName
), Loc
,
3986 "expected identifier in directive") ||
3987 parseComma() || parseTokenLoc(Loc
) ||
3988 check(parseIdentifier(FnEndName
), Loc
,
3989 "expected identifier in directive"))
3992 MCSymbol
*FnStartSym
= getContext().getOrCreateSymbol(FnStartName
);
3993 MCSymbol
*FnEndSym
= getContext().getOrCreateSymbol(FnEndName
);
3995 getStreamer().emitCVLinetableDirective(FunctionId
, FnStartSym
, FnEndSym
);
3999 /// parseDirectiveCVInlineLinetable
4000 /// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
4001 bool AsmParser::parseDirectiveCVInlineLinetable() {
4002 int64_t PrimaryFunctionId
, SourceFileId
, SourceLineNum
;
4003 StringRef FnStartName
, FnEndName
;
4004 SMLoc Loc
= getTok().getLoc();
4005 if (parseCVFunctionId(PrimaryFunctionId
, ".cv_inline_linetable") ||
4006 parseTokenLoc(Loc
) ||
4009 "expected SourceField in '.cv_inline_linetable' directive") ||
4010 check(SourceFileId
<= 0, Loc
,
4011 "File id less than zero in '.cv_inline_linetable' directive") ||
4012 parseTokenLoc(Loc
) ||
4015 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
4016 check(SourceLineNum
< 0, Loc
,
4017 "Line number less than zero in '.cv_inline_linetable' directive") ||
4018 parseTokenLoc(Loc
) || check(parseIdentifier(FnStartName
), Loc
,
4019 "expected identifier in directive") ||
4020 parseTokenLoc(Loc
) || check(parseIdentifier(FnEndName
), Loc
,
4021 "expected identifier in directive"))
4027 MCSymbol
*FnStartSym
= getContext().getOrCreateSymbol(FnStartName
);
4028 MCSymbol
*FnEndSym
= getContext().getOrCreateSymbol(FnEndName
);
4029 getStreamer().emitCVInlineLinetableDirective(PrimaryFunctionId
, SourceFileId
,
4030 SourceLineNum
, FnStartSym
,
4035 void AsmParser::initializeCVDefRangeTypeMap() {
4036 CVDefRangeTypeMap
["reg"] = CVDR_DEFRANGE_REGISTER
;
4037 CVDefRangeTypeMap
["frame_ptr_rel"] = CVDR_DEFRANGE_FRAMEPOINTER_REL
;
4038 CVDefRangeTypeMap
["subfield_reg"] = CVDR_DEFRANGE_SUBFIELD_REGISTER
;
4039 CVDefRangeTypeMap
["reg_rel"] = CVDR_DEFRANGE_REGISTER_REL
;
4042 /// parseDirectiveCVDefRange
4043 /// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
4044 bool AsmParser::parseDirectiveCVDefRange() {
4046 std::vector
<std::pair
<const MCSymbol
*, const MCSymbol
*>> Ranges
;
4047 while (getLexer().is(AsmToken::Identifier
)) {
4048 Loc
= getLexer().getLoc();
4049 StringRef GapStartName
;
4050 if (parseIdentifier(GapStartName
))
4051 return Error(Loc
, "expected identifier in directive");
4052 MCSymbol
*GapStartSym
= getContext().getOrCreateSymbol(GapStartName
);
4054 Loc
= getLexer().getLoc();
4055 StringRef GapEndName
;
4056 if (parseIdentifier(GapEndName
))
4057 return Error(Loc
, "expected identifier in directive");
4058 MCSymbol
*GapEndSym
= getContext().getOrCreateSymbol(GapEndName
);
4060 Ranges
.push_back({GapStartSym
, GapEndSym
});
4063 StringRef CVDefRangeTypeStr
;
4066 "expected comma before def_range type in .cv_def_range directive") ||
4067 parseIdentifier(CVDefRangeTypeStr
))
4068 return Error(Loc
, "expected def_range type in directive");
4070 StringMap
<CVDefRangeType
>::const_iterator CVTypeIt
=
4071 CVDefRangeTypeMap
.find(CVDefRangeTypeStr
);
4072 CVDefRangeType CVDRType
= (CVTypeIt
== CVDefRangeTypeMap
.end())
4074 : CVTypeIt
->getValue();
4076 case CVDR_DEFRANGE_REGISTER
: {
4078 if (parseToken(AsmToken::Comma
, "expected comma before register number in "
4079 ".cv_def_range directive") ||
4080 parseAbsoluteExpression(DRRegister
))
4081 return Error(Loc
, "expected register number");
4083 codeview::DefRangeRegisterHeader DRHdr
;
4084 DRHdr
.Register
= DRRegister
;
4085 DRHdr
.MayHaveNoName
= 0;
4086 getStreamer().emitCVDefRangeDirective(Ranges
, DRHdr
);
4089 case CVDR_DEFRANGE_FRAMEPOINTER_REL
: {
4091 if (parseToken(AsmToken::Comma
,
4092 "expected comma before offset in .cv_def_range directive") ||
4093 parseAbsoluteExpression(DROffset
))
4094 return Error(Loc
, "expected offset value");
4096 codeview::DefRangeFramePointerRelHeader DRHdr
;
4097 DRHdr
.Offset
= DROffset
;
4098 getStreamer().emitCVDefRangeDirective(Ranges
, DRHdr
);
4101 case CVDR_DEFRANGE_SUBFIELD_REGISTER
: {
4103 int64_t DROffsetInParent
;
4104 if (parseToken(AsmToken::Comma
, "expected comma before register number in "
4105 ".cv_def_range directive") ||
4106 parseAbsoluteExpression(DRRegister
))
4107 return Error(Loc
, "expected register number");
4108 if (parseToken(AsmToken::Comma
,
4109 "expected comma before offset in .cv_def_range directive") ||
4110 parseAbsoluteExpression(DROffsetInParent
))
4111 return Error(Loc
, "expected offset value");
4113 codeview::DefRangeSubfieldRegisterHeader DRHdr
;
4114 DRHdr
.Register
= DRRegister
;
4115 DRHdr
.MayHaveNoName
= 0;
4116 DRHdr
.OffsetInParent
= DROffsetInParent
;
4117 getStreamer().emitCVDefRangeDirective(Ranges
, DRHdr
);
4120 case CVDR_DEFRANGE_REGISTER_REL
: {
4123 int64_t DRBasePointerOffset
;
4124 if (parseToken(AsmToken::Comma
, "expected comma before register number in "
4125 ".cv_def_range directive") ||
4126 parseAbsoluteExpression(DRRegister
))
4127 return Error(Loc
, "expected register value");
4130 "expected comma before flag value in .cv_def_range directive") ||
4131 parseAbsoluteExpression(DRFlags
))
4132 return Error(Loc
, "expected flag value");
4133 if (parseToken(AsmToken::Comma
, "expected comma before base pointer offset "
4134 "in .cv_def_range directive") ||
4135 parseAbsoluteExpression(DRBasePointerOffset
))
4136 return Error(Loc
, "expected base pointer offset value");
4138 codeview::DefRangeRegisterRelHeader DRHdr
;
4139 DRHdr
.Register
= DRRegister
;
4140 DRHdr
.Flags
= DRFlags
;
4141 DRHdr
.BasePointerOffset
= DRBasePointerOffset
;
4142 getStreamer().emitCVDefRangeDirective(Ranges
, DRHdr
);
4146 return Error(Loc
, "unexpected def_range type in .cv_def_range directive");
4151 /// parseDirectiveCVString
4152 /// ::= .cv_stringtable "string"
4153 bool AsmParser::parseDirectiveCVString() {
4155 if (checkForValidSection() || parseEscapedString(Data
))
4158 // Put the string in the table and emit the offset.
4159 std::pair
<StringRef
, unsigned> Insertion
=
4160 getCVContext().addToStringTable(Data
);
4161 getStreamer().emitInt32(Insertion
.second
);
4165 /// parseDirectiveCVStringTable
4166 /// ::= .cv_stringtable
4167 bool AsmParser::parseDirectiveCVStringTable() {
4168 getStreamer().emitCVStringTableDirective();
4172 /// parseDirectiveCVFileChecksums
4173 /// ::= .cv_filechecksums
4174 bool AsmParser::parseDirectiveCVFileChecksums() {
4175 getStreamer().emitCVFileChecksumsDirective();
4179 /// parseDirectiveCVFileChecksumOffset
4180 /// ::= .cv_filechecksumoffset fileno
4181 bool AsmParser::parseDirectiveCVFileChecksumOffset() {
4183 if (parseIntToken(FileNo
, "expected identifier in directive"))
4187 getStreamer().emitCVFileChecksumOffsetDirective(FileNo
);
4191 /// parseDirectiveCVFPOData
4192 /// ::= .cv_fpo_data procsym
4193 bool AsmParser::parseDirectiveCVFPOData() {
4194 SMLoc DirLoc
= getLexer().getLoc();
4196 if (parseIdentifier(ProcName
))
4197 return TokError("expected symbol name");
4200 MCSymbol
*ProcSym
= getContext().getOrCreateSymbol(ProcName
);
4201 getStreamer().emitCVFPOData(ProcSym
, DirLoc
);
4205 /// parseDirectiveCFISections
4206 /// ::= .cfi_sections section [, section]
4207 bool AsmParser::parseDirectiveCFISections() {
4212 if (!parseOptionalToken(AsmToken::EndOfStatement
)) {
4214 if (parseIdentifier(Name
))
4215 return TokError("expected .eh_frame or .debug_frame");
4216 if (Name
== ".eh_frame")
4218 else if (Name
== ".debug_frame")
4220 if (parseOptionalToken(AsmToken::EndOfStatement
))
4226 getStreamer().emitCFISections(EH
, Debug
);
4230 /// parseDirectiveCFIStartProc
4231 /// ::= .cfi_startproc [simple]
4232 bool AsmParser::parseDirectiveCFIStartProc() {
4233 CFIStartProcLoc
= StartTokLoc
;
4236 if (!parseOptionalToken(AsmToken::EndOfStatement
)) {
4237 if (check(parseIdentifier(Simple
) || Simple
!= "simple",
4238 "unexpected token") ||
4243 // TODO(kristina): Deal with a corner case of incorrect diagnostic context
4244 // being produced if this directive is emitted as part of preprocessor macro
4245 // expansion which can *ONLY* happen if Clang's cc1as is the API consumer.
4246 // Tools like llvm-mc on the other hand are not affected by it, and report
4247 // correct context information.
4248 getStreamer().emitCFIStartProc(!Simple
.empty(), Lexer
.getLoc());
4252 /// parseDirectiveCFIEndProc
4253 /// ::= .cfi_endproc
4254 bool AsmParser::parseDirectiveCFIEndProc() {
4255 CFIStartProcLoc
= std::nullopt
;
4260 getStreamer().emitCFIEndProc();
4264 /// parse register name or number.
4265 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register
,
4266 SMLoc DirectiveLoc
) {
4269 if (getLexer().isNot(AsmToken::Integer
)) {
4270 if (getTargetParser().parseRegister(RegNo
, DirectiveLoc
, DirectiveLoc
))
4272 Register
= getContext().getRegisterInfo()->getDwarfRegNum(RegNo
, true);
4274 return parseAbsoluteExpression(Register
);
4279 /// parseDirectiveCFIDefCfa
4280 /// ::= .cfi_def_cfa register, offset
4281 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc
) {
4282 int64_t Register
= 0, Offset
= 0;
4283 if (parseRegisterOrRegisterNumber(Register
, DirectiveLoc
) || parseComma() ||
4284 parseAbsoluteExpression(Offset
) || parseEOL())
4287 getStreamer().emitCFIDefCfa(Register
, Offset
, DirectiveLoc
);
4291 /// parseDirectiveCFIDefCfaOffset
4292 /// ::= .cfi_def_cfa_offset offset
4293 bool AsmParser::parseDirectiveCFIDefCfaOffset(SMLoc DirectiveLoc
) {
4295 if (parseAbsoluteExpression(Offset
) || parseEOL())
4298 getStreamer().emitCFIDefCfaOffset(Offset
, DirectiveLoc
);
4302 /// parseDirectiveCFIRegister
4303 /// ::= .cfi_register register, register
4304 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc
) {
4305 int64_t Register1
= 0, Register2
= 0;
4306 if (parseRegisterOrRegisterNumber(Register1
, DirectiveLoc
) || parseComma() ||
4307 parseRegisterOrRegisterNumber(Register2
, DirectiveLoc
) || parseEOL())
4310 getStreamer().emitCFIRegister(Register1
, Register2
, DirectiveLoc
);
4314 /// parseDirectiveCFIWindowSave
4315 /// ::= .cfi_window_save
4316 bool AsmParser::parseDirectiveCFIWindowSave(SMLoc DirectiveLoc
) {
4319 getStreamer().emitCFIWindowSave(DirectiveLoc
);
4323 /// parseDirectiveCFIAdjustCfaOffset
4324 /// ::= .cfi_adjust_cfa_offset adjustment
4325 bool AsmParser::parseDirectiveCFIAdjustCfaOffset(SMLoc DirectiveLoc
) {
4326 int64_t Adjustment
= 0;
4327 if (parseAbsoluteExpression(Adjustment
) || parseEOL())
4330 getStreamer().emitCFIAdjustCfaOffset(Adjustment
, DirectiveLoc
);
4334 /// parseDirectiveCFIDefCfaRegister
4335 /// ::= .cfi_def_cfa_register register
4336 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc
) {
4337 int64_t Register
= 0;
4338 if (parseRegisterOrRegisterNumber(Register
, DirectiveLoc
) || parseEOL())
4341 getStreamer().emitCFIDefCfaRegister(Register
, DirectiveLoc
);
4345 /// parseDirectiveCFILLVMDefAspaceCfa
4346 /// ::= .cfi_llvm_def_aspace_cfa register, offset, address_space
4347 bool AsmParser::parseDirectiveCFILLVMDefAspaceCfa(SMLoc DirectiveLoc
) {
4348 int64_t Register
= 0, Offset
= 0, AddressSpace
= 0;
4349 if (parseRegisterOrRegisterNumber(Register
, DirectiveLoc
) || parseComma() ||
4350 parseAbsoluteExpression(Offset
) || parseComma() ||
4351 parseAbsoluteExpression(AddressSpace
) || parseEOL())
4354 getStreamer().emitCFILLVMDefAspaceCfa(Register
, Offset
, AddressSpace
,
4359 /// parseDirectiveCFIOffset
4360 /// ::= .cfi_offset register, offset
4361 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc
) {
4362 int64_t Register
= 0;
4365 if (parseRegisterOrRegisterNumber(Register
, DirectiveLoc
) || parseComma() ||
4366 parseAbsoluteExpression(Offset
) || parseEOL())
4369 getStreamer().emitCFIOffset(Register
, Offset
, DirectiveLoc
);
4373 /// parseDirectiveCFIRelOffset
4374 /// ::= .cfi_rel_offset register, offset
4375 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc
) {
4376 int64_t Register
= 0, Offset
= 0;
4378 if (parseRegisterOrRegisterNumber(Register
, DirectiveLoc
) || parseComma() ||
4379 parseAbsoluteExpression(Offset
) || parseEOL())
4382 getStreamer().emitCFIRelOffset(Register
, Offset
, DirectiveLoc
);
4386 static bool isValidEncoding(int64_t Encoding
) {
4387 if (Encoding
& ~0xff)
4390 if (Encoding
== dwarf::DW_EH_PE_omit
)
4393 const unsigned Format
= Encoding
& 0xf;
4394 if (Format
!= dwarf::DW_EH_PE_absptr
&& Format
!= dwarf::DW_EH_PE_udata2
&&
4395 Format
!= dwarf::DW_EH_PE_udata4
&& Format
!= dwarf::DW_EH_PE_udata8
&&
4396 Format
!= dwarf::DW_EH_PE_sdata2
&& Format
!= dwarf::DW_EH_PE_sdata4
&&
4397 Format
!= dwarf::DW_EH_PE_sdata8
&& Format
!= dwarf::DW_EH_PE_signed
)
4400 const unsigned Application
= Encoding
& 0x70;
4401 if (Application
!= dwarf::DW_EH_PE_absptr
&&
4402 Application
!= dwarf::DW_EH_PE_pcrel
)
4408 /// parseDirectiveCFIPersonalityOrLsda
4409 /// IsPersonality true for cfi_personality, false for cfi_lsda
4410 /// ::= .cfi_personality encoding, [symbol_name]
4411 /// ::= .cfi_lsda encoding, [symbol_name]
4412 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality
) {
4413 int64_t Encoding
= 0;
4414 if (parseAbsoluteExpression(Encoding
))
4416 if (Encoding
== dwarf::DW_EH_PE_omit
)
4420 if (check(!isValidEncoding(Encoding
), "unsupported encoding.") ||
4422 check(parseIdentifier(Name
), "expected identifier in directive") ||
4426 MCSymbol
*Sym
= getContext().getOrCreateSymbol(Name
);
4429 getStreamer().emitCFIPersonality(Sym
, Encoding
);
4431 getStreamer().emitCFILsda(Sym
, Encoding
);
4435 /// parseDirectiveCFIRememberState
4436 /// ::= .cfi_remember_state
4437 bool AsmParser::parseDirectiveCFIRememberState(SMLoc DirectiveLoc
) {
4440 getStreamer().emitCFIRememberState(DirectiveLoc
);
4444 /// parseDirectiveCFIRestoreState
4445 /// ::= .cfi_remember_state
4446 bool AsmParser::parseDirectiveCFIRestoreState(SMLoc DirectiveLoc
) {
4449 getStreamer().emitCFIRestoreState(DirectiveLoc
);
4453 /// parseDirectiveCFISameValue
4454 /// ::= .cfi_same_value register
4455 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc
) {
4456 int64_t Register
= 0;
4458 if (parseRegisterOrRegisterNumber(Register
, DirectiveLoc
) || parseEOL())
4461 getStreamer().emitCFISameValue(Register
, DirectiveLoc
);
4465 /// parseDirectiveCFIRestore
4466 /// ::= .cfi_restore register
4467 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc
) {
4468 int64_t Register
= 0;
4469 if (parseRegisterOrRegisterNumber(Register
, DirectiveLoc
) || parseEOL())
4472 getStreamer().emitCFIRestore(Register
, DirectiveLoc
);
4476 /// parseDirectiveCFIEscape
4477 /// ::= .cfi_escape expression[,...]
4478 bool AsmParser::parseDirectiveCFIEscape(SMLoc DirectiveLoc
) {
4481 if (parseAbsoluteExpression(CurrValue
))
4484 Values
.push_back((uint8_t)CurrValue
);
4486 while (getLexer().is(AsmToken::Comma
)) {
4489 if (parseAbsoluteExpression(CurrValue
))
4492 Values
.push_back((uint8_t)CurrValue
);
4495 getStreamer().emitCFIEscape(Values
, DirectiveLoc
);
4499 /// parseDirectiveCFIReturnColumn
4500 /// ::= .cfi_return_column register
4501 bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc
) {
4502 int64_t Register
= 0;
4503 if (parseRegisterOrRegisterNumber(Register
, DirectiveLoc
) || parseEOL())
4505 getStreamer().emitCFIReturnColumn(Register
);
4509 /// parseDirectiveCFISignalFrame
4510 /// ::= .cfi_signal_frame
4511 bool AsmParser::parseDirectiveCFISignalFrame(SMLoc DirectiveLoc
) {
4515 getStreamer().emitCFISignalFrame();
4519 /// parseDirectiveCFIUndefined
4520 /// ::= .cfi_undefined register
4521 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc
) {
4522 int64_t Register
= 0;
4524 if (parseRegisterOrRegisterNumber(Register
, DirectiveLoc
) || parseEOL())
4527 getStreamer().emitCFIUndefined(Register
, DirectiveLoc
);
4531 /// parseDirectiveCFILabel
4532 /// ::= .cfi_label label
4533 bool AsmParser::parseDirectiveCFILabel(SMLoc Loc
) {
4535 Loc
= Lexer
.getLoc();
4536 if (parseIdentifier(Name
))
4537 return TokError("expected identifier");
4540 getStreamer().emitCFILabelDirective(Loc
, Name
);
4544 /// parseDirectiveCFIValOffset
4545 /// ::= .cfi_val_offset register, offset
4546 bool AsmParser::parseDirectiveCFIValOffset(SMLoc DirectiveLoc
) {
4547 int64_t Register
= 0;
4550 if (parseRegisterOrRegisterNumber(Register
, DirectiveLoc
) || parseComma() ||
4551 parseAbsoluteExpression(Offset
) || parseEOL())
4554 getStreamer().emitCFIValOffset(Register
, Offset
, DirectiveLoc
);
4558 /// parseDirectiveAltmacro
4561 bool AsmParser::parseDirectiveAltmacro(StringRef Directive
) {
4564 AltMacroMode
= (Directive
== ".altmacro");
4568 /// parseDirectiveMacrosOnOff
4571 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive
) {
4574 setMacrosEnabled(Directive
== ".macros_on");
4578 /// parseDirectiveMacro
4579 /// ::= .macro name[,] [parameters]
4580 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc
) {
4582 if (parseIdentifier(Name
))
4583 return TokError("expected identifier in '.macro' directive");
4585 if (getLexer().is(AsmToken::Comma
))
4588 MCAsmMacroParameters Parameters
;
4589 while (getLexer().isNot(AsmToken::EndOfStatement
)) {
4591 if (!Parameters
.empty() && Parameters
.back().Vararg
)
4592 return Error(Lexer
.getLoc(), "vararg parameter '" +
4593 Parameters
.back().Name
+
4594 "' should be the last parameter");
4596 MCAsmMacroParameter Parameter
;
4597 if (parseIdentifier(Parameter
.Name
))
4598 return TokError("expected identifier in '.macro' directive");
4600 // Emit an error if two (or more) named parameters share the same name
4601 for (const MCAsmMacroParameter
& CurrParam
: Parameters
)
4602 if (CurrParam
.Name
== Parameter
.Name
)
4603 return TokError("macro '" + Name
+ "' has multiple parameters"
4604 " named '" + Parameter
.Name
+ "'");
4606 if (Lexer
.is(AsmToken::Colon
)) {
4607 Lex(); // consume ':'
4610 StringRef Qualifier
;
4612 QualLoc
= Lexer
.getLoc();
4613 if (parseIdentifier(Qualifier
))
4614 return Error(QualLoc
, "missing parameter qualifier for "
4615 "'" + Parameter
.Name
+ "' in macro '" + Name
+ "'");
4617 if (Qualifier
== "req")
4618 Parameter
.Required
= true;
4619 else if (Qualifier
== "vararg")
4620 Parameter
.Vararg
= true;
4622 return Error(QualLoc
, Qualifier
+ " is not a valid parameter qualifier "
4623 "for '" + Parameter
.Name
+ "' in macro '" + Name
+ "'");
4626 if (getLexer().is(AsmToken::Equal
)) {
4631 ParamLoc
= Lexer
.getLoc();
4632 if (parseMacroArgument(Parameter
.Value
, /*Vararg=*/false ))
4635 if (Parameter
.Required
)
4636 Warning(ParamLoc
, "pointless default value for required parameter "
4637 "'" + Parameter
.Name
+ "' in macro '" + Name
+ "'");
4640 Parameters
.push_back(std::move(Parameter
));
4642 if (getLexer().is(AsmToken::Comma
))
4646 // Eat just the end of statement.
4649 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
4650 AsmToken EndToken
, StartToken
= getTok();
4651 unsigned MacroDepth
= 0;
4652 // Lex the macro definition.
4654 // Ignore Lexing errors in macros.
4655 while (Lexer
.is(AsmToken::Error
)) {
4659 // Check whether we have reached the end of the file.
4660 if (getLexer().is(AsmToken::Eof
))
4661 return Error(DirectiveLoc
, "no matching '.endmacro' in definition");
4663 // Otherwise, check whether we have reach the .endmacro or the start of a
4664 // preprocessor line marker.
4665 if (getLexer().is(AsmToken::Identifier
)) {
4666 if (getTok().getIdentifier() == ".endm" ||
4667 getTok().getIdentifier() == ".endmacro") {
4668 if (MacroDepth
== 0) { // Outermost macro.
4669 EndToken
= getTok();
4671 if (getLexer().isNot(AsmToken::EndOfStatement
))
4672 return TokError("unexpected token in '" + EndToken
.getIdentifier() +
4676 // Otherwise we just found the end of an inner macro.
4679 } else if (getTok().getIdentifier() == ".macro") {
4680 // We allow nested macros. Those aren't instantiated until the outermost
4681 // macro is expanded so just ignore them for now.
4684 } else if (Lexer
.is(AsmToken::HashDirective
)) {
4685 (void)parseCppHashLineFilenameComment(getLexer().getLoc());
4688 // Otherwise, scan til the end of the statement.
4689 eatToEndOfStatement();
4692 if (getContext().lookupMacro(Name
)) {
4693 return Error(DirectiveLoc
, "macro '" + Name
+ "' is already defined");
4696 const char *BodyStart
= StartToken
.getLoc().getPointer();
4697 const char *BodyEnd
= EndToken
.getLoc().getPointer();
4698 StringRef Body
= StringRef(BodyStart
, BodyEnd
- BodyStart
);
4699 checkForBadMacro(DirectiveLoc
, Name
, Body
, Parameters
);
4700 MCAsmMacro
Macro(Name
, Body
, std::move(Parameters
));
4701 DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n";
4703 getContext().defineMacro(Name
, std::move(Macro
));
4707 /// checkForBadMacro
4709 /// With the support added for named parameters there may be code out there that
4710 /// is transitioning from positional parameters. In versions of gas that did
4711 /// not support named parameters they would be ignored on the macro definition.
4712 /// But to support both styles of parameters this is not possible so if a macro
4713 /// definition has named parameters but does not use them and has what appears
4714 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4715 /// warning that the positional parameter found in body which have no effect.
4716 /// Hoping the developer will either remove the named parameters from the macro
4717 /// definition so the positional parameters get used if that was what was
4718 /// intended or change the macro to use the named parameters. It is possible
4719 /// this warning will trigger when the none of the named parameters are used
4720 /// and the strings like $1 are infact to simply to be passed trough unchanged.
4721 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc
, StringRef Name
,
4723 ArrayRef
<MCAsmMacroParameter
> Parameters
) {
4724 // If this macro is not defined with named parameters the warning we are
4725 // checking for here doesn't apply.
4726 unsigned NParameters
= Parameters
.size();
4727 if (NParameters
== 0)
4730 bool NamedParametersFound
= false;
4731 bool PositionalParametersFound
= false;
4733 // Look at the body of the macro for use of both the named parameters and what
4734 // are likely to be positional parameters. This is what expandMacro() is
4735 // doing when it finds the parameters in the body.
4736 while (!Body
.empty()) {
4737 // Scan for the next possible parameter.
4738 std::size_t End
= Body
.size(), Pos
= 0;
4739 for (; Pos
!= End
; ++Pos
) {
4740 // Check for a substitution or escape.
4741 // This macro is defined with parameters, look for \foo, \bar, etc.
4742 if (Body
[Pos
] == '\\' && Pos
+ 1 != End
)
4745 // This macro should have parameters, but look for $0, $1, ..., $n too.
4746 if (Body
[Pos
] != '$' || Pos
+ 1 == End
)
4748 char Next
= Body
[Pos
+ 1];
4749 if (Next
== '$' || Next
== 'n' ||
4750 isdigit(static_cast<unsigned char>(Next
)))
4754 // Check if we reached the end.
4758 if (Body
[Pos
] == '$') {
4759 switch (Body
[Pos
+ 1]) {
4764 // $n => number of arguments
4766 PositionalParametersFound
= true;
4769 // $[0-9] => argument
4771 PositionalParametersFound
= true;
4777 unsigned I
= Pos
+ 1;
4778 while (isIdentifierChar(Body
[I
]) && I
+ 1 != End
)
4781 const char *Begin
= Body
.data() + Pos
+ 1;
4782 StringRef
Argument(Begin
, I
- (Pos
+ 1));
4784 for (; Index
< NParameters
; ++Index
)
4785 if (Parameters
[Index
].Name
== Argument
)
4788 if (Index
== NParameters
) {
4789 if (Body
[Pos
+ 1] == '(' && Body
[Pos
+ 2] == ')')
4795 NamedParametersFound
= true;
4796 Pos
+= 1 + Argument
.size();
4799 // Update the scan point.
4800 Body
= Body
.substr(Pos
);
4803 if (!NamedParametersFound
&& PositionalParametersFound
)
4804 Warning(DirectiveLoc
, "macro defined with named parameters which are not "
4805 "used in macro body, possible positional parameter "
4806 "found in body which will have no effect");
4809 /// parseDirectiveExitMacro
4811 bool AsmParser::parseDirectiveExitMacro(StringRef Directive
) {
4815 if (!isInsideMacroInstantiation())
4816 return TokError("unexpected '" + Directive
+ "' in file, "
4817 "no current macro definition");
4819 // Exit all conditionals that are active in the current macro.
4820 while (TheCondStack
.size() != ActiveMacros
.back()->CondStackDepth
) {
4821 TheCondState
= TheCondStack
.back();
4822 TheCondStack
.pop_back();
4829 /// parseDirectiveEndMacro
4832 bool AsmParser::parseDirectiveEndMacro(StringRef Directive
) {
4833 if (getLexer().isNot(AsmToken::EndOfStatement
))
4834 return TokError("unexpected token in '" + Directive
+ "' directive");
4836 // If we are inside a macro instantiation, terminate the current
4838 if (isInsideMacroInstantiation()) {
4843 // Otherwise, this .endmacro is a stray entry in the file; well formed
4844 // .endmacro directives are handled during the macro definition parsing.
4845 return TokError("unexpected '" + Directive
+ "' in file, "
4846 "no current macro definition");
4849 /// parseDirectivePurgeMacro
4850 /// ::= .purgem name
4851 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc
) {
4854 if (parseTokenLoc(Loc
) ||
4855 check(parseIdentifier(Name
), Loc
,
4856 "expected identifier in '.purgem' directive") ||
4860 if (!getContext().lookupMacro(Name
))
4861 return Error(DirectiveLoc
, "macro '" + Name
+ "' is not defined");
4863 getContext().undefineMacro(Name
);
4864 DEBUG_WITH_TYPE("asm-macros", dbgs()
4865 << "Un-defining macro: " << Name
<< "\n");
4869 /// parseDirectiveBundleAlignMode
4870 /// ::= {.bundle_align_mode} expression
4871 bool AsmParser::parseDirectiveBundleAlignMode() {
4872 // Expect a single argument: an expression that evaluates to a constant
4873 // in the inclusive range 0-30.
4874 SMLoc ExprLoc
= getLexer().getLoc();
4875 int64_t AlignSizePow2
;
4876 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2
) ||
4878 check(AlignSizePow2
< 0 || AlignSizePow2
> 30, ExprLoc
,
4879 "invalid bundle alignment size (expected between 0 and 30)"))
4882 getStreamer().emitBundleAlignMode(Align(1ULL << AlignSizePow2
));
4886 /// parseDirectiveBundleLock
4887 /// ::= {.bundle_lock} [align_to_end]
4888 bool AsmParser::parseDirectiveBundleLock() {
4889 if (checkForValidSection())
4891 bool AlignToEnd
= false;
4894 SMLoc Loc
= getTok().getLoc();
4895 const char *kInvalidOptionError
=
4896 "invalid option for '.bundle_lock' directive";
4898 if (!parseOptionalToken(AsmToken::EndOfStatement
)) {
4899 if (check(parseIdentifier(Option
), Loc
, kInvalidOptionError
) ||
4900 check(Option
!= "align_to_end", Loc
, kInvalidOptionError
) || parseEOL())
4905 getStreamer().emitBundleLock(AlignToEnd
);
4909 /// parseDirectiveBundleLock
4910 /// ::= {.bundle_lock}
4911 bool AsmParser::parseDirectiveBundleUnlock() {
4912 if (checkForValidSection() || parseEOL())
4915 getStreamer().emitBundleUnlock();
4919 /// parseDirectiveSpace
4920 /// ::= (.skip | .space) expression [ , expression ]
4921 bool AsmParser::parseDirectiveSpace(StringRef IDVal
) {
4922 SMLoc NumBytesLoc
= Lexer
.getLoc();
4923 const MCExpr
*NumBytes
;
4924 if (checkForValidSection() || parseExpression(NumBytes
))
4927 int64_t FillExpr
= 0;
4928 if (parseOptionalToken(AsmToken::Comma
))
4929 if (parseAbsoluteExpression(FillExpr
))
4934 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
4935 getStreamer().emitFill(*NumBytes
, FillExpr
, NumBytesLoc
);
4940 /// parseDirectiveDCB
4941 /// ::= .dcb.{b, l, w} expression, expression
4942 bool AsmParser::parseDirectiveDCB(StringRef IDVal
, unsigned Size
) {
4943 SMLoc NumValuesLoc
= Lexer
.getLoc();
4945 if (checkForValidSection() || parseAbsoluteExpression(NumValues
))
4948 if (NumValues
< 0) {
4949 Warning(NumValuesLoc
, "'" + Twine(IDVal
) + "' directive with negative repeat count has no effect");
4956 const MCExpr
*Value
;
4957 SMLoc ExprLoc
= getLexer().getLoc();
4958 if (parseExpression(Value
))
4961 // Special case constant expressions to match code generator.
4962 if (const MCConstantExpr
*MCE
= dyn_cast
<MCConstantExpr
>(Value
)) {
4963 assert(Size
<= 8 && "Invalid size");
4964 uint64_t IntValue
= MCE
->getValue();
4965 if (!isUIntN(8 * Size
, IntValue
) && !isIntN(8 * Size
, IntValue
))
4966 return Error(ExprLoc
, "literal value out of range for directive");
4967 for (uint64_t i
= 0, e
= NumValues
; i
!= e
; ++i
)
4968 getStreamer().emitIntValue(IntValue
, Size
);
4970 for (uint64_t i
= 0, e
= NumValues
; i
!= e
; ++i
)
4971 getStreamer().emitValue(Value
, Size
, ExprLoc
);
4977 /// parseDirectiveRealDCB
4978 /// ::= .dcb.{d, s} expression, expression
4979 bool AsmParser::parseDirectiveRealDCB(StringRef IDVal
, const fltSemantics
&Semantics
) {
4980 SMLoc NumValuesLoc
= Lexer
.getLoc();
4982 if (checkForValidSection() || parseAbsoluteExpression(NumValues
))
4985 if (NumValues
< 0) {
4986 Warning(NumValuesLoc
, "'" + Twine(IDVal
) + "' directive with negative repeat count has no effect");
4994 if (parseRealValue(Semantics
, AsInt
) || parseEOL())
4997 for (uint64_t i
= 0, e
= NumValues
; i
!= e
; ++i
)
4998 getStreamer().emitIntValue(AsInt
.getLimitedValue(),
4999 AsInt
.getBitWidth() / 8);
5004 /// parseDirectiveDS
5005 /// ::= .ds.{b, d, l, p, s, w, x} expression
5006 bool AsmParser::parseDirectiveDS(StringRef IDVal
, unsigned Size
) {
5007 SMLoc NumValuesLoc
= Lexer
.getLoc();
5009 if (checkForValidSection() || parseAbsoluteExpression(NumValues
) ||
5013 if (NumValues
< 0) {
5014 Warning(NumValuesLoc
, "'" + Twine(IDVal
) + "' directive with negative repeat count has no effect");
5018 for (uint64_t i
= 0, e
= NumValues
; i
!= e
; ++i
)
5019 getStreamer().emitFill(Size
, 0);
5024 /// parseDirectiveLEB128
5025 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
5026 bool AsmParser::parseDirectiveLEB128(bool Signed
) {
5027 if (checkForValidSection())
5030 auto parseOp
= [&]() -> bool {
5031 const MCExpr
*Value
;
5032 if (parseExpression(Value
))
5035 getStreamer().emitSLEB128Value(Value
);
5037 getStreamer().emitULEB128Value(Value
);
5041 return parseMany(parseOp
);
5044 /// parseDirectiveSymbolAttribute
5045 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
5046 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr
) {
5047 auto parseOp
= [&]() -> bool {
5049 SMLoc Loc
= getTok().getLoc();
5050 if (parseIdentifier(Name
))
5051 return Error(Loc
, "expected identifier");
5053 if (discardLTOSymbol(Name
))
5056 MCSymbol
*Sym
= getContext().getOrCreateSymbol(Name
);
5058 // Assembler local symbols don't make any sense here, except for directives
5059 // that the symbol should be tagged.
5060 if (Sym
->isTemporary() && Attr
!= MCSA_Memtag
)
5061 return Error(Loc
, "non-local symbol required");
5063 if (!getStreamer().emitSymbolAttribute(Sym
, Attr
))
5064 return Error(Loc
, "unable to emit symbol attribute");
5068 return parseMany(parseOp
);
5071 /// parseDirectiveComm
5072 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
5073 bool AsmParser::parseDirectiveComm(bool IsLocal
) {
5074 if (checkForValidSection())
5077 SMLoc IDLoc
= getLexer().getLoc();
5079 if (parseIdentifier(Name
))
5080 return TokError("expected identifier in directive");
5082 // Handle the identifier as the key symbol.
5083 MCSymbol
*Sym
= getContext().getOrCreateSymbol(Name
);
5089 SMLoc SizeLoc
= getLexer().getLoc();
5090 if (parseAbsoluteExpression(Size
))
5093 int64_t Pow2Alignment
= 0;
5094 SMLoc Pow2AlignmentLoc
;
5095 if (getLexer().is(AsmToken::Comma
)) {
5097 Pow2AlignmentLoc
= getLexer().getLoc();
5098 if (parseAbsoluteExpression(Pow2Alignment
))
5101 LCOMM::LCOMMType LCOMM
= Lexer
.getMAI().getLCOMMDirectiveAlignmentType();
5102 if (IsLocal
&& LCOMM
== LCOMM::NoAlignment
)
5103 return Error(Pow2AlignmentLoc
, "alignment not supported on this target");
5105 // If this target takes alignments in bytes (not log) validate and convert.
5106 if ((!IsLocal
&& Lexer
.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
5107 (IsLocal
&& LCOMM
== LCOMM::ByteAlignment
)) {
5108 if (!isPowerOf2_64(Pow2Alignment
))
5109 return Error(Pow2AlignmentLoc
, "alignment must be a power of 2");
5110 Pow2Alignment
= Log2_64(Pow2Alignment
);
5117 // NOTE: a size of zero for a .comm should create a undefined symbol
5118 // but a size of .lcomm creates a bss symbol of size zero.
5120 return Error(SizeLoc
, "size must be non-negative");
5122 Sym
->redefineIfPossible();
5123 if (!Sym
->isUndefined())
5124 return Error(IDLoc
, "invalid symbol redefinition");
5126 // Create the Symbol as a common or local common with Size and Pow2Alignment
5128 getStreamer().emitLocalCommonSymbol(Sym
, Size
,
5129 Align(1ULL << Pow2Alignment
));
5133 getStreamer().emitCommonSymbol(Sym
, Size
, Align(1ULL << Pow2Alignment
));
5137 /// parseDirectiveAbort
5138 /// ::= .abort [... message ...]
5139 bool AsmParser::parseDirectiveAbort(SMLoc DirectiveLoc
) {
5140 StringRef Str
= parseStringToEndOfStatement();
5145 return Error(DirectiveLoc
, ".abort detected. Assembly stopping");
5147 // FIXME: Actually abort assembly here.
5148 return Error(DirectiveLoc
,
5149 ".abort '" + Str
+ "' detected. Assembly stopping");
5152 /// parseDirectiveInclude
5153 /// ::= .include "filename"
5154 bool AsmParser::parseDirectiveInclude() {
5155 // Allow the strings to have escaped octal character sequence.
5156 std::string Filename
;
5157 SMLoc IncludeLoc
= getTok().getLoc();
5159 if (check(getTok().isNot(AsmToken::String
),
5160 "expected string in '.include' directive") ||
5161 parseEscapedString(Filename
) ||
5162 check(getTok().isNot(AsmToken::EndOfStatement
),
5163 "unexpected token in '.include' directive") ||
5164 // Attempt to switch the lexer to the included file before consuming the
5165 // end of statement to avoid losing it when we switch.
5166 check(enterIncludeFile(Filename
), IncludeLoc
,
5167 "Could not find include file '" + Filename
+ "'"))
5173 /// parseDirectiveIncbin
5174 /// ::= .incbin "filename" [ , skip [ , count ] ]
5175 bool AsmParser::parseDirectiveIncbin() {
5176 // Allow the strings to have escaped octal character sequence.
5177 std::string Filename
;
5178 SMLoc IncbinLoc
= getTok().getLoc();
5179 if (check(getTok().isNot(AsmToken::String
),
5180 "expected string in '.incbin' directive") ||
5181 parseEscapedString(Filename
))
5185 const MCExpr
*Count
= nullptr;
5186 SMLoc SkipLoc
, CountLoc
;
5187 if (parseOptionalToken(AsmToken::Comma
)) {
5188 // The skip expression can be omitted while specifying the count, e.g:
5189 // .incbin "filename",,4
5190 if (getTok().isNot(AsmToken::Comma
)) {
5191 if (parseTokenLoc(SkipLoc
) || parseAbsoluteExpression(Skip
))
5194 if (parseOptionalToken(AsmToken::Comma
)) {
5195 CountLoc
= getTok().getLoc();
5196 if (parseExpression(Count
))
5204 if (check(Skip
< 0, SkipLoc
, "skip is negative"))
5207 // Attempt to process the included file.
5208 if (processIncbinFile(Filename
, Skip
, Count
, CountLoc
))
5209 return Error(IncbinLoc
, "Could not find incbin file '" + Filename
+ "'");
5213 /// parseDirectiveIf
5214 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
5215 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc
, DirectiveKind DirKind
) {
5216 TheCondStack
.push_back(TheCondState
);
5217 TheCondState
.TheCond
= AsmCond::IfCond
;
5218 if (TheCondState
.Ignore
) {
5219 eatToEndOfStatement();
5222 if (parseAbsoluteExpression(ExprValue
) || parseEOL())
5227 llvm_unreachable("unsupported directive");
5232 ExprValue
= ExprValue
== 0;
5235 ExprValue
= ExprValue
>= 0;
5238 ExprValue
= ExprValue
> 0;
5241 ExprValue
= ExprValue
<= 0;
5244 ExprValue
= ExprValue
< 0;
5248 TheCondState
.CondMet
= ExprValue
;
5249 TheCondState
.Ignore
= !TheCondState
.CondMet
;
5255 /// parseDirectiveIfb
5257 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc
, bool ExpectBlank
) {
5258 TheCondStack
.push_back(TheCondState
);
5259 TheCondState
.TheCond
= AsmCond::IfCond
;
5261 if (TheCondState
.Ignore
) {
5262 eatToEndOfStatement();
5264 StringRef Str
= parseStringToEndOfStatement();
5269 TheCondState
.CondMet
= ExpectBlank
== Str
.empty();
5270 TheCondState
.Ignore
= !TheCondState
.CondMet
;
5276 /// parseDirectiveIfc
5277 /// ::= .ifc string1, string2
5278 /// ::= .ifnc string1, string2
5279 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc
, bool ExpectEqual
) {
5280 TheCondStack
.push_back(TheCondState
);
5281 TheCondState
.TheCond
= AsmCond::IfCond
;
5283 if (TheCondState
.Ignore
) {
5284 eatToEndOfStatement();
5286 StringRef Str1
= parseStringToComma();
5291 StringRef Str2
= parseStringToEndOfStatement();
5296 TheCondState
.CondMet
= ExpectEqual
== (Str1
.trim() == Str2
.trim());
5297 TheCondState
.Ignore
= !TheCondState
.CondMet
;
5303 /// parseDirectiveIfeqs
5304 /// ::= .ifeqs string1, string2
5305 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc
, bool ExpectEqual
) {
5306 if (Lexer
.isNot(AsmToken::String
)) {
5308 return TokError("expected string parameter for '.ifeqs' directive");
5309 return TokError("expected string parameter for '.ifnes' directive");
5312 StringRef String1
= getTok().getStringContents();
5315 if (Lexer
.isNot(AsmToken::Comma
)) {
5318 "expected comma after first string for '.ifeqs' directive");
5319 return TokError("expected comma after first string for '.ifnes' directive");
5324 if (Lexer
.isNot(AsmToken::String
)) {
5326 return TokError("expected string parameter for '.ifeqs' directive");
5327 return TokError("expected string parameter for '.ifnes' directive");
5330 StringRef String2
= getTok().getStringContents();
5333 TheCondStack
.push_back(TheCondState
);
5334 TheCondState
.TheCond
= AsmCond::IfCond
;
5335 TheCondState
.CondMet
= ExpectEqual
== (String1
== String2
);
5336 TheCondState
.Ignore
= !TheCondState
.CondMet
;
5341 /// parseDirectiveIfdef
5342 /// ::= .ifdef symbol
5343 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc
, bool expect_defined
) {
5345 TheCondStack
.push_back(TheCondState
);
5346 TheCondState
.TheCond
= AsmCond::IfCond
;
5348 if (TheCondState
.Ignore
) {
5349 eatToEndOfStatement();
5351 if (check(parseIdentifier(Name
), "expected identifier after '.ifdef'") ||
5355 MCSymbol
*Sym
= getContext().lookupSymbol(Name
);
5358 TheCondState
.CondMet
= (Sym
&& !Sym
->isUndefined(false));
5360 TheCondState
.CondMet
= (!Sym
|| Sym
->isUndefined(false));
5361 TheCondState
.Ignore
= !TheCondState
.CondMet
;
5367 /// parseDirectiveElseIf
5368 /// ::= .elseif expression
5369 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc
) {
5370 if (TheCondState
.TheCond
!= AsmCond::IfCond
&&
5371 TheCondState
.TheCond
!= AsmCond::ElseIfCond
)
5372 return Error(DirectiveLoc
, "Encountered a .elseif that doesn't follow an"
5373 " .if or an .elseif");
5374 TheCondState
.TheCond
= AsmCond::ElseIfCond
;
5376 bool LastIgnoreState
= false;
5377 if (!TheCondStack
.empty())
5378 LastIgnoreState
= TheCondStack
.back().Ignore
;
5379 if (LastIgnoreState
|| TheCondState
.CondMet
) {
5380 TheCondState
.Ignore
= true;
5381 eatToEndOfStatement();
5384 if (parseAbsoluteExpression(ExprValue
))
5390 TheCondState
.CondMet
= ExprValue
;
5391 TheCondState
.Ignore
= !TheCondState
.CondMet
;
5397 /// parseDirectiveElse
5399 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc
) {
5403 if (TheCondState
.TheCond
!= AsmCond::IfCond
&&
5404 TheCondState
.TheCond
!= AsmCond::ElseIfCond
)
5405 return Error(DirectiveLoc
, "Encountered a .else that doesn't follow "
5406 " an .if or an .elseif");
5407 TheCondState
.TheCond
= AsmCond::ElseCond
;
5408 bool LastIgnoreState
= false;
5409 if (!TheCondStack
.empty())
5410 LastIgnoreState
= TheCondStack
.back().Ignore
;
5411 if (LastIgnoreState
|| TheCondState
.CondMet
)
5412 TheCondState
.Ignore
= true;
5414 TheCondState
.Ignore
= false;
5419 /// parseDirectiveEnd
5421 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc
) {
5425 while (Lexer
.isNot(AsmToken::Eof
))
5431 /// parseDirectiveError
5433 /// ::= .error [string]
5434 bool AsmParser::parseDirectiveError(SMLoc L
, bool WithMessage
) {
5435 if (!TheCondStack
.empty()) {
5436 if (TheCondStack
.back().Ignore
) {
5437 eatToEndOfStatement();
5443 return Error(L
, ".err encountered");
5445 StringRef Message
= ".error directive invoked in source file";
5446 if (Lexer
.isNot(AsmToken::EndOfStatement
)) {
5447 if (Lexer
.isNot(AsmToken::String
))
5448 return TokError(".error argument must be a string");
5450 Message
= getTok().getStringContents();
5454 return Error(L
, Message
);
5457 /// parseDirectiveWarning
5458 /// ::= .warning [string]
5459 bool AsmParser::parseDirectiveWarning(SMLoc L
) {
5460 if (!TheCondStack
.empty()) {
5461 if (TheCondStack
.back().Ignore
) {
5462 eatToEndOfStatement();
5467 StringRef Message
= ".warning directive invoked in source file";
5469 if (!parseOptionalToken(AsmToken::EndOfStatement
)) {
5470 if (Lexer
.isNot(AsmToken::String
))
5471 return TokError(".warning argument must be a string");
5473 Message
= getTok().getStringContents();
5479 return Warning(L
, Message
);
5482 /// parseDirectiveEndIf
5484 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc
) {
5488 if ((TheCondState
.TheCond
== AsmCond::NoCond
) || TheCondStack
.empty())
5489 return Error(DirectiveLoc
, "Encountered a .endif that doesn't follow "
5491 if (!TheCondStack
.empty()) {
5492 TheCondState
= TheCondStack
.back();
5493 TheCondStack
.pop_back();
5499 void AsmParser::initializeDirectiveKindMap() {
5500 /* Lookup will be done with the directive
5501 * converted to lower case, so all these
5502 * keys should be lower case.
5503 * (target specific directives are handled
5506 DirectiveKindMap
[".set"] = DK_SET
;
5507 DirectiveKindMap
[".equ"] = DK_EQU
;
5508 DirectiveKindMap
[".equiv"] = DK_EQUIV
;
5509 DirectiveKindMap
[".ascii"] = DK_ASCII
;
5510 DirectiveKindMap
[".asciz"] = DK_ASCIZ
;
5511 DirectiveKindMap
[".string"] = DK_STRING
;
5512 DirectiveKindMap
[".byte"] = DK_BYTE
;
5513 DirectiveKindMap
[".short"] = DK_SHORT
;
5514 DirectiveKindMap
[".value"] = DK_VALUE
;
5515 DirectiveKindMap
[".2byte"] = DK_2BYTE
;
5516 DirectiveKindMap
[".long"] = DK_LONG
;
5517 DirectiveKindMap
[".int"] = DK_INT
;
5518 DirectiveKindMap
[".4byte"] = DK_4BYTE
;
5519 DirectiveKindMap
[".quad"] = DK_QUAD
;
5520 DirectiveKindMap
[".8byte"] = DK_8BYTE
;
5521 DirectiveKindMap
[".octa"] = DK_OCTA
;
5522 DirectiveKindMap
[".single"] = DK_SINGLE
;
5523 DirectiveKindMap
[".float"] = DK_FLOAT
;
5524 DirectiveKindMap
[".double"] = DK_DOUBLE
;
5525 DirectiveKindMap
[".align"] = DK_ALIGN
;
5526 DirectiveKindMap
[".align32"] = DK_ALIGN32
;
5527 DirectiveKindMap
[".balign"] = DK_BALIGN
;
5528 DirectiveKindMap
[".balignw"] = DK_BALIGNW
;
5529 DirectiveKindMap
[".balignl"] = DK_BALIGNL
;
5530 DirectiveKindMap
[".p2align"] = DK_P2ALIGN
;
5531 DirectiveKindMap
[".p2alignw"] = DK_P2ALIGNW
;
5532 DirectiveKindMap
[".p2alignl"] = DK_P2ALIGNL
;
5533 DirectiveKindMap
[".org"] = DK_ORG
;
5534 DirectiveKindMap
[".fill"] = DK_FILL
;
5535 DirectiveKindMap
[".zero"] = DK_ZERO
;
5536 DirectiveKindMap
[".extern"] = DK_EXTERN
;
5537 DirectiveKindMap
[".globl"] = DK_GLOBL
;
5538 DirectiveKindMap
[".global"] = DK_GLOBAL
;
5539 DirectiveKindMap
[".lazy_reference"] = DK_LAZY_REFERENCE
;
5540 DirectiveKindMap
[".no_dead_strip"] = DK_NO_DEAD_STRIP
;
5541 DirectiveKindMap
[".symbol_resolver"] = DK_SYMBOL_RESOLVER
;
5542 DirectiveKindMap
[".private_extern"] = DK_PRIVATE_EXTERN
;
5543 DirectiveKindMap
[".reference"] = DK_REFERENCE
;
5544 DirectiveKindMap
[".weak_definition"] = DK_WEAK_DEFINITION
;
5545 DirectiveKindMap
[".weak_reference"] = DK_WEAK_REFERENCE
;
5546 DirectiveKindMap
[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN
;
5547 DirectiveKindMap
[".cold"] = DK_COLD
;
5548 DirectiveKindMap
[".comm"] = DK_COMM
;
5549 DirectiveKindMap
[".common"] = DK_COMMON
;
5550 DirectiveKindMap
[".lcomm"] = DK_LCOMM
;
5551 DirectiveKindMap
[".abort"] = DK_ABORT
;
5552 DirectiveKindMap
[".include"] = DK_INCLUDE
;
5553 DirectiveKindMap
[".incbin"] = DK_INCBIN
;
5554 DirectiveKindMap
[".code16"] = DK_CODE16
;
5555 DirectiveKindMap
[".code16gcc"] = DK_CODE16GCC
;
5556 DirectiveKindMap
[".rept"] = DK_REPT
;
5557 DirectiveKindMap
[".rep"] = DK_REPT
;
5558 DirectiveKindMap
[".irp"] = DK_IRP
;
5559 DirectiveKindMap
[".irpc"] = DK_IRPC
;
5560 DirectiveKindMap
[".endr"] = DK_ENDR
;
5561 DirectiveKindMap
[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE
;
5562 DirectiveKindMap
[".bundle_lock"] = DK_BUNDLE_LOCK
;
5563 DirectiveKindMap
[".bundle_unlock"] = DK_BUNDLE_UNLOCK
;
5564 DirectiveKindMap
[".if"] = DK_IF
;
5565 DirectiveKindMap
[".ifeq"] = DK_IFEQ
;
5566 DirectiveKindMap
[".ifge"] = DK_IFGE
;
5567 DirectiveKindMap
[".ifgt"] = DK_IFGT
;
5568 DirectiveKindMap
[".ifle"] = DK_IFLE
;
5569 DirectiveKindMap
[".iflt"] = DK_IFLT
;
5570 DirectiveKindMap
[".ifne"] = DK_IFNE
;
5571 DirectiveKindMap
[".ifb"] = DK_IFB
;
5572 DirectiveKindMap
[".ifnb"] = DK_IFNB
;
5573 DirectiveKindMap
[".ifc"] = DK_IFC
;
5574 DirectiveKindMap
[".ifeqs"] = DK_IFEQS
;
5575 DirectiveKindMap
[".ifnc"] = DK_IFNC
;
5576 DirectiveKindMap
[".ifnes"] = DK_IFNES
;
5577 DirectiveKindMap
[".ifdef"] = DK_IFDEF
;
5578 DirectiveKindMap
[".ifndef"] = DK_IFNDEF
;
5579 DirectiveKindMap
[".ifnotdef"] = DK_IFNOTDEF
;
5580 DirectiveKindMap
[".elseif"] = DK_ELSEIF
;
5581 DirectiveKindMap
[".else"] = DK_ELSE
;
5582 DirectiveKindMap
[".end"] = DK_END
;
5583 DirectiveKindMap
[".endif"] = DK_ENDIF
;
5584 DirectiveKindMap
[".skip"] = DK_SKIP
;
5585 DirectiveKindMap
[".space"] = DK_SPACE
;
5586 DirectiveKindMap
[".file"] = DK_FILE
;
5587 DirectiveKindMap
[".line"] = DK_LINE
;
5588 DirectiveKindMap
[".loc"] = DK_LOC
;
5589 DirectiveKindMap
[".loc_label"] = DK_LOC_LABEL
;
5590 DirectiveKindMap
[".stabs"] = DK_STABS
;
5591 DirectiveKindMap
[".cv_file"] = DK_CV_FILE
;
5592 DirectiveKindMap
[".cv_func_id"] = DK_CV_FUNC_ID
;
5593 DirectiveKindMap
[".cv_loc"] = DK_CV_LOC
;
5594 DirectiveKindMap
[".cv_linetable"] = DK_CV_LINETABLE
;
5595 DirectiveKindMap
[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE
;
5596 DirectiveKindMap
[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID
;
5597 DirectiveKindMap
[".cv_def_range"] = DK_CV_DEF_RANGE
;
5598 DirectiveKindMap
[".cv_string"] = DK_CV_STRING
;
5599 DirectiveKindMap
[".cv_stringtable"] = DK_CV_STRINGTABLE
;
5600 DirectiveKindMap
[".cv_filechecksums"] = DK_CV_FILECHECKSUMS
;
5601 DirectiveKindMap
[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET
;
5602 DirectiveKindMap
[".cv_fpo_data"] = DK_CV_FPO_DATA
;
5603 DirectiveKindMap
[".sleb128"] = DK_SLEB128
;
5604 DirectiveKindMap
[".uleb128"] = DK_ULEB128
;
5605 DirectiveKindMap
[".cfi_sections"] = DK_CFI_SECTIONS
;
5606 DirectiveKindMap
[".cfi_startproc"] = DK_CFI_STARTPROC
;
5607 DirectiveKindMap
[".cfi_endproc"] = DK_CFI_ENDPROC
;
5608 DirectiveKindMap
[".cfi_def_cfa"] = DK_CFI_DEF_CFA
;
5609 DirectiveKindMap
[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET
;
5610 DirectiveKindMap
[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET
;
5611 DirectiveKindMap
[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER
;
5612 DirectiveKindMap
[".cfi_llvm_def_aspace_cfa"] = DK_CFI_LLVM_DEF_ASPACE_CFA
;
5613 DirectiveKindMap
[".cfi_offset"] = DK_CFI_OFFSET
;
5614 DirectiveKindMap
[".cfi_rel_offset"] = DK_CFI_REL_OFFSET
;
5615 DirectiveKindMap
[".cfi_personality"] = DK_CFI_PERSONALITY
;
5616 DirectiveKindMap
[".cfi_lsda"] = DK_CFI_LSDA
;
5617 DirectiveKindMap
[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE
;
5618 DirectiveKindMap
[".cfi_restore_state"] = DK_CFI_RESTORE_STATE
;
5619 DirectiveKindMap
[".cfi_same_value"] = DK_CFI_SAME_VALUE
;
5620 DirectiveKindMap
[".cfi_restore"] = DK_CFI_RESTORE
;
5621 DirectiveKindMap
[".cfi_escape"] = DK_CFI_ESCAPE
;
5622 DirectiveKindMap
[".cfi_return_column"] = DK_CFI_RETURN_COLUMN
;
5623 DirectiveKindMap
[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME
;
5624 DirectiveKindMap
[".cfi_undefined"] = DK_CFI_UNDEFINED
;
5625 DirectiveKindMap
[".cfi_register"] = DK_CFI_REGISTER
;
5626 DirectiveKindMap
[".cfi_window_save"] = DK_CFI_WINDOW_SAVE
;
5627 DirectiveKindMap
[".cfi_label"] = DK_CFI_LABEL
;
5628 DirectiveKindMap
[".cfi_b_key_frame"] = DK_CFI_B_KEY_FRAME
;
5629 DirectiveKindMap
[".cfi_mte_tagged_frame"] = DK_CFI_MTE_TAGGED_FRAME
;
5630 DirectiveKindMap
[".cfi_val_offset"] = DK_CFI_VAL_OFFSET
;
5631 DirectiveKindMap
[".macros_on"] = DK_MACROS_ON
;
5632 DirectiveKindMap
[".macros_off"] = DK_MACROS_OFF
;
5633 DirectiveKindMap
[".macro"] = DK_MACRO
;
5634 DirectiveKindMap
[".exitm"] = DK_EXITM
;
5635 DirectiveKindMap
[".endm"] = DK_ENDM
;
5636 DirectiveKindMap
[".endmacro"] = DK_ENDMACRO
;
5637 DirectiveKindMap
[".purgem"] = DK_PURGEM
;
5638 DirectiveKindMap
[".err"] = DK_ERR
;
5639 DirectiveKindMap
[".error"] = DK_ERROR
;
5640 DirectiveKindMap
[".warning"] = DK_WARNING
;
5641 DirectiveKindMap
[".altmacro"] = DK_ALTMACRO
;
5642 DirectiveKindMap
[".noaltmacro"] = DK_NOALTMACRO
;
5643 DirectiveKindMap
[".reloc"] = DK_RELOC
;
5644 DirectiveKindMap
[".dc"] = DK_DC
;
5645 DirectiveKindMap
[".dc.a"] = DK_DC_A
;
5646 DirectiveKindMap
[".dc.b"] = DK_DC_B
;
5647 DirectiveKindMap
[".dc.d"] = DK_DC_D
;
5648 DirectiveKindMap
[".dc.l"] = DK_DC_L
;
5649 DirectiveKindMap
[".dc.s"] = DK_DC_S
;
5650 DirectiveKindMap
[".dc.w"] = DK_DC_W
;
5651 DirectiveKindMap
[".dc.x"] = DK_DC_X
;
5652 DirectiveKindMap
[".dcb"] = DK_DCB
;
5653 DirectiveKindMap
[".dcb.b"] = DK_DCB_B
;
5654 DirectiveKindMap
[".dcb.d"] = DK_DCB_D
;
5655 DirectiveKindMap
[".dcb.l"] = DK_DCB_L
;
5656 DirectiveKindMap
[".dcb.s"] = DK_DCB_S
;
5657 DirectiveKindMap
[".dcb.w"] = DK_DCB_W
;
5658 DirectiveKindMap
[".dcb.x"] = DK_DCB_X
;
5659 DirectiveKindMap
[".ds"] = DK_DS
;
5660 DirectiveKindMap
[".ds.b"] = DK_DS_B
;
5661 DirectiveKindMap
[".ds.d"] = DK_DS_D
;
5662 DirectiveKindMap
[".ds.l"] = DK_DS_L
;
5663 DirectiveKindMap
[".ds.p"] = DK_DS_P
;
5664 DirectiveKindMap
[".ds.s"] = DK_DS_S
;
5665 DirectiveKindMap
[".ds.w"] = DK_DS_W
;
5666 DirectiveKindMap
[".ds.x"] = DK_DS_X
;
5667 DirectiveKindMap
[".print"] = DK_PRINT
;
5668 DirectiveKindMap
[".addrsig"] = DK_ADDRSIG
;
5669 DirectiveKindMap
[".addrsig_sym"] = DK_ADDRSIG_SYM
;
5670 DirectiveKindMap
[".pseudoprobe"] = DK_PSEUDO_PROBE
;
5671 DirectiveKindMap
[".lto_discard"] = DK_LTO_DISCARD
;
5672 DirectiveKindMap
[".lto_set_conditional"] = DK_LTO_SET_CONDITIONAL
;
5673 DirectiveKindMap
[".memtag"] = DK_MEMTAG
;
5676 MCAsmMacro
*AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc
) {
5677 AsmToken EndToken
, StartToken
= getTok();
5679 unsigned NestLevel
= 0;
5681 // Check whether we have reached the end of the file.
5682 if (getLexer().is(AsmToken::Eof
)) {
5683 printError(DirectiveLoc
, "no matching '.endr' in definition");
5687 if (Lexer
.is(AsmToken::Identifier
)) {
5688 StringRef Ident
= getTok().getIdentifier();
5689 if (Ident
== ".rep" || Ident
== ".rept" || Ident
== ".irp" ||
5692 } else if (Ident
== ".endr") {
5693 if (NestLevel
== 0) {
5694 EndToken
= getTok();
5696 if (Lexer
.is(AsmToken::EndOfStatement
))
5698 printError(getTok().getLoc(), "expected newline");
5705 // Otherwise, scan till the end of the statement.
5706 eatToEndOfStatement();
5709 const char *BodyStart
= StartToken
.getLoc().getPointer();
5710 const char *BodyEnd
= EndToken
.getLoc().getPointer();
5711 StringRef Body
= StringRef(BodyStart
, BodyEnd
- BodyStart
);
5713 // We Are Anonymous.
5714 MacroLikeBodies
.emplace_back(StringRef(), Body
, MCAsmMacroParameters());
5715 return &MacroLikeBodies
.back();
5718 void AsmParser::instantiateMacroLikeBody(MCAsmMacro
*M
, SMLoc DirectiveLoc
,
5719 raw_svector_ostream
&OS
) {
5722 std::unique_ptr
<MemoryBuffer
> Instantiation
=
5723 MemoryBuffer::getMemBufferCopy(OS
.str(), "<instantiation>");
5725 // Create the macro instantiation object and add to the current macro
5726 // instantiation stack.
5727 MacroInstantiation
*MI
= new MacroInstantiation
{
5728 DirectiveLoc
, CurBuffer
, getTok().getLoc(), TheCondStack
.size()};
5729 ActiveMacros
.push_back(MI
);
5731 // Jump to the macro instantiation and prime the lexer.
5732 CurBuffer
= SrcMgr
.AddNewSourceBuffer(std::move(Instantiation
), SMLoc());
5733 Lexer
.setBuffer(SrcMgr
.getMemoryBuffer(CurBuffer
)->getBuffer());
5737 /// parseDirectiveRept
5738 /// ::= .rep | .rept count
5739 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc
, StringRef Dir
) {
5740 const MCExpr
*CountExpr
;
5741 SMLoc CountLoc
= getTok().getLoc();
5742 if (parseExpression(CountExpr
))
5746 if (!CountExpr
->evaluateAsAbsolute(Count
, getStreamer().getAssemblerPtr())) {
5747 return Error(CountLoc
, "unexpected token in '" + Dir
+ "' directive");
5750 if (check(Count
< 0, CountLoc
, "Count is negative") || parseEOL())
5753 // Lex the rept definition.
5754 MCAsmMacro
*M
= parseMacroLikeBody(DirectiveLoc
);
5758 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5759 // to hold the macro body with substitutions.
5760 SmallString
<256> Buf
;
5761 raw_svector_ostream
OS(Buf
);
5763 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5764 if (expandMacro(OS
, *M
, {}, {}, false))
5767 instantiateMacroLikeBody(M
, DirectiveLoc
, OS
);
5772 /// parseDirectiveIrp
5773 /// ::= .irp symbol,values
5774 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc
) {
5775 MCAsmMacroParameter Parameter
;
5776 MCAsmMacroArguments A
;
5777 if (check(parseIdentifier(Parameter
.Name
),
5778 "expected identifier in '.irp' directive") ||
5779 parseComma() || parseMacroArguments(nullptr, A
) || parseEOL())
5782 // Lex the irp definition.
5783 MCAsmMacro
*M
= parseMacroLikeBody(DirectiveLoc
);
5787 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5788 // to hold the macro body with substitutions.
5789 SmallString
<256> Buf
;
5790 raw_svector_ostream
OS(Buf
);
5792 for (const MCAsmMacroArgument
&Arg
: A
) {
5793 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5794 // This is undocumented, but GAS seems to support it.
5795 if (expandMacro(OS
, *M
, Parameter
, Arg
, true))
5799 instantiateMacroLikeBody(M
, DirectiveLoc
, OS
);
5804 /// parseDirectiveIrpc
5805 /// ::= .irpc symbol,values
5806 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc
) {
5807 MCAsmMacroParameter Parameter
;
5808 MCAsmMacroArguments A
;
5810 if (check(parseIdentifier(Parameter
.Name
),
5811 "expected identifier in '.irpc' directive") ||
5812 parseComma() || parseMacroArguments(nullptr, A
))
5815 if (A
.size() != 1 || A
.front().size() != 1)
5816 return TokError("unexpected token in '.irpc' directive");
5820 // Lex the irpc definition.
5821 MCAsmMacro
*M
= parseMacroLikeBody(DirectiveLoc
);
5825 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5826 // to hold the macro body with substitutions.
5827 SmallString
<256> Buf
;
5828 raw_svector_ostream
OS(Buf
);
5830 StringRef Values
= A
[0][0].is(AsmToken::String
) ? A
[0][0].getStringContents()
5831 : A
[0][0].getString();
5832 for (std::size_t I
= 0, End
= Values
.size(); I
!= End
; ++I
) {
5833 MCAsmMacroArgument Arg
;
5834 Arg
.emplace_back(AsmToken::Identifier
, Values
.substr(I
, 1));
5836 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5837 // This is undocumented, but GAS seems to support it.
5838 if (expandMacro(OS
, *M
, Parameter
, Arg
, true))
5842 instantiateMacroLikeBody(M
, DirectiveLoc
, OS
);
5847 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc
) {
5848 if (ActiveMacros
.empty())
5849 return TokError("unmatched '.endr' directive");
5851 // The only .repl that should get here are the ones created by
5852 // instantiateMacroLikeBody.
5853 assert(getLexer().is(AsmToken::EndOfStatement
));
5859 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc
, ParseStatementInfo
&Info
,
5861 const MCExpr
*Value
;
5862 SMLoc ExprLoc
= getLexer().getLoc();
5863 if (parseExpression(Value
))
5865 const MCConstantExpr
*MCE
= dyn_cast
<MCConstantExpr
>(Value
);
5867 return Error(ExprLoc
, "unexpected expression in _emit");
5868 uint64_t IntValue
= MCE
->getValue();
5869 if (!isUInt
<8>(IntValue
) && !isInt
<8>(IntValue
))
5870 return Error(ExprLoc
, "literal value out of range for directive");
5872 Info
.AsmRewrites
->emplace_back(AOK_Emit
, IDLoc
, Len
);
5876 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc
, ParseStatementInfo
&Info
) {
5877 const MCExpr
*Value
;
5878 SMLoc ExprLoc
= getLexer().getLoc();
5879 if (parseExpression(Value
))
5881 const MCConstantExpr
*MCE
= dyn_cast
<MCConstantExpr
>(Value
);
5883 return Error(ExprLoc
, "unexpected expression in align");
5884 uint64_t IntValue
= MCE
->getValue();
5885 if (!isPowerOf2_64(IntValue
))
5886 return Error(ExprLoc
, "literal value not a power of two greater then zero");
5888 Info
.AsmRewrites
->emplace_back(AOK_Align
, IDLoc
, 5, Log2_64(IntValue
));
5892 bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc
) {
5893 const AsmToken StrTok
= getTok();
5895 if (StrTok
.isNot(AsmToken::String
) || StrTok
.getString().front() != '"')
5896 return Error(DirectiveLoc
, "expected double quoted string after .print");
5899 llvm::outs() << StrTok
.getStringContents() << '\n';
5903 bool AsmParser::parseDirectiveAddrsig() {
5906 getStreamer().emitAddrsig();
5910 bool AsmParser::parseDirectiveAddrsigSym() {
5912 if (check(parseIdentifier(Name
), "expected identifier") || parseEOL())
5914 MCSymbol
*Sym
= getContext().getOrCreateSymbol(Name
);
5915 getStreamer().emitAddrsigSym(Sym
);
5919 bool AsmParser::parseDirectivePseudoProbe() {
5924 int64_t Discriminator
= 0;
5926 if (parseIntToken(Guid
, "unexpected token in '.pseudoprobe' directive"))
5929 if (parseIntToken(Index
, "unexpected token in '.pseudoprobe' directive"))
5932 if (parseIntToken(Type
, "unexpected token in '.pseudoprobe' directive"))
5935 if (parseIntToken(Attr
, "unexpected token in '.pseudoprobe' directive"))
5938 if (hasDiscriminator(Attr
)) {
5939 if (parseIntToken(Discriminator
,
5940 "unexpected token in '.pseudoprobe' directive"))
5944 // Parse inline stack like @ GUID:11:12 @ GUID:1:11 @ GUID:3:21
5945 MCPseudoProbeInlineStack InlineStack
;
5947 while (getLexer().is(AsmToken::At
)) {
5951 int64_t CallerGuid
= 0;
5952 if (getLexer().is(AsmToken::Integer
)) {
5953 if (parseIntToken(CallerGuid
,
5954 "unexpected token in '.pseudoprobe' directive"))
5959 if (getLexer().is(AsmToken::Colon
))
5962 int64_t CallerProbeId
= 0;
5963 if (getLexer().is(AsmToken::Integer
)) {
5964 if (parseIntToken(CallerProbeId
,
5965 "unexpected token in '.pseudoprobe' directive"))
5969 InlineSite
Site(CallerGuid
, CallerProbeId
);
5970 InlineStack
.push_back(Site
);
5973 // Parse function entry name
5975 if (parseIdentifier(FnName
))
5976 return Error(getLexer().getLoc(), "unexpected token in '.pseudoprobe' directive");
5977 MCSymbol
*FnSym
= getContext().lookupSymbol(FnName
);
5982 getStreamer().emitPseudoProbe(Guid
, Index
, Type
, Attr
, Discriminator
,
5983 InlineStack
, FnSym
);
5987 /// parseDirectiveLTODiscard
5988 /// ::= ".lto_discard" [ identifier ( , identifier )* ]
5989 /// The LTO library emits this directive to discard non-prevailing symbols.
5990 /// We ignore symbol assignments and attribute changes for the specified
5992 bool AsmParser::parseDirectiveLTODiscard() {
5993 auto ParseOp
= [&]() -> bool {
5995 SMLoc Loc
= getTok().getLoc();
5996 if (parseIdentifier(Name
))
5997 return Error(Loc
, "expected identifier");
5998 LTODiscardSymbols
.insert(Name
);
6002 LTODiscardSymbols
.clear();
6003 return parseMany(ParseOp
);
6006 // We are comparing pointers, but the pointers are relative to a single string.
6007 // Thus, this should always be deterministic.
6008 static int rewritesSort(const AsmRewrite
*AsmRewriteA
,
6009 const AsmRewrite
*AsmRewriteB
) {
6010 if (AsmRewriteA
->Loc
.getPointer() < AsmRewriteB
->Loc
.getPointer())
6012 if (AsmRewriteB
->Loc
.getPointer() < AsmRewriteA
->Loc
.getPointer())
6015 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
6016 // rewrite to the same location. Make sure the SizeDirective rewrite is
6017 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
6018 // ensures the sort algorithm is stable.
6019 if (AsmRewritePrecedence
[AsmRewriteA
->Kind
] >
6020 AsmRewritePrecedence
[AsmRewriteB
->Kind
])
6023 if (AsmRewritePrecedence
[AsmRewriteA
->Kind
] <
6024 AsmRewritePrecedence
[AsmRewriteB
->Kind
])
6026 llvm_unreachable("Unstable rewrite sort.");
6029 bool AsmParser::parseMSInlineAsm(
6030 std::string
&AsmString
, unsigned &NumOutputs
, unsigned &NumInputs
,
6031 SmallVectorImpl
<std::pair
<void *, bool>> &OpDecls
,
6032 SmallVectorImpl
<std::string
> &Constraints
,
6033 SmallVectorImpl
<std::string
> &Clobbers
, const MCInstrInfo
*MII
,
6034 MCInstPrinter
*IP
, MCAsmParserSemaCallback
&SI
) {
6035 SmallVector
<void *, 4> InputDecls
;
6036 SmallVector
<void *, 4> OutputDecls
;
6037 SmallVector
<bool, 4> InputDeclsAddressOf
;
6038 SmallVector
<bool, 4> OutputDeclsAddressOf
;
6039 SmallVector
<std::string
, 4> InputConstraints
;
6040 SmallVector
<std::string
, 4> OutputConstraints
;
6041 SmallVector
<MCRegister
, 4> ClobberRegs
;
6043 SmallVector
<AsmRewrite
, 4> AsmStrRewrites
;
6048 // While we have input, parse each statement.
6049 unsigned InputIdx
= 0;
6050 unsigned OutputIdx
= 0;
6051 while (getLexer().isNot(AsmToken::Eof
)) {
6052 // Parse curly braces marking block start/end
6053 if (parseCurlyBlockScope(AsmStrRewrites
))
6056 ParseStatementInfo
Info(&AsmStrRewrites
);
6057 bool StatementErr
= parseStatement(Info
, &SI
);
6059 if (StatementErr
|| Info
.ParseError
) {
6060 // Emit pending errors if any exist.
6061 printPendingErrors();
6065 // No pending error should exist here.
6066 assert(!hasPendingError() && "unexpected error from parseStatement");
6068 if (Info
.Opcode
== ~0U)
6071 const MCInstrDesc
&Desc
= MII
->get(Info
.Opcode
);
6073 // Build the list of clobbers, outputs and inputs.
6074 for (unsigned i
= 1, e
= Info
.ParsedOperands
.size(); i
!= e
; ++i
) {
6075 MCParsedAsmOperand
&Operand
= *Info
.ParsedOperands
[i
];
6077 // Register operand.
6078 if (Operand
.isReg() && !Operand
.needAddressOf() &&
6079 !getTargetParser().omitRegisterFromClobberLists(Operand
.getReg())) {
6080 unsigned NumDefs
= Desc
.getNumDefs();
6082 if (NumDefs
&& Operand
.getMCOperandNum() < NumDefs
)
6083 ClobberRegs
.push_back(Operand
.getReg());
6087 // Expr/Input or Output.
6088 StringRef SymName
= Operand
.getSymName();
6089 if (SymName
.empty())
6092 void *OpDecl
= Operand
.getOpDecl();
6096 StringRef Constraint
= Operand
.getConstraint();
6097 if (Operand
.isImm()) {
6098 // Offset as immediate
6099 if (Operand
.isOffsetOfLocal())
6105 bool isOutput
= (i
== 1) && Desc
.mayStore();
6106 bool Restricted
= Operand
.isMemUseUpRegs();
6107 SMLoc Start
= SMLoc::getFromPointer(SymName
.data());
6110 OutputDecls
.push_back(OpDecl
);
6111 OutputDeclsAddressOf
.push_back(Operand
.needAddressOf());
6112 OutputConstraints
.push_back(("=" + Constraint
).str());
6113 AsmStrRewrites
.emplace_back(AOK_Output
, Start
, SymName
.size(), 0,
6116 InputDecls
.push_back(OpDecl
);
6117 InputDeclsAddressOf
.push_back(Operand
.needAddressOf());
6118 InputConstraints
.push_back(Constraint
.str());
6119 if (Desc
.operands()[i
- 1].isBranchTarget())
6120 AsmStrRewrites
.emplace_back(AOK_CallInput
, Start
, SymName
.size(), 0,
6123 AsmStrRewrites
.emplace_back(AOK_Input
, Start
, SymName
.size(), 0,
6128 // Consider implicit defs to be clobbers. Think of cpuid and push.
6129 llvm::append_range(ClobberRegs
, Desc
.implicit_defs());
6132 // Set the number of Outputs and Inputs.
6133 NumOutputs
= OutputDecls
.size();
6134 NumInputs
= InputDecls
.size();
6136 // Set the unique clobbers.
6137 array_pod_sort(ClobberRegs
.begin(), ClobberRegs
.end());
6138 ClobberRegs
.erase(llvm::unique(ClobberRegs
), ClobberRegs
.end());
6139 Clobbers
.assign(ClobberRegs
.size(), std::string());
6140 for (unsigned I
= 0, E
= ClobberRegs
.size(); I
!= E
; ++I
) {
6141 raw_string_ostream
OS(Clobbers
[I
]);
6142 IP
->printRegName(OS
, ClobberRegs
[I
]);
6145 // Merge the various outputs and inputs. Output are expected first.
6146 if (NumOutputs
|| NumInputs
) {
6147 unsigned NumExprs
= NumOutputs
+ NumInputs
;
6148 OpDecls
.resize(NumExprs
);
6149 Constraints
.resize(NumExprs
);
6150 for (unsigned i
= 0; i
< NumOutputs
; ++i
) {
6151 OpDecls
[i
] = std::make_pair(OutputDecls
[i
], OutputDeclsAddressOf
[i
]);
6152 Constraints
[i
] = OutputConstraints
[i
];
6154 for (unsigned i
= 0, j
= NumOutputs
; i
< NumInputs
; ++i
, ++j
) {
6155 OpDecls
[j
] = std::make_pair(InputDecls
[i
], InputDeclsAddressOf
[i
]);
6156 Constraints
[j
] = InputConstraints
[i
];
6160 // Build the IR assembly string.
6161 std::string AsmStringIR
;
6162 raw_string_ostream
OS(AsmStringIR
);
6163 StringRef ASMString
=
6164 SrcMgr
.getMemoryBuffer(SrcMgr
.getMainFileID())->getBuffer();
6165 const char *AsmStart
= ASMString
.begin();
6166 const char *AsmEnd
= ASMString
.end();
6167 array_pod_sort(AsmStrRewrites
.begin(), AsmStrRewrites
.end(), rewritesSort
);
6168 for (auto I
= AsmStrRewrites
.begin(), E
= AsmStrRewrites
.end(); I
!= E
; ++I
) {
6169 const AsmRewrite
&AR
= *I
;
6170 // Check if this has already been covered by another rewrite...
6173 AsmRewriteKind Kind
= AR
.Kind
;
6175 const char *Loc
= AR
.Loc
.getPointer();
6176 assert(Loc
>= AsmStart
&& "Expected Loc to be at or after Start!");
6178 // Emit everything up to the immediate/expression.
6179 if (unsigned Len
= Loc
- AsmStart
)
6180 OS
<< StringRef(AsmStart
, Len
);
6182 // Skip the original expression.
6183 if (Kind
== AOK_Skip
) {
6184 AsmStart
= Loc
+ AR
.Len
;
6188 unsigned AdditionalSkip
= 0;
6189 // Rewrite expressions in $N notation.
6194 assert(AR
.IntelExp
.isValid() && "cannot write invalid intel expression");
6195 if (AR
.IntelExp
.NeedBracs
)
6197 if (AR
.IntelExp
.hasBaseReg())
6198 OS
<< AR
.IntelExp
.BaseReg
;
6199 if (AR
.IntelExp
.hasIndexReg())
6200 OS
<< (AR
.IntelExp
.hasBaseReg() ? " + " : "")
6201 << AR
.IntelExp
.IndexReg
;
6202 if (AR
.IntelExp
.Scale
> 1)
6203 OS
<< " * $$" << AR
.IntelExp
.Scale
;
6204 if (AR
.IntelExp
.hasOffset()) {
6205 if (AR
.IntelExp
.hasRegs())
6207 // Fuse this rewrite with a rewrite of the offset name, if present.
6208 StringRef OffsetName
= AR
.IntelExp
.OffsetName
;
6209 SMLoc OffsetLoc
= SMLoc::getFromPointer(AR
.IntelExp
.OffsetName
.data());
6210 size_t OffsetLen
= OffsetName
.size();
6211 auto rewrite_it
= std::find_if(
6212 I
, AsmStrRewrites
.end(), [&](const AsmRewrite
&FusingAR
) {
6213 return FusingAR
.Loc
== OffsetLoc
&& FusingAR
.Len
== OffsetLen
&&
6214 (FusingAR
.Kind
== AOK_Input
||
6215 FusingAR
.Kind
== AOK_CallInput
);
6217 if (rewrite_it
== AsmStrRewrites
.end()) {
6218 OS
<< "offset " << OffsetName
;
6219 } else if (rewrite_it
->Kind
== AOK_CallInput
) {
6220 OS
<< "${" << InputIdx
++ << ":P}";
6221 rewrite_it
->Done
= true;
6223 OS
<< '$' << InputIdx
++;
6224 rewrite_it
->Done
= true;
6227 if (AR
.IntelExp
.Imm
|| AR
.IntelExp
.emitImm())
6228 OS
<< (AR
.IntelExp
.emitImm() ? "$$" : " + $$") << AR
.IntelExp
.Imm
;
6229 if (AR
.IntelExp
.NeedBracs
)
6233 OS
<< Ctx
.getAsmInfo()->getPrivateLabelPrefix() << AR
.Label
;
6236 if (AR
.IntelExpRestricted
)
6237 OS
<< "${" << InputIdx
++ << ":P}";
6239 OS
<< '$' << InputIdx
++;
6242 OS
<< "${" << InputIdx
++ << ":P}";
6245 if (AR
.IntelExpRestricted
)
6246 OS
<< "${" << OutputIdx
++ << ":P}";
6248 OS
<< '$' << OutputIdx
++;
6250 case AOK_SizeDirective
:
6253 case 8: OS
<< "byte ptr "; break;
6254 case 16: OS
<< "word ptr "; break;
6255 case 32: OS
<< "dword ptr "; break;
6256 case 64: OS
<< "qword ptr "; break;
6257 case 80: OS
<< "xword ptr "; break;
6258 case 128: OS
<< "xmmword ptr "; break;
6259 case 256: OS
<< "ymmword ptr "; break;
6266 // MS alignment directives are measured in bytes. If the native assembler
6267 // measures alignment in bytes, we can pass it straight through.
6269 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
6272 // Alignment is in log2 form, so print that instead and skip the original
6274 unsigned Val
= AR
.Val
;
6276 assert(Val
< 10 && "Expected alignment less then 2^10.");
6277 AdditionalSkip
= (Val
< 4) ? 2 : Val
< 7 ? 3 : 4;
6283 case AOK_EndOfStatement
:
6288 // Skip the original expression.
6289 AsmStart
= Loc
+ AR
.Len
+ AdditionalSkip
;
6292 // Emit the remainder of the asm string.
6293 if (AsmStart
!= AsmEnd
)
6294 OS
<< StringRef(AsmStart
, AsmEnd
- AsmStart
);
6296 AsmString
= std::move(AsmStringIR
);
6300 bool HLASMAsmParser::parseAsHLASMLabel(ParseStatementInfo
&Info
,
6301 MCAsmParserSemaCallback
*SI
) {
6302 AsmToken LabelTok
= getTok();
6303 SMLoc LabelLoc
= LabelTok
.getLoc();
6306 if (parseIdentifier(LabelVal
))
6307 return Error(LabelLoc
, "The HLASM Label has to be an Identifier");
6309 // We have validated whether the token is an Identifier.
6310 // Now we have to validate whether the token is a
6311 // valid HLASM Label.
6312 if (!getTargetParser().isLabel(LabelTok
) || checkForValidSection())
6315 // Lex leading spaces to get to the next operand.
6318 // We shouldn't emit the label if there is nothing else after the label.
6319 // i.e asm("<token>\n")
6320 if (getTok().is(AsmToken::EndOfStatement
))
6321 return Error(LabelLoc
,
6322 "Cannot have just a label for an HLASM inline asm statement");
6324 MCSymbol
*Sym
= getContext().getOrCreateSymbol(
6325 getContext().getAsmInfo()->shouldEmitLabelsInUpperCase()
6329 getTargetParser().doBeforeLabelEmit(Sym
, LabelLoc
);
6332 Out
.emitLabel(Sym
, LabelLoc
);
6334 // If we are generating dwarf for assembly source files then gather the
6335 // info to make a dwarf label entry for this label if needed.
6336 if (enabledGenDwarfForAssembly())
6337 MCGenDwarfLabelEntry::Make(Sym
, &getStreamer(), getSourceManager(),
6340 getTargetParser().onLabelParsed(Sym
);
6345 bool HLASMAsmParser::parseAsMachineInstruction(ParseStatementInfo
&Info
,
6346 MCAsmParserSemaCallback
*SI
) {
6347 AsmToken OperationEntryTok
= Lexer
.getTok();
6348 SMLoc OperationEntryLoc
= OperationEntryTok
.getLoc();
6349 StringRef OperationEntryVal
;
6351 // Attempt to parse the first token as an Identifier
6352 if (parseIdentifier(OperationEntryVal
))
6353 return Error(OperationEntryLoc
, "unexpected token at start of statement");
6355 // Once we've parsed the operation entry successfully, lex
6356 // any spaces to get to the OperandEntries.
6359 return parseAndMatchAndEmitTargetInstruction(
6360 Info
, OperationEntryVal
, OperationEntryTok
, OperationEntryLoc
);
6363 bool HLASMAsmParser::parseStatement(ParseStatementInfo
&Info
,
6364 MCAsmParserSemaCallback
*SI
) {
6365 assert(!hasPendingError() && "parseStatement started with pending error");
6367 // Should the first token be interpreted as a HLASM Label.
6368 bool ShouldParseAsHLASMLabel
= false;
6370 // If a Name Entry exists, it should occur at the very
6371 // start of the string. In this case, we should parse the
6372 // first non-space token as a Label.
6373 // If the Name entry is missing (i.e. there's some other
6374 // token), then we attempt to parse the first non-space
6375 // token as a Machine Instruction.
6376 if (getTok().isNot(AsmToken::Space
))
6377 ShouldParseAsHLASMLabel
= true;
6379 // If we have an EndOfStatement (which includes the target's comment
6380 // string) we can appropriately lex it early on)
6381 if (Lexer
.is(AsmToken::EndOfStatement
)) {
6382 // if this is a line comment we can drop it safely
6383 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
6384 getTok().getString().front() == '\n')
6390 // We have established how to parse the inline asm statement.
6391 // Now we can safely lex any leading spaces to get to the
6395 // If we see a new line or carriage return as the first operand,
6396 // after lexing leading spaces, emit the new line and lex the
6397 // EndOfStatement token.
6398 if (Lexer
.is(AsmToken::EndOfStatement
)) {
6399 if (getTok().getString().front() == '\n' ||
6400 getTok().getString().front() == '\r') {
6407 // Handle the label first if we have to before processing the rest
6408 // of the tokens as a machine instruction.
6409 if (ShouldParseAsHLASMLabel
) {
6410 // If there were any errors while handling and emitting the label,
6412 if (parseAsHLASMLabel(Info
, SI
)) {
6413 // If we know we've failed in parsing, simply eat until end of the
6414 // statement. This ensures that we don't process any other statements.
6415 eatToEndOfStatement();
6420 return parseAsMachineInstruction(Info
, SI
);
6424 namespace MCParserUtils
{
6426 bool parseAssignmentExpression(StringRef Name
, bool allow_redef
,
6427 MCAsmParser
&Parser
, MCSymbol
*&Sym
,
6428 const MCExpr
*&Value
) {
6430 // FIXME: Use better location, we should use proper tokens.
6431 SMLoc EqualLoc
= Parser
.getTok().getLoc();
6432 if (Parser
.parseExpression(Value
))
6433 return Parser
.TokError("missing expression");
6435 // Note: we don't count b as used in "a = b". This is to allow
6439 if (Parser
.parseEOL())
6442 // Validate that the LHS is allowed to be a variable (either it has not been
6443 // used as a symbol, or it is an absolute symbol).
6444 Sym
= Parser
.getContext().lookupSymbol(Name
);
6446 // Diagnose assignment to a label.
6448 // FIXME: Diagnostics. Note the location of the definition as a label.
6449 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
6450 if (Value
->isSymbolUsedInExpression(Sym
))
6451 return Parser
.Error(EqualLoc
, "Recursive use of '" + Name
+ "'");
6452 else if (Sym
->isUndefined(/*SetUsed*/ false) && !Sym
->isUsed() &&
6454 ; // Allow redefinitions of undefined symbols only used in directives.
6455 else if (Sym
->isVariable() && !Sym
->isUsed() && allow_redef
)
6456 ; // Allow redefinitions of variables that haven't yet been used.
6457 else if (!Sym
->isUndefined() && (!Sym
->isVariable() || !allow_redef
))
6458 return Parser
.Error(EqualLoc
, "redefinition of '" + Name
+ "'");
6459 else if (!Sym
->isVariable())
6460 return Parser
.Error(EqualLoc
, "invalid assignment to '" + Name
+ "'");
6461 else if (!isa
<MCConstantExpr
>(Sym
->getVariableValue()))
6462 return Parser
.Error(EqualLoc
,
6463 "invalid reassignment of non-absolute variable '" +
6465 } else if (Name
== ".") {
6466 Parser
.getStreamer().emitValueToOffset(Value
, 0, EqualLoc
);
6469 Sym
= Parser
.getContext().getOrCreateSymbol(Name
);
6471 Sym
->setRedefinable(allow_redef
);
6476 } // end namespace MCParserUtils
6477 } // end namespace llvm
6479 /// Create an MCAsmParser instance.
6480 MCAsmParser
*llvm::createMCAsmParser(SourceMgr
&SM
, MCContext
&C
,
6481 MCStreamer
&Out
, const MCAsmInfo
&MAI
,
6483 if (C
.getTargetTriple().isSystemZ() && C
.getTargetTriple().isOSzOS())
6484 return new HLASMAsmParser(SM
, C
, Out
, MAI
, CB
);
6486 return new AsmParser(SM
, C
, Out
, MAI
, CB
);