1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCParser/AsmCond.h"
27 #include "llvm/MC/MCParser/AsmLexer.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
30 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCSectionMachO.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/MC/MCTargetAsmParser.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/SourceMgr.h"
41 #include "llvm/Support/raw_ostream.h"
49 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
52 /// \brief Helper types for tracking macro definitions.
53 typedef std::vector<AsmToken> MCAsmMacroArgument;
54 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
56 struct MCAsmMacroParameter {
58 MCAsmMacroArgument Value;
62 MCAsmMacroParameter() : Required(false), Vararg(false) {}
65 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
70 MCAsmMacroParameters Parameters;
73 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
74 : Name(N), Body(B), Parameters(std::move(P)) {}
77 /// \brief Helper class for storing information about an active macro
79 struct MacroInstantiation {
80 /// The location of the instantiation.
81 SMLoc InstantiationLoc;
83 /// The buffer where parsing should resume upon instantiation completion.
86 /// The location where parsing should resume upon instantiation completion.
89 /// The depth of TheCondStack at the start of the instantiation.
90 size_t CondStackDepth;
93 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
96 struct ParseStatementInfo {
97 /// \brief The parsed operands from the last parsed statement.
98 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
100 /// \brief The opcode from the last parsed instruction.
103 /// \brief Was there an error parsing the inline assembly?
106 SmallVectorImpl<AsmRewrite> *AsmRewrites;
108 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
109 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
110 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
113 /// \brief The concrete assembly parser instance.
114 class AsmParser : public MCAsmParser {
115 AsmParser(const AsmParser &) = delete;
116 void operator=(const AsmParser &) = delete;
121 const MCAsmInfo &MAI;
123 SourceMgr::DiagHandlerTy SavedDiagHandler;
124 void *SavedDiagContext;
125 std::unique_ptr<MCAsmParserExtension> PlatformParser;
127 /// This is the current buffer index we're lexing from as managed by the
128 /// SourceMgr object.
131 AsmCond TheCondState;
132 std::vector<AsmCond> TheCondStack;
134 /// \brief maps directive names to handler methods in parser
135 /// extensions. Extensions register themselves in this map by calling
136 /// addDirectiveHandler.
137 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
139 /// \brief Map of currently defined macros.
140 StringMap<MCAsmMacro> MacroMap;
142 /// \brief Stack of active macro instantiations.
143 std::vector<MacroInstantiation*> ActiveMacros;
145 /// \brief List of bodies of anonymous macros.
146 std::deque<MCAsmMacro> MacroLikeBodies;
148 /// Boolean tracking whether macro substitution is enabled.
149 unsigned MacrosEnabledFlag : 1;
151 /// \brief Keeps track of how many .macro's have been instantiated.
152 unsigned NumOfMacroInstantiations;
154 /// Flag tracking whether any errors have been encountered.
155 unsigned HadError : 1;
157 /// The values from the last parsed cpp hash file line comment if any.
158 StringRef CppHashFilename;
159 int64_t CppHashLineNumber;
162 /// When generating dwarf for assembly source files we need to calculate the
163 /// logical line number based on the last parsed cpp hash file line comment
164 /// and current line. Since this is slow and messes up the SourceMgr's
165 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
166 SMLoc LastQueryIDLoc;
167 unsigned LastQueryBuffer;
168 unsigned LastQueryLine;
170 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
171 unsigned AssemblerDialect;
173 /// \brief is Darwin compatibility enabled?
176 /// \brief Are we parsing ms-style inline assembly?
177 bool ParsingInlineAsm;
180 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
181 const MCAsmInfo &MAI);
182 ~AsmParser() override;
184 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
186 void addDirectiveHandler(StringRef Directive,
187 ExtensionDirectiveHandler Handler) override {
188 ExtensionDirectiveMap[Directive] = Handler;
191 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
192 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
196 /// @name MCAsmParser Interface
199 SourceMgr &getSourceManager() override { return SrcMgr; }
200 MCAsmLexer &getLexer() override { return Lexer; }
201 MCContext &getContext() override { return Ctx; }
202 MCStreamer &getStreamer() override { return Out; }
203 unsigned getAssemblerDialect() override {
204 if (AssemblerDialect == ~0U)
205 return MAI.getAssemblerDialect();
207 return AssemblerDialect;
209 void setAssemblerDialect(unsigned i) override {
210 AssemblerDialect = i;
213 void Note(SMLoc L, const Twine &Msg,
214 ArrayRef<SMRange> Ranges = None) override;
215 bool Warning(SMLoc L, const Twine &Msg,
216 ArrayRef<SMRange> Ranges = None) override;
217 bool Error(SMLoc L, const Twine &Msg,
218 ArrayRef<SMRange> Ranges = None) override;
220 const AsmToken &Lex() override;
222 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
223 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
225 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
226 unsigned &NumOutputs, unsigned &NumInputs,
227 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
228 SmallVectorImpl<std::string> &Constraints,
229 SmallVectorImpl<std::string> &Clobbers,
230 const MCInstrInfo *MII, const MCInstPrinter *IP,
231 MCAsmParserSemaCallback &SI) override;
233 bool parseExpression(const MCExpr *&Res);
234 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
235 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
236 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
237 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
238 SMLoc &EndLoc) override;
239 bool parseAbsoluteExpression(int64_t &Res) override;
241 /// \brief Parse an identifier or string (as a quoted identifier)
242 /// and set \p Res to the identifier contents.
243 bool parseIdentifier(StringRef &Res) override;
244 void eatToEndOfStatement() override;
246 void checkForValidSection() override;
251 bool parseStatement(ParseStatementInfo &Info,
252 MCAsmParserSemaCallback *SI);
253 void eatToEndOfLine();
254 bool parseCppHashLineFilenameComment(const SMLoc &L);
256 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
257 ArrayRef<MCAsmMacroParameter> Parameters);
258 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
259 ArrayRef<MCAsmMacroParameter> Parameters,
260 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
263 /// \brief Are macros enabled in the parser?
264 bool areMacrosEnabled() {return MacrosEnabledFlag;}
266 /// \brief Control a flag in the parser that enables or disables macros.
267 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
269 /// \brief Lookup a previously defined macro.
270 /// \param Name Macro name.
271 /// \returns Pointer to macro. NULL if no such macro was defined.
272 const MCAsmMacro* lookupMacro(StringRef Name);
274 /// \brief Define a new macro with the given name and information.
275 void defineMacro(StringRef Name, MCAsmMacro Macro);
277 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
278 void undefineMacro(StringRef Name);
280 /// \brief Are we inside a macro instantiation?
281 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
283 /// \brief Handle entry to macro instantiation.
285 /// \param M The macro.
286 /// \param NameLoc Instantiation location.
287 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
289 /// \brief Handle exit from macro instantiation.
290 void handleMacroExit();
292 /// \brief Extract AsmTokens for a macro argument.
293 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
295 /// \brief Parse all macro arguments for a given macro.
296 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
298 void printMacroInstantiations();
299 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
300 ArrayRef<SMRange> Ranges = None) const {
301 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
303 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
305 /// \brief Enter the specified file. This returns true on failure.
306 bool enterIncludeFile(const std::string &Filename);
308 /// \brief Process the specified file for the .incbin directive.
309 /// This returns true on failure.
310 bool processIncbinFile(const std::string &Filename);
312 /// \brief Reset the current lexer position to that given by \p Loc. The
313 /// current token is not set; clients should ensure Lex() is called
316 /// \param InBuffer If not 0, should be the known buffer id that contains the
318 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
320 /// \brief Parse up to the end of statement and a return the contents from the
321 /// current token until the end of the statement; the current token on exit
322 /// will be either the EndOfStatement or EOF.
323 StringRef parseStringToEndOfStatement() override;
325 /// \brief Parse until the end of a statement or a comma is encountered,
326 /// return the contents from the current token up to the end or comma.
327 StringRef parseStringToComma();
329 bool parseAssignment(StringRef Name, bool allow_redef,
330 bool NoDeadStrip = false);
332 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
333 MCBinaryExpr::Opcode &Kind);
335 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
336 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
337 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
339 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
341 // Generic (target and platform independent) directive parsing.
343 DK_NO_DIRECTIVE, // Placeholder
344 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
345 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
346 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
347 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
348 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
349 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
350 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
351 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
352 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
353 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
354 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
355 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
356 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
357 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
358 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
359 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
360 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
361 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
362 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
363 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
364 DK_MACROS_ON, DK_MACROS_OFF,
365 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
366 DK_SLEB128, DK_ULEB128,
367 DK_ERR, DK_ERROR, DK_WARNING,
371 /// \brief Maps directive name --> DirectiveKind enum, for
372 /// directives parsed by this class.
373 StringMap<DirectiveKind> DirectiveKindMap;
375 // ".ascii", ".asciz", ".string"
376 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
377 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
378 bool parseDirectiveOctaValue(); // ".octa"
379 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
380 bool parseDirectiveFill(); // ".fill"
381 bool parseDirectiveZero(); // ".zero"
382 // ".set", ".equ", ".equiv"
383 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
384 bool parseDirectiveOrg(); // ".org"
385 // ".align{,32}", ".p2align{,w,l}"
386 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
388 // ".file", ".line", ".loc", ".stabs"
389 bool parseDirectiveFile(SMLoc DirectiveLoc);
390 bool parseDirectiveLine();
391 bool parseDirectiveLoc();
392 bool parseDirectiveStabs();
395 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
396 bool parseDirectiveCFIWindowSave();
397 bool parseDirectiveCFISections();
398 bool parseDirectiveCFIStartProc();
399 bool parseDirectiveCFIEndProc();
400 bool parseDirectiveCFIDefCfaOffset();
401 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIAdjustCfaOffset();
403 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
404 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
405 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
406 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
407 bool parseDirectiveCFIRememberState();
408 bool parseDirectiveCFIRestoreState();
409 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
410 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
411 bool parseDirectiveCFIEscape();
412 bool parseDirectiveCFISignalFrame();
413 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
416 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
417 bool parseDirectiveExitMacro(StringRef Directive);
418 bool parseDirectiveEndMacro(StringRef Directive);
419 bool parseDirectiveMacro(SMLoc DirectiveLoc);
420 bool parseDirectiveMacrosOnOff(StringRef Directive);
422 // ".bundle_align_mode"
423 bool parseDirectiveBundleAlignMode();
425 bool parseDirectiveBundleLock();
427 bool parseDirectiveBundleUnlock();
430 bool parseDirectiveSpace(StringRef IDVal);
432 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
433 bool parseDirectiveLEB128(bool Signed);
435 /// \brief Parse a directive like ".globl" which
436 /// accepts a single symbol (which should be a label or an external).
437 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
439 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
441 bool parseDirectiveAbort(); // ".abort"
442 bool parseDirectiveInclude(); // ".include"
443 bool parseDirectiveIncbin(); // ".incbin"
445 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
446 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
447 // ".ifb" or ".ifnb", depending on ExpectBlank.
448 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
449 // ".ifc" or ".ifnc", depending on ExpectEqual.
450 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
451 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
452 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
453 // ".ifdef" or ".ifndef", depending on expect_defined
454 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
455 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
456 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
457 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
458 bool parseEscapedString(std::string &Data) override;
460 const MCExpr *applyModifierToExpr(const MCExpr *E,
461 MCSymbolRefExpr::VariantKind Variant);
463 // Macro-like directives
464 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
465 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
466 raw_svector_ostream &OS);
467 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
468 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
469 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
470 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
472 // "_emit" or "__emit"
473 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
477 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
480 bool parseDirectiveEnd(SMLoc DirectiveLoc);
482 // ".err" or ".error"
483 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
486 bool parseDirectiveWarning(SMLoc DirectiveLoc);
488 void initializeDirectiveKindMap();
494 extern MCAsmParserExtension *createDarwinAsmParser();
495 extern MCAsmParserExtension *createELFAsmParser();
496 extern MCAsmParserExtension *createCOFFAsmParser();
500 enum { DEFAULT_ADDRSPACE = 0 };
502 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
503 const MCAsmInfo &MAI)
504 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
505 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
506 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
507 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
508 // Save the old handler.
509 SavedDiagHandler = SrcMgr.getDiagHandler();
510 SavedDiagContext = SrcMgr.getDiagContext();
511 // Set our own handler which calls the saved handler.
512 SrcMgr.setDiagHandler(DiagHandler, this);
513 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
515 // Initialize the platform / file format parser.
516 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
517 case MCObjectFileInfo::IsCOFF:
518 PlatformParser.reset(createCOFFAsmParser());
520 case MCObjectFileInfo::IsMachO:
521 PlatformParser.reset(createDarwinAsmParser());
524 case MCObjectFileInfo::IsELF:
525 PlatformParser.reset(createELFAsmParser());
529 PlatformParser->Initialize(*this);
530 initializeDirectiveKindMap();
532 NumOfMacroInstantiations = 0;
535 AsmParser::~AsmParser() {
536 assert((HadError || ActiveMacros.empty()) &&
537 "Unexpected active macro instantiation!");
540 void AsmParser::printMacroInstantiations() {
541 // Print the active macro instantiation stack.
542 for (std::vector<MacroInstantiation *>::const_reverse_iterator
543 it = ActiveMacros.rbegin(),
544 ie = ActiveMacros.rend();
546 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
547 "while in macro instantiation");
550 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
551 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
552 printMacroInstantiations();
555 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
556 if(getTargetParser().getTargetOptions().MCNoWarn)
558 if (getTargetParser().getTargetOptions().MCFatalWarnings)
559 return Error(L, Msg, Ranges);
560 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
561 printMacroInstantiations();
565 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
567 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
568 printMacroInstantiations();
572 bool AsmParser::enterIncludeFile(const std::string &Filename) {
573 std::string IncludedFile;
575 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
580 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
584 /// Process the specified .incbin file by searching for it in the include paths
585 /// then just emitting the byte contents of the file to the streamer. This
586 /// returns true on failure.
587 bool AsmParser::processIncbinFile(const std::string &Filename) {
588 std::string IncludedFile;
590 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
594 // Pick up the bytes from the file and emit them.
595 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
599 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
600 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
601 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
605 const AsmToken &AsmParser::Lex() {
606 const AsmToken *tok = &Lexer.Lex();
608 if (tok->is(AsmToken::Eof)) {
609 // If this is the end of an included file, pop the parent file off the
611 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
612 if (ParentIncludeLoc != SMLoc()) {
613 jumpToLoc(ParentIncludeLoc);
618 if (tok->is(AsmToken::Error))
619 Error(Lexer.getErrLoc(), Lexer.getErr());
624 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
625 // Create the initial section, if requested.
626 if (!NoInitialTextSection)
627 Out.InitSections(false);
633 AsmCond StartingCondState = TheCondState;
635 // If we are generating dwarf for assembly source files save the initial text
636 // section and generate a .file directive.
637 if (getContext().getGenDwarfForAssembly()) {
638 MCSection *Sec = getStreamer().getCurrentSection().first;
639 if (!Sec->getBeginSymbol()) {
640 MCSymbol *SectionStartSym = getContext().createTempSymbol();
641 getStreamer().EmitLabel(SectionStartSym);
642 Sec->setBeginSymbol(SectionStartSym);
644 bool InsertResult = getContext().addGenDwarfSection(Sec);
645 assert(InsertResult && ".text section should not have debug info yet");
647 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
648 0, StringRef(), getContext().getMainFileName()));
651 // While we have input, parse each statement.
652 while (Lexer.isNot(AsmToken::Eof)) {
653 ParseStatementInfo Info;
654 if (!parseStatement(Info, nullptr))
657 // We had an error, validate that one was emitted and recover by skipping to
659 assert(HadError && "Parse statement returned an error, but none emitted!");
660 eatToEndOfStatement();
663 if (TheCondState.TheCond != StartingCondState.TheCond ||
664 TheCondState.Ignore != StartingCondState.Ignore)
665 return TokError("unmatched .ifs or .elses");
667 // Check to see there are no empty DwarfFile slots.
668 const auto &LineTables = getContext().getMCDwarfLineTables();
669 if (!LineTables.empty()) {
671 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
672 if (File.Name.empty() && Index != 0)
673 TokError("unassigned file number: " + Twine(Index) +
674 " for .file directives");
679 // Check to see that all assembler local symbols were actually defined.
680 // Targets that don't do subsections via symbols may not want this, though,
681 // so conservatively exclude them. Only do this if we're finalizing, though,
682 // as otherwise we won't necessarilly have seen everything yet.
683 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
684 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
685 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
688 MCSymbol *Sym = i->getValue();
689 // Variable symbols may not be marked as defined, so check those
690 // explicitly. If we know it's a variable, we have a definition for
691 // the purposes of this check.
692 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
693 // FIXME: We would really like to refer back to where the symbol was
694 // first referenced for a source location. We need to add something
695 // to track that. Currently, we just point to the end of the file.
696 printMessage(getLexer().getLoc(), SourceMgr::DK_Error,
697 "assembler local symbol '" + Sym->getName() +
702 // Finalize the output stream if there are no errors and if the client wants
704 if (!HadError && !NoFinalize)
710 void AsmParser::checkForValidSection() {
711 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
712 TokError("expected section directive before assembly directive");
713 Out.InitSections(false);
717 /// \brief Throw away the rest of the line for testing purposes.
718 void AsmParser::eatToEndOfStatement() {
719 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
723 if (Lexer.is(AsmToken::EndOfStatement))
727 StringRef AsmParser::parseStringToEndOfStatement() {
728 const char *Start = getTok().getLoc().getPointer();
730 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
733 const char *End = getTok().getLoc().getPointer();
734 return StringRef(Start, End - Start);
737 StringRef AsmParser::parseStringToComma() {
738 const char *Start = getTok().getLoc().getPointer();
740 while (Lexer.isNot(AsmToken::EndOfStatement) &&
741 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
744 const char *End = getTok().getLoc().getPointer();
745 return StringRef(Start, End - Start);
748 /// \brief Parse a paren expression and return it.
749 /// NOTE: This assumes the leading '(' has already been consumed.
751 /// parenexpr ::= expr)
753 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
754 if (parseExpression(Res))
756 if (Lexer.isNot(AsmToken::RParen))
757 return TokError("expected ')' in parentheses expression");
758 EndLoc = Lexer.getTok().getEndLoc();
763 /// \brief Parse a bracket expression and return it.
764 /// NOTE: This assumes the leading '[' has already been consumed.
766 /// bracketexpr ::= expr]
768 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
769 if (parseExpression(Res))
771 if (Lexer.isNot(AsmToken::RBrac))
772 return TokError("expected ']' in brackets expression");
773 EndLoc = Lexer.getTok().getEndLoc();
778 /// \brief Parse a primary expression and return it.
779 /// primaryexpr ::= (parenexpr
780 /// primaryexpr ::= symbol
781 /// primaryexpr ::= number
782 /// primaryexpr ::= '.'
783 /// primaryexpr ::= ~,+,- primaryexpr
784 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
785 SMLoc FirstTokenLoc = getLexer().getLoc();
786 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
787 switch (FirstTokenKind) {
789 return TokError("unknown token in expression");
790 // If we have an error assume that we've already handled it.
791 case AsmToken::Error:
793 case AsmToken::Exclaim:
794 Lex(); // Eat the operator.
795 if (parsePrimaryExpr(Res, EndLoc))
797 Res = MCUnaryExpr::createLNot(Res, getContext());
799 case AsmToken::Dollar:
801 case AsmToken::String:
802 case AsmToken::Identifier: {
803 StringRef Identifier;
804 if (parseIdentifier(Identifier)) {
805 if (FirstTokenKind == AsmToken::Dollar) {
806 if (Lexer.getMAI().getDollarIsPC()) {
807 // This is a '$' reference, which references the current PC. Emit a
808 // temporary label to the streamer and refer to it.
809 MCSymbol *Sym = Ctx.createTempSymbol();
811 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
813 EndLoc = FirstTokenLoc;
816 return Error(FirstTokenLoc, "invalid token in expression");
819 // Parse symbol variant
820 std::pair<StringRef, StringRef> Split;
821 if (!MAI.useParensForSymbolVariant()) {
822 if (FirstTokenKind == AsmToken::String) {
823 if (Lexer.is(AsmToken::At)) {
824 Lexer.Lex(); // eat @
825 SMLoc AtLoc = getLexer().getLoc();
827 if (parseIdentifier(VName))
828 return Error(AtLoc, "expected symbol variant after '@'");
830 Split = std::make_pair(Identifier, VName);
833 Split = Identifier.split('@');
835 } else if (Lexer.is(AsmToken::LParen)) {
836 Lexer.Lex(); // eat (
838 parseIdentifier(VName);
839 if (Lexer.isNot(AsmToken::RParen)) {
840 return Error(Lexer.getTok().getLoc(),
841 "unexpected token in variant, expected ')'");
843 Lexer.Lex(); // eat )
844 Split = std::make_pair(Identifier, VName);
847 EndLoc = SMLoc::getFromPointer(Identifier.end());
849 // This is a symbol reference.
850 StringRef SymbolName = Identifier;
851 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
853 // Lookup the symbol variant if used.
854 if (Split.second.size()) {
855 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
856 if (Variant != MCSymbolRefExpr::VK_Invalid) {
857 SymbolName = Split.first;
858 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
859 Variant = MCSymbolRefExpr::VK_None;
861 return Error(SMLoc::getFromPointer(Split.second.begin()),
862 "invalid variant '" + Split.second + "'");
866 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
868 // If this is an absolute variable reference, substitute it now to preserve
869 // semantics in the face of reassignment.
870 if (Sym->isVariable() &&
871 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
873 return Error(EndLoc, "unexpected modifier on variable reference");
875 Res = Sym->getVariableValue(/*SetUsed*/ false);
879 // Otherwise create a symbol ref.
880 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
883 case AsmToken::BigNum:
884 return TokError("literal value out of range for directive");
885 case AsmToken::Integer: {
886 SMLoc Loc = getTok().getLoc();
887 int64_t IntVal = getTok().getIntVal();
888 Res = MCConstantExpr::create(IntVal, getContext());
889 EndLoc = Lexer.getTok().getEndLoc();
891 // Look for 'b' or 'f' following an Integer as a directional label
892 if (Lexer.getKind() == AsmToken::Identifier) {
893 StringRef IDVal = getTok().getString();
894 // Lookup the symbol variant if used.
895 std::pair<StringRef, StringRef> Split = IDVal.split('@');
896 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
897 if (Split.first.size() != IDVal.size()) {
898 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
899 if (Variant == MCSymbolRefExpr::VK_Invalid)
900 return TokError("invalid variant '" + Split.second + "'");
903 if (IDVal == "f" || IDVal == "b") {
905 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
906 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
907 if (IDVal == "b" && Sym->isUndefined())
908 return Error(Loc, "invalid reference to undefined symbol");
909 EndLoc = Lexer.getTok().getEndLoc();
910 Lex(); // Eat identifier.
915 case AsmToken::Real: {
916 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
917 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
918 Res = MCConstantExpr::create(IntVal, getContext());
919 EndLoc = Lexer.getTok().getEndLoc();
923 case AsmToken::Dot: {
924 // This is a '.' reference, which references the current PC. Emit a
925 // temporary label to the streamer and refer to it.
926 MCSymbol *Sym = Ctx.createTempSymbol();
928 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
929 EndLoc = Lexer.getTok().getEndLoc();
930 Lex(); // Eat identifier.
933 case AsmToken::LParen:
934 Lex(); // Eat the '('.
935 return parseParenExpr(Res, EndLoc);
936 case AsmToken::LBrac:
937 if (!PlatformParser->HasBracketExpressions())
938 return TokError("brackets expression not supported on this target");
939 Lex(); // Eat the '['.
940 return parseBracketExpr(Res, EndLoc);
941 case AsmToken::Minus:
942 Lex(); // Eat the operator.
943 if (parsePrimaryExpr(Res, EndLoc))
945 Res = MCUnaryExpr::createMinus(Res, getContext());
948 Lex(); // Eat the operator.
949 if (parsePrimaryExpr(Res, EndLoc))
951 Res = MCUnaryExpr::createPlus(Res, getContext());
953 case AsmToken::Tilde:
954 Lex(); // Eat the operator.
955 if (parsePrimaryExpr(Res, EndLoc))
957 Res = MCUnaryExpr::createNot(Res, getContext());
962 bool AsmParser::parseExpression(const MCExpr *&Res) {
964 return parseExpression(Res, EndLoc);
968 AsmParser::applyModifierToExpr(const MCExpr *E,
969 MCSymbolRefExpr::VariantKind Variant) {
970 // Ask the target implementation about this expression first.
971 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
974 // Recurse over the given expression, rebuilding it to apply the given variant
975 // if there is exactly one symbol.
976 switch (E->getKind()) {
978 case MCExpr::Constant:
981 case MCExpr::SymbolRef: {
982 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
984 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
985 TokError("invalid variant on expression '" + getTok().getIdentifier() +
986 "' (already modified)");
990 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
993 case MCExpr::Unary: {
994 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
995 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
998 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
1001 case MCExpr::Binary: {
1002 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1003 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1004 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1014 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1018 llvm_unreachable("Invalid expression kind!");
1021 /// \brief Parse an expression and return it.
1023 /// expr ::= expr &&,|| expr -> lowest.
1024 /// expr ::= expr |,^,&,! expr
1025 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1026 /// expr ::= expr <<,>> expr
1027 /// expr ::= expr +,- expr
1028 /// expr ::= expr *,/,% expr -> highest.
1029 /// expr ::= primaryexpr
1031 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1032 // Parse the expression.
1034 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1037 // As a special case, we support 'a op b @ modifier' by rewriting the
1038 // expression to include the modifier. This is inefficient, but in general we
1039 // expect users to use 'a@modifier op b'.
1040 if (Lexer.getKind() == AsmToken::At) {
1043 if (Lexer.isNot(AsmToken::Identifier))
1044 return TokError("unexpected symbol modifier following '@'");
1046 MCSymbolRefExpr::VariantKind Variant =
1047 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1048 if (Variant == MCSymbolRefExpr::VK_Invalid)
1049 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1051 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1053 return TokError("invalid modifier '" + getTok().getIdentifier() +
1054 "' (no symbols present)");
1061 // Try to constant fold it up front, if possible.
1063 if (Res->evaluateAsAbsolute(Value))
1064 Res = MCConstantExpr::create(Value, getContext());
1069 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1071 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1074 bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1076 if (parseParenExpr(Res, EndLoc))
1079 for (; ParenDepth > 0; --ParenDepth) {
1080 if (parseBinOpRHS(1, Res, EndLoc))
1083 // We don't Lex() the last RParen.
1084 // This is the same behavior as parseParenExpression().
1085 if (ParenDepth - 1 > 0) {
1086 if (Lexer.isNot(AsmToken::RParen))
1087 return TokError("expected ')' in parentheses expression");
1088 EndLoc = Lexer.getTok().getEndLoc();
1095 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1098 SMLoc StartLoc = Lexer.getLoc();
1099 if (parseExpression(Expr))
1102 if (!Expr->evaluateAsAbsolute(Res))
1103 return Error(StartLoc, "expected absolute expression");
1108 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1109 MCBinaryExpr::Opcode &Kind) {
1112 return 0; // not a binop.
1114 // Lowest Precedence: &&, ||
1115 case AsmToken::AmpAmp:
1116 Kind = MCBinaryExpr::LAnd;
1118 case AsmToken::PipePipe:
1119 Kind = MCBinaryExpr::LOr;
1122 // Low Precedence: |, &, ^
1124 // FIXME: gas seems to support '!' as an infix operator?
1125 case AsmToken::Pipe:
1126 Kind = MCBinaryExpr::Or;
1128 case AsmToken::Caret:
1129 Kind = MCBinaryExpr::Xor;
1132 Kind = MCBinaryExpr::And;
1135 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1136 case AsmToken::EqualEqual:
1137 Kind = MCBinaryExpr::EQ;
1139 case AsmToken::ExclaimEqual:
1140 case AsmToken::LessGreater:
1141 Kind = MCBinaryExpr::NE;
1143 case AsmToken::Less:
1144 Kind = MCBinaryExpr::LT;
1146 case AsmToken::LessEqual:
1147 Kind = MCBinaryExpr::LTE;
1149 case AsmToken::Greater:
1150 Kind = MCBinaryExpr::GT;
1152 case AsmToken::GreaterEqual:
1153 Kind = MCBinaryExpr::GTE;
1156 // Intermediate Precedence: <<, >>
1157 case AsmToken::LessLess:
1158 Kind = MCBinaryExpr::Shl;
1160 case AsmToken::GreaterGreater:
1161 Kind = MAI.shouldUseLogicalShr() ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1164 // High Intermediate Precedence: +, -
1165 case AsmToken::Plus:
1166 Kind = MCBinaryExpr::Add;
1168 case AsmToken::Minus:
1169 Kind = MCBinaryExpr::Sub;
1172 // Highest Precedence: *, /, %
1173 case AsmToken::Star:
1174 Kind = MCBinaryExpr::Mul;
1176 case AsmToken::Slash:
1177 Kind = MCBinaryExpr::Div;
1179 case AsmToken::Percent:
1180 Kind = MCBinaryExpr::Mod;
1185 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1186 /// Res contains the LHS of the expression on input.
1187 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1190 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1191 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1193 // If the next token is lower precedence than we are allowed to eat, return
1194 // successfully with what we ate already.
1195 if (TokPrec < Precedence)
1200 // Eat the next primary expression.
1202 if (parsePrimaryExpr(RHS, EndLoc))
1205 // If BinOp binds less tightly with RHS than the operator after RHS, let
1206 // the pending operator take RHS as its LHS.
1207 MCBinaryExpr::Opcode Dummy;
1208 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1209 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1212 // Merge LHS and RHS according to operator.
1213 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
1218 /// ::= EndOfStatement
1219 /// ::= Label* Directive ...Operands... EndOfStatement
1220 /// ::= Label* Identifier OperandList* EndOfStatement
1221 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1222 MCAsmParserSemaCallback *SI) {
1223 if (Lexer.is(AsmToken::EndOfStatement)) {
1229 // Statements always start with an identifier or are a full line comment.
1230 AsmToken ID = getTok();
1231 SMLoc IDLoc = ID.getLoc();
1233 int64_t LocalLabelVal = -1;
1234 // A full line comment is a '#' as the first token.
1235 if (Lexer.is(AsmToken::Hash))
1236 return parseCppHashLineFilenameComment(IDLoc);
1238 // Allow an integer followed by a ':' as a directional local label.
1239 if (Lexer.is(AsmToken::Integer)) {
1240 LocalLabelVal = getTok().getIntVal();
1241 if (LocalLabelVal < 0) {
1242 if (!TheCondState.Ignore)
1243 return TokError("unexpected token at start of statement");
1246 IDVal = getTok().getString();
1247 Lex(); // Consume the integer token to be used as an identifier token.
1248 if (Lexer.getKind() != AsmToken::Colon) {
1249 if (!TheCondState.Ignore)
1250 return TokError("unexpected token at start of statement");
1253 } else if (Lexer.is(AsmToken::Dot)) {
1254 // Treat '.' as a valid identifier in this context.
1257 } else if (parseIdentifier(IDVal)) {
1258 if (!TheCondState.Ignore)
1259 return TokError("unexpected token at start of statement");
1263 // Handle conditional assembly here before checking for skipping. We
1264 // have to do this so that .endif isn't skipped in a ".if 0" block for
1266 StringMap<DirectiveKind>::const_iterator DirKindIt =
1267 DirectiveKindMap.find(IDVal);
1268 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1270 : DirKindIt->getValue();
1281 return parseDirectiveIf(IDLoc, DirKind);
1283 return parseDirectiveIfb(IDLoc, true);
1285 return parseDirectiveIfb(IDLoc, false);
1287 return parseDirectiveIfc(IDLoc, true);
1289 return parseDirectiveIfeqs(IDLoc, true);
1291 return parseDirectiveIfc(IDLoc, false);
1293 return parseDirectiveIfeqs(IDLoc, false);
1295 return parseDirectiveIfdef(IDLoc, true);
1298 return parseDirectiveIfdef(IDLoc, false);
1300 return parseDirectiveElseIf(IDLoc);
1302 return parseDirectiveElse(IDLoc);
1304 return parseDirectiveEndIf(IDLoc);
1307 // Ignore the statement if in the middle of inactive conditional
1309 if (TheCondState.Ignore) {
1310 eatToEndOfStatement();
1314 // FIXME: Recurse on local labels?
1316 // See what kind of statement we have.
1317 switch (Lexer.getKind()) {
1318 case AsmToken::Colon: {
1319 checkForValidSection();
1321 // identifier ':' -> Label.
1324 // Diagnose attempt to use '.' as a label.
1326 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1328 // Diagnose attempt to use a variable as a label.
1330 // FIXME: Diagnostics. Note the location of the definition as a label.
1331 // FIXME: This doesn't diagnose assignment to a symbol which has been
1332 // implicitly marked as external.
1334 if (LocalLabelVal == -1) {
1335 if (ParsingInlineAsm && SI) {
1336 StringRef RewrittenLabel =
1337 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1338 assert(RewrittenLabel.size() &&
1339 "We should have an internal name here.");
1340 Info.AsmRewrites->push_back(AsmRewrite(AOK_Label, IDLoc,
1341 IDVal.size(), RewrittenLabel));
1342 IDVal = RewrittenLabel;
1344 Sym = getContext().getOrCreateSymbol(IDVal);
1346 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1348 Sym->redefineIfPossible();
1350 if (!Sym->isUndefined() || Sym->isVariable())
1351 return Error(IDLoc, "invalid symbol redefinition");
1354 if (!ParsingInlineAsm)
1357 // If we are generating dwarf for assembly source files then gather the
1358 // info to make a dwarf label entry for this label if needed.
1359 if (getContext().getGenDwarfForAssembly())
1360 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1363 getTargetParser().onLabelParsed(Sym);
1365 // Consume any end of statement token, if present, to avoid spurious
1366 // AddBlankLine calls().
1367 if (Lexer.is(AsmToken::EndOfStatement)) {
1369 if (Lexer.is(AsmToken::Eof))
1376 case AsmToken::Equal:
1377 // identifier '=' ... -> assignment statement
1380 return parseAssignment(IDVal, true);
1382 default: // Normal instruction or directive.
1386 // If macros are enabled, check to see if this is a macro instantiation.
1387 if (areMacrosEnabled())
1388 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1389 return handleMacroEntry(M, IDLoc);
1392 // Otherwise, we have a normal instruction or directive.
1394 // Directives start with "."
1395 if (IDVal[0] == '.' && IDVal != ".") {
1396 // There are several entities interested in parsing directives:
1398 // 1. The target-specific assembly parser. Some directives are target
1399 // specific or may potentially behave differently on certain targets.
1400 // 2. Asm parser extensions. For example, platform-specific parsers
1401 // (like the ELF parser) register themselves as extensions.
1402 // 3. The generic directive parser implemented by this class. These are
1403 // all the directives that behave in a target and platform independent
1404 // manner, or at least have a default behavior that's shared between
1405 // all targets and platforms.
1407 // First query the target-specific parser. It will return 'true' if it
1408 // isn't interested in this directive.
1409 if (!getTargetParser().ParseDirective(ID))
1412 // Next, check the extension directive map to see if any extension has
1413 // registered itself to parse this directive.
1414 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1415 ExtensionDirectiveMap.lookup(IDVal);
1417 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1419 // Finally, if no one else is interested in this directive, it must be
1420 // generic and familiar to this class.
1426 return parseDirectiveSet(IDVal, true);
1428 return parseDirectiveSet(IDVal, false);
1430 return parseDirectiveAscii(IDVal, false);
1433 return parseDirectiveAscii(IDVal, true);
1435 return parseDirectiveValue(1);
1439 return parseDirectiveValue(2);
1443 return parseDirectiveValue(4);
1446 return parseDirectiveValue(8);
1448 return parseDirectiveOctaValue();
1451 return parseDirectiveRealValue(APFloat::IEEEsingle);
1453 return parseDirectiveRealValue(APFloat::IEEEdouble);
1455 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1456 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1459 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1460 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1463 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1465 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1467 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1469 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1471 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1473 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1475 return parseDirectiveOrg();
1477 return parseDirectiveFill();
1479 return parseDirectiveZero();
1481 eatToEndOfStatement(); // .extern is the default, ignore it.
1485 return parseDirectiveSymbolAttribute(MCSA_Global);
1486 case DK_LAZY_REFERENCE:
1487 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1488 case DK_NO_DEAD_STRIP:
1489 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1490 case DK_SYMBOL_RESOLVER:
1491 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1492 case DK_PRIVATE_EXTERN:
1493 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1495 return parseDirectiveSymbolAttribute(MCSA_Reference);
1496 case DK_WEAK_DEFINITION:
1497 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1498 case DK_WEAK_REFERENCE:
1499 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1500 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1501 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1504 return parseDirectiveComm(/*IsLocal=*/false);
1506 return parseDirectiveComm(/*IsLocal=*/true);
1508 return parseDirectiveAbort();
1510 return parseDirectiveInclude();
1512 return parseDirectiveIncbin();
1515 return TokError(Twine(IDVal) + " not supported yet");
1517 return parseDirectiveRept(IDLoc, IDVal);
1519 return parseDirectiveIrp(IDLoc);
1521 return parseDirectiveIrpc(IDLoc);
1523 return parseDirectiveEndr(IDLoc);
1524 case DK_BUNDLE_ALIGN_MODE:
1525 return parseDirectiveBundleAlignMode();
1526 case DK_BUNDLE_LOCK:
1527 return parseDirectiveBundleLock();
1528 case DK_BUNDLE_UNLOCK:
1529 return parseDirectiveBundleUnlock();
1531 return parseDirectiveLEB128(true);
1533 return parseDirectiveLEB128(false);
1536 return parseDirectiveSpace(IDVal);
1538 return parseDirectiveFile(IDLoc);
1540 return parseDirectiveLine();
1542 return parseDirectiveLoc();
1544 return parseDirectiveStabs();
1545 case DK_CFI_SECTIONS:
1546 return parseDirectiveCFISections();
1547 case DK_CFI_STARTPROC:
1548 return parseDirectiveCFIStartProc();
1549 case DK_CFI_ENDPROC:
1550 return parseDirectiveCFIEndProc();
1551 case DK_CFI_DEF_CFA:
1552 return parseDirectiveCFIDefCfa(IDLoc);
1553 case DK_CFI_DEF_CFA_OFFSET:
1554 return parseDirectiveCFIDefCfaOffset();
1555 case DK_CFI_ADJUST_CFA_OFFSET:
1556 return parseDirectiveCFIAdjustCfaOffset();
1557 case DK_CFI_DEF_CFA_REGISTER:
1558 return parseDirectiveCFIDefCfaRegister(IDLoc);
1560 return parseDirectiveCFIOffset(IDLoc);
1561 case DK_CFI_REL_OFFSET:
1562 return parseDirectiveCFIRelOffset(IDLoc);
1563 case DK_CFI_PERSONALITY:
1564 return parseDirectiveCFIPersonalityOrLsda(true);
1566 return parseDirectiveCFIPersonalityOrLsda(false);
1567 case DK_CFI_REMEMBER_STATE:
1568 return parseDirectiveCFIRememberState();
1569 case DK_CFI_RESTORE_STATE:
1570 return parseDirectiveCFIRestoreState();
1571 case DK_CFI_SAME_VALUE:
1572 return parseDirectiveCFISameValue(IDLoc);
1573 case DK_CFI_RESTORE:
1574 return parseDirectiveCFIRestore(IDLoc);
1576 return parseDirectiveCFIEscape();
1577 case DK_CFI_SIGNAL_FRAME:
1578 return parseDirectiveCFISignalFrame();
1579 case DK_CFI_UNDEFINED:
1580 return parseDirectiveCFIUndefined(IDLoc);
1581 case DK_CFI_REGISTER:
1582 return parseDirectiveCFIRegister(IDLoc);
1583 case DK_CFI_WINDOW_SAVE:
1584 return parseDirectiveCFIWindowSave();
1587 return parseDirectiveMacrosOnOff(IDVal);
1589 return parseDirectiveMacro(IDLoc);
1591 return parseDirectiveExitMacro(IDVal);
1594 return parseDirectiveEndMacro(IDVal);
1596 return parseDirectivePurgeMacro(IDLoc);
1598 return parseDirectiveEnd(IDLoc);
1600 return parseDirectiveError(IDLoc, false);
1602 return parseDirectiveError(IDLoc, true);
1604 return parseDirectiveWarning(IDLoc);
1607 return Error(IDLoc, "unknown directive");
1610 // __asm _emit or __asm __emit
1611 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1612 IDVal == "_EMIT" || IDVal == "__EMIT"))
1613 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1616 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1617 return parseDirectiveMSAlign(IDLoc, Info);
1619 checkForValidSection();
1621 // Canonicalize the opcode to lower case.
1622 std::string OpcodeStr = IDVal.lower();
1623 ParseInstructionInfo IInfo(Info.AsmRewrites);
1624 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1625 Info.ParsedOperands);
1626 Info.ParseError = HadError;
1628 // Dump the parsed representation, if requested.
1629 if (getShowParsedOperands()) {
1630 SmallString<256> Str;
1631 raw_svector_ostream OS(Str);
1632 OS << "parsed instruction: [";
1633 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1636 Info.ParsedOperands[i]->print(OS);
1640 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1643 // If we are generating dwarf for the current section then generate a .loc
1644 // directive for the instruction.
1645 if (!HadError && getContext().getGenDwarfForAssembly() &&
1646 getContext().getGenDwarfSectionSyms().count(
1647 getStreamer().getCurrentSection().first)) {
1649 if (ActiveMacros.empty())
1650 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1652 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
1653 ActiveMacros.front()->ExitBuffer);
1655 // If we previously parsed a cpp hash file line comment then make sure the
1656 // current Dwarf File is for the CppHashFilename if not then emit the
1657 // Dwarf File table for it and adjust the line number for the .loc.
1658 if (CppHashFilename.size()) {
1659 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1660 0, StringRef(), CppHashFilename);
1661 getContext().setGenDwarfFileNumber(FileNumber);
1663 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1664 // cache with the different Loc from the call above we save the last
1665 // info we queried here with SrcMgr.FindLineNumber().
1666 unsigned CppHashLocLineNo;
1667 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1668 CppHashLocLineNo = LastQueryLine;
1670 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1671 LastQueryLine = CppHashLocLineNo;
1672 LastQueryIDLoc = CppHashLoc;
1673 LastQueryBuffer = CppHashBuf;
1675 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1678 getStreamer().EmitDwarfLocDirective(
1679 getContext().getGenDwarfFileNumber(), Line, 0,
1680 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1684 // If parsing succeeded, match the instruction.
1687 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1688 Info.ParsedOperands, Out,
1689 ErrorInfo, ParsingInlineAsm);
1692 // Don't skip the rest of the line, the instruction parser is responsible for
1697 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1698 /// since they may not be able to be tokenized to get to the end of line token.
1699 void AsmParser::eatToEndOfLine() {
1700 if (!Lexer.is(AsmToken::EndOfStatement))
1701 Lexer.LexUntilEndOfLine();
1706 /// parseCppHashLineFilenameComment as this:
1707 /// ::= # number "filename"
1708 /// or just as a full line comment if it doesn't have a number and a string.
1709 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1710 Lex(); // Eat the hash token.
1712 if (getLexer().isNot(AsmToken::Integer)) {
1713 // Consume the line since in cases it is not a well-formed line directive,
1714 // as if were simply a full line comment.
1719 int64_t LineNumber = getTok().getIntVal();
1722 if (getLexer().isNot(AsmToken::String)) {
1727 StringRef Filename = getTok().getString();
1728 // Get rid of the enclosing quotes.
1729 Filename = Filename.substr(1, Filename.size() - 2);
1731 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1733 CppHashFilename = Filename;
1734 CppHashLineNumber = LineNumber;
1735 CppHashBuf = CurBuffer;
1737 // Ignore any trailing characters, they're just comment.
1742 /// \brief will use the last parsed cpp hash line filename comment
1743 /// for the Filename and LineNo if any in the diagnostic.
1744 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1745 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1746 raw_ostream &OS = errs();
1748 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1749 const SMLoc &DiagLoc = Diag.getLoc();
1750 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1751 unsigned CppHashBuf =
1752 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1754 // Like SourceMgr::printMessage() we need to print the include stack if any
1755 // before printing the message.
1756 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1757 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1758 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
1759 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1760 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1763 // If we have not parsed a cpp hash line filename comment or the source
1764 // manager changed or buffer changed (like in a nested include) then just
1765 // print the normal diagnostic using its Filename and LineNo.
1766 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1767 DiagBuf != CppHashBuf) {
1768 if (Parser->SavedDiagHandler)
1769 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1771 Diag.print(nullptr, OS);
1775 // Use the CppHashFilename and calculate a line number based on the
1776 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1778 const std::string &Filename = Parser->CppHashFilename;
1780 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1781 int CppHashLocLineNo =
1782 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1784 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1786 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1787 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1788 Diag.getLineContents(), Diag.getRanges());
1790 if (Parser->SavedDiagHandler)
1791 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1793 NewDiag.print(nullptr, OS);
1796 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1797 // difference being that that function accepts '@' as part of identifiers and
1798 // we can't do that. AsmLexer.cpp should probably be changed to handle
1799 // '@' as a special case when needed.
1800 static bool isIdentifierChar(char c) {
1801 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1805 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1806 ArrayRef<MCAsmMacroParameter> Parameters,
1807 ArrayRef<MCAsmMacroArgument> A,
1808 bool EnableAtPseudoVariable, const SMLoc &L) {
1809 unsigned NParameters = Parameters.size();
1810 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1811 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1812 return Error(L, "Wrong number of arguments");
1814 // A macro without parameters is handled differently on Darwin:
1815 // gas accepts no arguments and does no substitutions
1816 while (!Body.empty()) {
1817 // Scan for the next substitution.
1818 std::size_t End = Body.size(), Pos = 0;
1819 for (; Pos != End; ++Pos) {
1820 // Check for a substitution or escape.
1821 if (IsDarwin && !NParameters) {
1822 // This macro has no parameters, look for $0, $1, etc.
1823 if (Body[Pos] != '$' || Pos + 1 == End)
1826 char Next = Body[Pos + 1];
1827 if (Next == '$' || Next == 'n' ||
1828 isdigit(static_cast<unsigned char>(Next)))
1831 // This macro has parameters, look for \foo, \bar, etc.
1832 if (Body[Pos] == '\\' && Pos + 1 != End)
1838 OS << Body.slice(0, Pos);
1840 // Check if we reached the end.
1844 if (IsDarwin && !NParameters) {
1845 switch (Body[Pos + 1]) {
1851 // $n => number of arguments
1856 // $[0-9] => argument
1858 // Missing arguments are ignored.
1859 unsigned Index = Body[Pos + 1] - '0';
1860 if (Index >= A.size())
1863 // Otherwise substitute with the token values, with spaces eliminated.
1864 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1865 ie = A[Index].end();
1867 OS << it->getString();
1873 unsigned I = Pos + 1;
1875 // Check for the \@ pseudo-variable.
1876 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
1879 while (isIdentifierChar(Body[I]) && I + 1 != End)
1882 const char *Begin = Body.data() + Pos + 1;
1883 StringRef Argument(Begin, I - (Pos + 1));
1886 if (Argument == "@") {
1887 OS << NumOfMacroInstantiations;
1890 for (; Index < NParameters; ++Index)
1891 if (Parameters[Index].Name == Argument)
1894 if (Index == NParameters) {
1895 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1898 OS << '\\' << Argument;
1902 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1903 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1904 ie = A[Index].end();
1906 // We expect no quotes around the string's contents when
1907 // parsing for varargs.
1908 if (it->getKind() != AsmToken::String || VarargParameter)
1909 OS << it->getString();
1911 OS << it->getStringContents();
1913 Pos += 1 + Argument.size();
1917 // Update the scan point.
1918 Body = Body.substr(Pos);
1924 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
1925 size_t CondStackDepth)
1926 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
1927 CondStackDepth(CondStackDepth) {}
1929 static bool isOperator(AsmToken::TokenKind kind) {
1933 case AsmToken::Plus:
1934 case AsmToken::Minus:
1935 case AsmToken::Tilde:
1936 case AsmToken::Slash:
1937 case AsmToken::Star:
1939 case AsmToken::Equal:
1940 case AsmToken::EqualEqual:
1941 case AsmToken::Pipe:
1942 case AsmToken::PipePipe:
1943 case AsmToken::Caret:
1945 case AsmToken::AmpAmp:
1946 case AsmToken::Exclaim:
1947 case AsmToken::ExclaimEqual:
1948 case AsmToken::Percent:
1949 case AsmToken::Less:
1950 case AsmToken::LessEqual:
1951 case AsmToken::LessLess:
1952 case AsmToken::LessGreater:
1953 case AsmToken::Greater:
1954 case AsmToken::GreaterEqual:
1955 case AsmToken::GreaterGreater:
1961 class AsmLexerSkipSpaceRAII {
1963 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1964 Lexer.setSkipSpace(SkipSpace);
1967 ~AsmLexerSkipSpaceRAII() {
1968 Lexer.setSkipSpace(true);
1976 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1979 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1980 StringRef Str = parseStringToEndOfStatement();
1981 MA.emplace_back(AsmToken::String, Str);
1986 unsigned ParenLevel = 0;
1987 unsigned AddTokens = 0;
1989 // Darwin doesn't use spaces to delmit arguments.
1990 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1993 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1994 return TokError("unexpected token in macro instantiation");
1996 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1999 if (Lexer.is(AsmToken::Space)) {
2000 Lex(); // Eat spaces
2002 // Spaces can delimit parameters, but could also be part an expression.
2003 // If the token after a space is an operator, add the token and the next
2004 // one into this argument
2006 if (isOperator(Lexer.getKind())) {
2007 // Check to see whether the token is used as an operator,
2008 // or part of an identifier
2009 const char *NextChar = getTok().getEndLoc().getPointer();
2010 if (*NextChar == ' ')
2014 if (!AddTokens && ParenLevel == 0) {
2020 // handleMacroEntry relies on not advancing the lexer here
2021 // to be able to fill in the remaining default parameter values
2022 if (Lexer.is(AsmToken::EndOfStatement))
2025 // Adjust the current parentheses level.
2026 if (Lexer.is(AsmToken::LParen))
2028 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2031 // Append the token to the current argument list.
2032 MA.push_back(getTok());
2038 if (ParenLevel != 0)
2039 return TokError("unbalanced parentheses in macro argument");
2043 // Parse the macro instantiation arguments.
2044 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2045 MCAsmMacroArguments &A) {
2046 const unsigned NParameters = M ? M->Parameters.size() : 0;
2047 bool NamedParametersFound = false;
2048 SmallVector<SMLoc, 4> FALocs;
2050 A.resize(NParameters);
2051 FALocs.resize(NParameters);
2053 // Parse two kinds of macro invocations:
2054 // - macros defined without any parameters accept an arbitrary number of them
2055 // - macros defined with parameters accept at most that many of them
2056 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2057 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2059 SMLoc IDLoc = Lexer.getLoc();
2060 MCAsmMacroParameter FA;
2062 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2063 if (parseIdentifier(FA.Name)) {
2064 Error(IDLoc, "invalid argument identifier for formal argument");
2065 eatToEndOfStatement();
2069 if (!Lexer.is(AsmToken::Equal)) {
2070 TokError("expected '=' after formal parameter identifier");
2071 eatToEndOfStatement();
2076 NamedParametersFound = true;
2079 if (NamedParametersFound && FA.Name.empty()) {
2080 Error(IDLoc, "cannot mix positional and keyword arguments");
2081 eatToEndOfStatement();
2085 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2086 if (parseMacroArgument(FA.Value, Vararg))
2089 unsigned PI = Parameter;
2090 if (!FA.Name.empty()) {
2092 for (FAI = 0; FAI < NParameters; ++FAI)
2093 if (M->Parameters[FAI].Name == FA.Name)
2096 if (FAI >= NParameters) {
2097 assert(M && "expected macro to be defined");
2099 "parameter named '" + FA.Name + "' does not exist for macro '" +
2106 if (!FA.Value.empty()) {
2111 if (FALocs.size() <= PI)
2112 FALocs.resize(PI + 1);
2114 FALocs[PI] = Lexer.getLoc();
2117 // At the end of the statement, fill in remaining arguments that have
2118 // default values. If there aren't any, then the next argument is
2119 // required but missing
2120 if (Lexer.is(AsmToken::EndOfStatement)) {
2121 bool Failure = false;
2122 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2123 if (A[FAI].empty()) {
2124 if (M->Parameters[FAI].Required) {
2125 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2126 "missing value for required parameter "
2127 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2131 if (!M->Parameters[FAI].Value.empty())
2132 A[FAI] = M->Parameters[FAI].Value;
2138 if (Lexer.is(AsmToken::Comma))
2142 return TokError("too many positional arguments");
2145 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2146 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2147 return (I == MacroMap.end()) ? nullptr : &I->getValue();
2150 void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2151 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2154 void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2156 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2157 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2158 // this, although we should protect against infinite loops.
2159 if (ActiveMacros.size() == 20)
2160 return TokError("macros cannot be nested more than 20 levels deep");
2162 MCAsmMacroArguments A;
2163 if (parseMacroArguments(M, A))
2166 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2167 // to hold the macro body with substitutions.
2168 SmallString<256> Buf;
2169 StringRef Body = M->Body;
2170 raw_svector_ostream OS(Buf);
2172 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2175 // We include the .endmacro in the buffer as our cue to exit the macro
2177 OS << ".endmacro\n";
2179 std::unique_ptr<MemoryBuffer> Instantiation =
2180 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2182 // Create the macro instantiation object and add to the current macro
2183 // instantiation stack.
2184 MacroInstantiation *MI = new MacroInstantiation(
2185 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2186 ActiveMacros.push_back(MI);
2188 ++NumOfMacroInstantiations;
2190 // Jump to the macro instantiation and prime the lexer.
2191 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2192 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2198 void AsmParser::handleMacroExit() {
2199 // Jump to the EndOfStatement we should return to, and consume it.
2200 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2203 // Pop the instantiation entry.
2204 delete ActiveMacros.back();
2205 ActiveMacros.pop_back();
2208 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2211 const MCExpr *Value;
2212 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2217 // In the case where we parse an expression starting with a '.', we will
2218 // not generate an error, nor will we create a symbol. In this case we
2219 // should just return out.
2223 // Do the assignment.
2224 Out.EmitAssignment(Sym, Value);
2226 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2231 /// parseIdentifier:
2234 bool AsmParser::parseIdentifier(StringRef &Res) {
2235 // The assembler has relaxed rules for accepting identifiers, in particular we
2236 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2237 // separate tokens. At this level, we have already lexed so we cannot (currently)
2238 // handle this as a context dependent token, instead we detect adjacent tokens
2239 // and return the combined identifier.
2240 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2241 SMLoc PrefixLoc = getLexer().getLoc();
2243 // Consume the prefix character, and check for a following identifier.
2245 if (Lexer.isNot(AsmToken::Identifier))
2248 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2249 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2252 // Construct the joined identifier and consume the token.
2254 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2259 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2262 Res = getTok().getIdentifier();
2264 Lex(); // Consume the identifier token.
2269 /// parseDirectiveSet:
2270 /// ::= .equ identifier ',' expression
2271 /// ::= .equiv identifier ',' expression
2272 /// ::= .set identifier ',' expression
2273 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2276 if (parseIdentifier(Name))
2277 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2279 if (getLexer().isNot(AsmToken::Comma))
2280 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2283 return parseAssignment(Name, allow_redef, true);
2286 bool AsmParser::parseEscapedString(std::string &Data) {
2287 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2290 StringRef Str = getTok().getStringContents();
2291 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2292 if (Str[i] != '\\') {
2297 // Recognize escaped characters. Note that this escape semantics currently
2298 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2301 return TokError("unexpected backslash at end of string");
2303 // Recognize octal sequences.
2304 if ((unsigned)(Str[i] - '0') <= 7) {
2305 // Consume up to three octal characters.
2306 unsigned Value = Str[i] - '0';
2308 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2310 Value = Value * 8 + (Str[i] - '0');
2312 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2314 Value = Value * 8 + (Str[i] - '0');
2319 return TokError("invalid octal escape sequence (out of range)");
2321 Data += (unsigned char)Value;
2325 // Otherwise recognize individual escapes.
2328 // Just reject invalid escape sequences for now.
2329 return TokError("invalid escape sequence (unrecognized character)");
2331 case 'b': Data += '\b'; break;
2332 case 'f': Data += '\f'; break;
2333 case 'n': Data += '\n'; break;
2334 case 'r': Data += '\r'; break;
2335 case 't': Data += '\t'; break;
2336 case '"': Data += '"'; break;
2337 case '\\': Data += '\\'; break;
2344 /// parseDirectiveAscii:
2345 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2346 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2347 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2348 checkForValidSection();
2351 if (getLexer().isNot(AsmToken::String))
2352 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2355 if (parseEscapedString(Data))
2358 getStreamer().EmitBytes(Data);
2360 getStreamer().EmitBytes(StringRef("\0", 1));
2364 if (getLexer().is(AsmToken::EndOfStatement))
2367 if (getLexer().isNot(AsmToken::Comma))
2368 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2377 /// parseDirectiveValue
2378 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2379 bool AsmParser::parseDirectiveValue(unsigned Size) {
2380 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2381 checkForValidSection();
2384 const MCExpr *Value;
2385 SMLoc ExprLoc = getLexer().getLoc();
2386 if (parseExpression(Value))
2389 // Special case constant expressions to match code generator.
2390 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2391 assert(Size <= 8 && "Invalid size");
2392 uint64_t IntValue = MCE->getValue();
2393 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2394 return Error(ExprLoc, "literal value out of range for directive");
2395 getStreamer().EmitIntValue(IntValue, Size);
2397 getStreamer().EmitValue(Value, Size, ExprLoc);
2399 if (getLexer().is(AsmToken::EndOfStatement))
2402 // FIXME: Improve diagnostic.
2403 if (getLexer().isNot(AsmToken::Comma))
2404 return TokError("unexpected token in directive");
2413 /// ParseDirectiveOctaValue
2414 /// ::= .octa [ hexconstant (, hexconstant)* ]
2415 bool AsmParser::parseDirectiveOctaValue() {
2416 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2417 checkForValidSection();
2420 if (Lexer.getKind() == AsmToken::Error)
2422 if (Lexer.getKind() != AsmToken::Integer &&
2423 Lexer.getKind() != AsmToken::BigNum)
2424 return TokError("unknown token in expression");
2426 SMLoc ExprLoc = getLexer().getLoc();
2427 APInt IntValue = getTok().getAPIntVal();
2431 if (IntValue.isIntN(64)) {
2433 lo = IntValue.getZExtValue();
2434 } else if (IntValue.isIntN(128)) {
2435 // It might actually have more than 128 bits, but the top ones are zero.
2436 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2437 lo = IntValue.getLoBits(64).getZExtValue();
2439 return Error(ExprLoc, "literal value out of range for directive");
2441 if (MAI.isLittleEndian()) {
2442 getStreamer().EmitIntValue(lo, 8);
2443 getStreamer().EmitIntValue(hi, 8);
2445 getStreamer().EmitIntValue(hi, 8);
2446 getStreamer().EmitIntValue(lo, 8);
2449 if (getLexer().is(AsmToken::EndOfStatement))
2452 // FIXME: Improve diagnostic.
2453 if (getLexer().isNot(AsmToken::Comma))
2454 return TokError("unexpected token in directive");
2463 /// parseDirectiveRealValue
2464 /// ::= (.single | .double) [ expression (, expression)* ]
2465 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2466 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2467 checkForValidSection();
2470 // We don't truly support arithmetic on floating point expressions, so we
2471 // have to manually parse unary prefixes.
2473 if (getLexer().is(AsmToken::Minus)) {
2476 } else if (getLexer().is(AsmToken::Plus))
2479 if (getLexer().isNot(AsmToken::Integer) &&
2480 getLexer().isNot(AsmToken::Real) &&
2481 getLexer().isNot(AsmToken::Identifier))
2482 return TokError("unexpected token in directive");
2484 // Convert to an APFloat.
2485 APFloat Value(Semantics);
2486 StringRef IDVal = getTok().getString();
2487 if (getLexer().is(AsmToken::Identifier)) {
2488 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2489 Value = APFloat::getInf(Semantics);
2490 else if (!IDVal.compare_lower("nan"))
2491 Value = APFloat::getNaN(Semantics, false, ~0);
2493 return TokError("invalid floating point literal");
2494 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2495 APFloat::opInvalidOp)
2496 return TokError("invalid floating point literal");
2500 // Consume the numeric token.
2503 // Emit the value as an integer.
2504 APInt AsInt = Value.bitcastToAPInt();
2505 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2506 AsInt.getBitWidth() / 8);
2508 if (getLexer().is(AsmToken::EndOfStatement))
2511 if (getLexer().isNot(AsmToken::Comma))
2512 return TokError("unexpected token in directive");
2521 /// parseDirectiveZero
2522 /// ::= .zero expression
2523 bool AsmParser::parseDirectiveZero() {
2524 checkForValidSection();
2527 if (parseAbsoluteExpression(NumBytes))
2531 if (getLexer().is(AsmToken::Comma)) {
2533 if (parseAbsoluteExpression(Val))
2537 if (getLexer().isNot(AsmToken::EndOfStatement))
2538 return TokError("unexpected token in '.zero' directive");
2542 getStreamer().EmitFill(NumBytes, Val);
2547 /// parseDirectiveFill
2548 /// ::= .fill expression [ , expression [ , expression ] ]
2549 bool AsmParser::parseDirectiveFill() {
2550 checkForValidSection();
2552 SMLoc RepeatLoc = getLexer().getLoc();
2554 if (parseAbsoluteExpression(NumValues))
2557 if (NumValues < 0) {
2559 "'.fill' directive with negative repeat count has no effect");
2563 int64_t FillSize = 1;
2564 int64_t FillExpr = 0;
2566 SMLoc SizeLoc, ExprLoc;
2567 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2568 if (getLexer().isNot(AsmToken::Comma))
2569 return TokError("unexpected token in '.fill' directive");
2572 SizeLoc = getLexer().getLoc();
2573 if (parseAbsoluteExpression(FillSize))
2576 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2577 if (getLexer().isNot(AsmToken::Comma))
2578 return TokError("unexpected token in '.fill' directive");
2581 ExprLoc = getLexer().getLoc();
2582 if (parseAbsoluteExpression(FillExpr))
2585 if (getLexer().isNot(AsmToken::EndOfStatement))
2586 return TokError("unexpected token in '.fill' directive");
2593 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2597 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2601 if (!isUInt<32>(FillExpr) && FillSize > 4)
2602 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2604 if (NumValues > 0) {
2605 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2606 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2607 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2608 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2609 if (NonZeroFillSize < FillSize)
2610 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2617 /// parseDirectiveOrg
2618 /// ::= .org expression [ , expression ]
2619 bool AsmParser::parseDirectiveOrg() {
2620 checkForValidSection();
2622 const MCExpr *Offset;
2623 SMLoc Loc = getTok().getLoc();
2624 if (parseExpression(Offset))
2627 // Parse optional fill expression.
2628 int64_t FillExpr = 0;
2629 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2630 if (getLexer().isNot(AsmToken::Comma))
2631 return TokError("unexpected token in '.org' directive");
2634 if (parseAbsoluteExpression(FillExpr))
2637 if (getLexer().isNot(AsmToken::EndOfStatement))
2638 return TokError("unexpected token in '.org' directive");
2643 // Only limited forms of relocatable expressions are accepted here, it
2644 // has to be relative to the current section. The streamer will return
2645 // 'true' if the expression wasn't evaluatable.
2646 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2647 return Error(Loc, "expected assembly-time absolute expression");
2652 /// parseDirectiveAlign
2653 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2654 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2655 checkForValidSection();
2657 SMLoc AlignmentLoc = getLexer().getLoc();
2659 if (parseAbsoluteExpression(Alignment))
2663 bool HasFillExpr = false;
2664 int64_t FillExpr = 0;
2665 int64_t MaxBytesToFill = 0;
2666 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2667 if (getLexer().isNot(AsmToken::Comma))
2668 return TokError("unexpected token in directive");
2671 // The fill expression can be omitted while specifying a maximum number of
2672 // alignment bytes, e.g:
2674 if (getLexer().isNot(AsmToken::Comma)) {
2676 if (parseAbsoluteExpression(FillExpr))
2680 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2681 if (getLexer().isNot(AsmToken::Comma))
2682 return TokError("unexpected token in directive");
2685 MaxBytesLoc = getLexer().getLoc();
2686 if (parseAbsoluteExpression(MaxBytesToFill))
2689 if (getLexer().isNot(AsmToken::EndOfStatement))
2690 return TokError("unexpected token in directive");
2699 // Compute alignment in bytes.
2701 // FIXME: Diagnose overflow.
2702 if (Alignment >= 32) {
2703 Error(AlignmentLoc, "invalid alignment value");
2707 Alignment = 1ULL << Alignment;
2709 // Reject alignments that aren't a power of two, for gas compatibility.
2710 if (!isPowerOf2_64(Alignment))
2711 Error(AlignmentLoc, "alignment must be a power of 2");
2714 // Diagnose non-sensical max bytes to align.
2715 if (MaxBytesLoc.isValid()) {
2716 if (MaxBytesToFill < 1) {
2717 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2718 "many bytes, ignoring maximum bytes expression");
2722 if (MaxBytesToFill >= Alignment) {
2723 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2729 // Check whether we should use optimal code alignment for this .align
2731 const MCSection *Section = getStreamer().getCurrentSection().first;
2732 assert(Section && "must have section to emit alignment");
2733 bool UseCodeAlign = Section->UseCodeAlign();
2734 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2735 ValueSize == 1 && UseCodeAlign) {
2736 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2738 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2739 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2746 /// parseDirectiveFile
2747 /// ::= .file [number] filename
2748 /// ::= .file number directory filename
2749 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2750 // FIXME: I'm not sure what this is.
2751 int64_t FileNumber = -1;
2752 SMLoc FileNumberLoc = getLexer().getLoc();
2753 if (getLexer().is(AsmToken::Integer)) {
2754 FileNumber = getTok().getIntVal();
2758 return TokError("file number less than one");
2761 if (getLexer().isNot(AsmToken::String))
2762 return TokError("unexpected token in '.file' directive");
2764 // Usually the directory and filename together, otherwise just the directory.
2765 // Allow the strings to have escaped octal character sequence.
2766 std::string Path = getTok().getString();
2767 if (parseEscapedString(Path))
2771 StringRef Directory;
2773 std::string FilenameData;
2774 if (getLexer().is(AsmToken::String)) {
2775 if (FileNumber == -1)
2776 return TokError("explicit path specified, but no file number");
2777 if (parseEscapedString(FilenameData))
2779 Filename = FilenameData;
2786 if (getLexer().isNot(AsmToken::EndOfStatement))
2787 return TokError("unexpected token in '.file' directive");
2789 if (FileNumber == -1)
2790 getStreamer().EmitFileDirective(Filename);
2792 if (getContext().getGenDwarfForAssembly())
2794 "input can't have .file dwarf directives when -g is "
2795 "used to generate dwarf debug info for assembly code");
2797 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2799 Error(FileNumberLoc, "file number already allocated");
2805 /// parseDirectiveLine
2806 /// ::= .line [number]
2807 bool AsmParser::parseDirectiveLine() {
2808 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2809 if (getLexer().isNot(AsmToken::Integer))
2810 return TokError("unexpected token in '.line' directive");
2812 int64_t LineNumber = getTok().getIntVal();
2816 // FIXME: Do something with the .line.
2819 if (getLexer().isNot(AsmToken::EndOfStatement))
2820 return TokError("unexpected token in '.line' directive");
2825 /// parseDirectiveLoc
2826 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2827 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2828 /// The first number is a file number, must have been previously assigned with
2829 /// a .file directive, the second number is the line number and optionally the
2830 /// third number is a column position (zero if not specified). The remaining
2831 /// optional items are .loc sub-directives.
2832 bool AsmParser::parseDirectiveLoc() {
2833 if (getLexer().isNot(AsmToken::Integer))
2834 return TokError("unexpected token in '.loc' directive");
2835 int64_t FileNumber = getTok().getIntVal();
2837 return TokError("file number less than one in '.loc' directive");
2838 if (!getContext().isValidDwarfFileNumber(FileNumber))
2839 return TokError("unassigned file number in '.loc' directive");
2842 int64_t LineNumber = 0;
2843 if (getLexer().is(AsmToken::Integer)) {
2844 LineNumber = getTok().getIntVal();
2846 return TokError("line number less than zero in '.loc' directive");
2850 int64_t ColumnPos = 0;
2851 if (getLexer().is(AsmToken::Integer)) {
2852 ColumnPos = getTok().getIntVal();
2854 return TokError("column position less than zero in '.loc' directive");
2858 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2860 int64_t Discriminator = 0;
2861 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2863 if (getLexer().is(AsmToken::EndOfStatement))
2867 SMLoc Loc = getTok().getLoc();
2868 if (parseIdentifier(Name))
2869 return TokError("unexpected token in '.loc' directive");
2871 if (Name == "basic_block")
2872 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2873 else if (Name == "prologue_end")
2874 Flags |= DWARF2_FLAG_PROLOGUE_END;
2875 else if (Name == "epilogue_begin")
2876 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2877 else if (Name == "is_stmt") {
2878 Loc = getTok().getLoc();
2879 const MCExpr *Value;
2880 if (parseExpression(Value))
2882 // The expression must be the constant 0 or 1.
2883 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2884 int Value = MCE->getValue();
2886 Flags &= ~DWARF2_FLAG_IS_STMT;
2887 else if (Value == 1)
2888 Flags |= DWARF2_FLAG_IS_STMT;
2890 return Error(Loc, "is_stmt value not 0 or 1");
2892 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2894 } else if (Name == "isa") {
2895 Loc = getTok().getLoc();
2896 const MCExpr *Value;
2897 if (parseExpression(Value))
2899 // The expression must be a constant greater or equal to 0.
2900 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2901 int Value = MCE->getValue();
2903 return Error(Loc, "isa number less than zero");
2906 return Error(Loc, "isa number not a constant value");
2908 } else if (Name == "discriminator") {
2909 if (parseAbsoluteExpression(Discriminator))
2912 return Error(Loc, "unknown sub-directive in '.loc' directive");
2915 if (getLexer().is(AsmToken::EndOfStatement))
2920 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2921 Isa, Discriminator, StringRef());
2926 /// parseDirectiveStabs
2927 /// ::= .stabs string, number, number, number
2928 bool AsmParser::parseDirectiveStabs() {
2929 return TokError("unsupported directive '.stabs'");
2932 /// parseDirectiveCFISections
2933 /// ::= .cfi_sections section [, section]
2934 bool AsmParser::parseDirectiveCFISections() {
2939 if (parseIdentifier(Name))
2940 return TokError("Expected an identifier");
2942 if (Name == ".eh_frame")
2944 else if (Name == ".debug_frame")
2947 if (getLexer().is(AsmToken::Comma)) {
2950 if (parseIdentifier(Name))
2951 return TokError("Expected an identifier");
2953 if (Name == ".eh_frame")
2955 else if (Name == ".debug_frame")
2959 getStreamer().EmitCFISections(EH, Debug);
2963 /// parseDirectiveCFIStartProc
2964 /// ::= .cfi_startproc [simple]
2965 bool AsmParser::parseDirectiveCFIStartProc() {
2967 if (getLexer().isNot(AsmToken::EndOfStatement))
2968 if (parseIdentifier(Simple) || Simple != "simple")
2969 return TokError("unexpected token in .cfi_startproc directive");
2971 getStreamer().EmitCFIStartProc(!Simple.empty());
2975 /// parseDirectiveCFIEndProc
2976 /// ::= .cfi_endproc
2977 bool AsmParser::parseDirectiveCFIEndProc() {
2978 getStreamer().EmitCFIEndProc();
2982 /// \brief parse register name or number.
2983 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2984 SMLoc DirectiveLoc) {
2987 if (getLexer().isNot(AsmToken::Integer)) {
2988 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2990 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2992 return parseAbsoluteExpression(Register);
2997 /// parseDirectiveCFIDefCfa
2998 /// ::= .cfi_def_cfa register, offset
2999 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3000 int64_t Register = 0;
3001 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3004 if (getLexer().isNot(AsmToken::Comma))
3005 return TokError("unexpected token in directive");
3009 if (parseAbsoluteExpression(Offset))
3012 getStreamer().EmitCFIDefCfa(Register, Offset);
3016 /// parseDirectiveCFIDefCfaOffset
3017 /// ::= .cfi_def_cfa_offset offset
3018 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3020 if (parseAbsoluteExpression(Offset))
3023 getStreamer().EmitCFIDefCfaOffset(Offset);
3027 /// parseDirectiveCFIRegister
3028 /// ::= .cfi_register register, register
3029 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3030 int64_t Register1 = 0;
3031 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3034 if (getLexer().isNot(AsmToken::Comma))
3035 return TokError("unexpected token in directive");
3038 int64_t Register2 = 0;
3039 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3042 getStreamer().EmitCFIRegister(Register1, Register2);
3046 /// parseDirectiveCFIWindowSave
3047 /// ::= .cfi_window_save
3048 bool AsmParser::parseDirectiveCFIWindowSave() {
3049 getStreamer().EmitCFIWindowSave();
3053 /// parseDirectiveCFIAdjustCfaOffset
3054 /// ::= .cfi_adjust_cfa_offset adjustment
3055 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3056 int64_t Adjustment = 0;
3057 if (parseAbsoluteExpression(Adjustment))
3060 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3064 /// parseDirectiveCFIDefCfaRegister
3065 /// ::= .cfi_def_cfa_register register
3066 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3067 int64_t Register = 0;
3068 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3071 getStreamer().EmitCFIDefCfaRegister(Register);
3075 /// parseDirectiveCFIOffset
3076 /// ::= .cfi_offset register, offset
3077 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3078 int64_t Register = 0;
3081 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3084 if (getLexer().isNot(AsmToken::Comma))
3085 return TokError("unexpected token in directive");
3088 if (parseAbsoluteExpression(Offset))
3091 getStreamer().EmitCFIOffset(Register, Offset);
3095 /// parseDirectiveCFIRelOffset
3096 /// ::= .cfi_rel_offset register, offset
3097 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3098 int64_t Register = 0;
3100 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3103 if (getLexer().isNot(AsmToken::Comma))
3104 return TokError("unexpected token in directive");
3108 if (parseAbsoluteExpression(Offset))
3111 getStreamer().EmitCFIRelOffset(Register, Offset);
3115 static bool isValidEncoding(int64_t Encoding) {
3116 if (Encoding & ~0xff)
3119 if (Encoding == dwarf::DW_EH_PE_omit)
3122 const unsigned Format = Encoding & 0xf;
3123 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3124 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3125 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3126 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3129 const unsigned Application = Encoding & 0x70;
3130 if (Application != dwarf::DW_EH_PE_absptr &&
3131 Application != dwarf::DW_EH_PE_pcrel)
3137 /// parseDirectiveCFIPersonalityOrLsda
3138 /// IsPersonality true for cfi_personality, false for cfi_lsda
3139 /// ::= .cfi_personality encoding, [symbol_name]
3140 /// ::= .cfi_lsda encoding, [symbol_name]
3141 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3142 int64_t Encoding = 0;
3143 if (parseAbsoluteExpression(Encoding))
3145 if (Encoding == dwarf::DW_EH_PE_omit)
3148 if (!isValidEncoding(Encoding))
3149 return TokError("unsupported encoding.");
3151 if (getLexer().isNot(AsmToken::Comma))
3152 return TokError("unexpected token in directive");
3156 if (parseIdentifier(Name))
3157 return TokError("expected identifier in directive");
3159 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3162 getStreamer().EmitCFIPersonality(Sym, Encoding);
3164 getStreamer().EmitCFILsda(Sym, Encoding);
3168 /// parseDirectiveCFIRememberState
3169 /// ::= .cfi_remember_state
3170 bool AsmParser::parseDirectiveCFIRememberState() {
3171 getStreamer().EmitCFIRememberState();
3175 /// parseDirectiveCFIRestoreState
3176 /// ::= .cfi_remember_state
3177 bool AsmParser::parseDirectiveCFIRestoreState() {
3178 getStreamer().EmitCFIRestoreState();
3182 /// parseDirectiveCFISameValue
3183 /// ::= .cfi_same_value register
3184 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3185 int64_t Register = 0;
3187 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3190 getStreamer().EmitCFISameValue(Register);
3194 /// parseDirectiveCFIRestore
3195 /// ::= .cfi_restore register
3196 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3197 int64_t Register = 0;
3198 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3201 getStreamer().EmitCFIRestore(Register);
3205 /// parseDirectiveCFIEscape
3206 /// ::= .cfi_escape expression[,...]
3207 bool AsmParser::parseDirectiveCFIEscape() {
3210 if (parseAbsoluteExpression(CurrValue))
3213 Values.push_back((uint8_t)CurrValue);
3215 while (getLexer().is(AsmToken::Comma)) {
3218 if (parseAbsoluteExpression(CurrValue))
3221 Values.push_back((uint8_t)CurrValue);
3224 getStreamer().EmitCFIEscape(Values);
3228 /// parseDirectiveCFISignalFrame
3229 /// ::= .cfi_signal_frame
3230 bool AsmParser::parseDirectiveCFISignalFrame() {
3231 if (getLexer().isNot(AsmToken::EndOfStatement))
3232 return Error(getLexer().getLoc(),
3233 "unexpected token in '.cfi_signal_frame'");
3235 getStreamer().EmitCFISignalFrame();
3239 /// parseDirectiveCFIUndefined
3240 /// ::= .cfi_undefined register
3241 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3242 int64_t Register = 0;
3244 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3247 getStreamer().EmitCFIUndefined(Register);
3251 /// parseDirectiveMacrosOnOff
3254 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3255 if (getLexer().isNot(AsmToken::EndOfStatement))
3256 return Error(getLexer().getLoc(),
3257 "unexpected token in '" + Directive + "' directive");
3259 setMacrosEnabled(Directive == ".macros_on");
3263 /// parseDirectiveMacro
3264 /// ::= .macro name[,] [parameters]
3265 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3267 if (parseIdentifier(Name))
3268 return TokError("expected identifier in '.macro' directive");
3270 if (getLexer().is(AsmToken::Comma))
3273 MCAsmMacroParameters Parameters;
3274 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3276 if (!Parameters.empty() && Parameters.back().Vararg)
3277 return Error(Lexer.getLoc(),
3278 "Vararg parameter '" + Parameters.back().Name +
3279 "' should be last one in the list of parameters.");
3281 MCAsmMacroParameter Parameter;
3282 if (parseIdentifier(Parameter.Name))
3283 return TokError("expected identifier in '.macro' directive");
3285 if (Lexer.is(AsmToken::Colon)) {
3286 Lex(); // consume ':'
3289 StringRef Qualifier;
3291 QualLoc = Lexer.getLoc();
3292 if (parseIdentifier(Qualifier))
3293 return Error(QualLoc, "missing parameter qualifier for "
3294 "'" + Parameter.Name + "' in macro '" + Name + "'");
3296 if (Qualifier == "req")
3297 Parameter.Required = true;
3298 else if (Qualifier == "vararg")
3299 Parameter.Vararg = true;
3301 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3302 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3305 if (getLexer().is(AsmToken::Equal)) {
3310 ParamLoc = Lexer.getLoc();
3311 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3314 if (Parameter.Required)
3315 Warning(ParamLoc, "pointless default value for required parameter "
3316 "'" + Parameter.Name + "' in macro '" + Name + "'");
3319 Parameters.push_back(std::move(Parameter));
3321 if (getLexer().is(AsmToken::Comma))
3325 // Eat the end of statement.
3328 AsmToken EndToken, StartToken = getTok();
3329 unsigned MacroDepth = 0;
3331 // Lex the macro definition.
3333 // Check whether we have reached the end of the file.
3334 if (getLexer().is(AsmToken::Eof))
3335 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3337 // Otherwise, check whether we have reach the .endmacro.
3338 if (getLexer().is(AsmToken::Identifier)) {
3339 if (getTok().getIdentifier() == ".endm" ||
3340 getTok().getIdentifier() == ".endmacro") {
3341 if (MacroDepth == 0) { // Outermost macro.
3342 EndToken = getTok();
3344 if (getLexer().isNot(AsmToken::EndOfStatement))
3345 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3349 // Otherwise we just found the end of an inner macro.
3352 } else if (getTok().getIdentifier() == ".macro") {
3353 // We allow nested macros. Those aren't instantiated until the outermost
3354 // macro is expanded so just ignore them for now.
3359 // Otherwise, scan til the end of the statement.
3360 eatToEndOfStatement();
3363 if (lookupMacro(Name)) {
3364 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3367 const char *BodyStart = StartToken.getLoc().getPointer();
3368 const char *BodyEnd = EndToken.getLoc().getPointer();
3369 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3370 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3371 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
3375 /// checkForBadMacro
3377 /// With the support added for named parameters there may be code out there that
3378 /// is transitioning from positional parameters. In versions of gas that did
3379 /// not support named parameters they would be ignored on the macro definition.
3380 /// But to support both styles of parameters this is not possible so if a macro
3381 /// definition has named parameters but does not use them and has what appears
3382 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3383 /// warning that the positional parameter found in body which have no effect.
3384 /// Hoping the developer will either remove the named parameters from the macro
3385 /// definition so the positional parameters get used if that was what was
3386 /// intended or change the macro to use the named parameters. It is possible
3387 /// this warning will trigger when the none of the named parameters are used
3388 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3389 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3391 ArrayRef<MCAsmMacroParameter> Parameters) {
3392 // If this macro is not defined with named parameters the warning we are
3393 // checking for here doesn't apply.
3394 unsigned NParameters = Parameters.size();
3395 if (NParameters == 0)
3398 bool NamedParametersFound = false;
3399 bool PositionalParametersFound = false;
3401 // Look at the body of the macro for use of both the named parameters and what
3402 // are likely to be positional parameters. This is what expandMacro() is
3403 // doing when it finds the parameters in the body.
3404 while (!Body.empty()) {
3405 // Scan for the next possible parameter.
3406 std::size_t End = Body.size(), Pos = 0;
3407 for (; Pos != End; ++Pos) {
3408 // Check for a substitution or escape.
3409 // This macro is defined with parameters, look for \foo, \bar, etc.
3410 if (Body[Pos] == '\\' && Pos + 1 != End)
3413 // This macro should have parameters, but look for $0, $1, ..., $n too.
3414 if (Body[Pos] != '$' || Pos + 1 == End)
3416 char Next = Body[Pos + 1];
3417 if (Next == '$' || Next == 'n' ||
3418 isdigit(static_cast<unsigned char>(Next)))
3422 // Check if we reached the end.
3426 if (Body[Pos] == '$') {
3427 switch (Body[Pos + 1]) {
3432 // $n => number of arguments
3434 PositionalParametersFound = true;
3437 // $[0-9] => argument
3439 PositionalParametersFound = true;
3445 unsigned I = Pos + 1;
3446 while (isIdentifierChar(Body[I]) && I + 1 != End)
3449 const char *Begin = Body.data() + Pos + 1;
3450 StringRef Argument(Begin, I - (Pos + 1));
3452 for (; Index < NParameters; ++Index)
3453 if (Parameters[Index].Name == Argument)
3456 if (Index == NParameters) {
3457 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3463 NamedParametersFound = true;
3464 Pos += 1 + Argument.size();
3467 // Update the scan point.
3468 Body = Body.substr(Pos);
3471 if (!NamedParametersFound && PositionalParametersFound)
3472 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3473 "used in macro body, possible positional parameter "
3474 "found in body which will have no effect");
3477 /// parseDirectiveExitMacro
3479 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3480 if (getLexer().isNot(AsmToken::EndOfStatement))
3481 return TokError("unexpected token in '" + Directive + "' directive");
3483 if (!isInsideMacroInstantiation())
3484 return TokError("unexpected '" + Directive + "' in file, "
3485 "no current macro definition");
3487 // Exit all conditionals that are active in the current macro.
3488 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3489 TheCondState = TheCondStack.back();
3490 TheCondStack.pop_back();
3497 /// parseDirectiveEndMacro
3500 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3501 if (getLexer().isNot(AsmToken::EndOfStatement))
3502 return TokError("unexpected token in '" + Directive + "' directive");
3504 // If we are inside a macro instantiation, terminate the current
3506 if (isInsideMacroInstantiation()) {
3511 // Otherwise, this .endmacro is a stray entry in the file; well formed
3512 // .endmacro directives are handled during the macro definition parsing.
3513 return TokError("unexpected '" + Directive + "' in file, "
3514 "no current macro definition");
3517 /// parseDirectivePurgeMacro
3519 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3521 if (parseIdentifier(Name))
3522 return TokError("expected identifier in '.purgem' directive");
3524 if (getLexer().isNot(AsmToken::EndOfStatement))
3525 return TokError("unexpected token in '.purgem' directive");
3527 if (!lookupMacro(Name))
3528 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3530 undefineMacro(Name);
3534 /// parseDirectiveBundleAlignMode
3535 /// ::= {.bundle_align_mode} expression
3536 bool AsmParser::parseDirectiveBundleAlignMode() {
3537 checkForValidSection();
3539 // Expect a single argument: an expression that evaluates to a constant
3540 // in the inclusive range 0-30.
3541 SMLoc ExprLoc = getLexer().getLoc();
3542 int64_t AlignSizePow2;
3543 if (parseAbsoluteExpression(AlignSizePow2))
3545 else if (getLexer().isNot(AsmToken::EndOfStatement))
3546 return TokError("unexpected token after expression in"
3547 " '.bundle_align_mode' directive");
3548 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3549 return Error(ExprLoc,
3550 "invalid bundle alignment size (expected between 0 and 30)");
3554 // Because of AlignSizePow2's verified range we can safely truncate it to
3556 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3560 /// parseDirectiveBundleLock
3561 /// ::= {.bundle_lock} [align_to_end]
3562 bool AsmParser::parseDirectiveBundleLock() {
3563 checkForValidSection();
3564 bool AlignToEnd = false;
3566 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3568 SMLoc Loc = getTok().getLoc();
3569 const char *kInvalidOptionError =
3570 "invalid option for '.bundle_lock' directive";
3572 if (parseIdentifier(Option))
3573 return Error(Loc, kInvalidOptionError);
3575 if (Option != "align_to_end")
3576 return Error(Loc, kInvalidOptionError);
3577 else if (getLexer().isNot(AsmToken::EndOfStatement))
3579 "unexpected token after '.bundle_lock' directive option");
3585 getStreamer().EmitBundleLock(AlignToEnd);
3589 /// parseDirectiveBundleLock
3590 /// ::= {.bundle_lock}
3591 bool AsmParser::parseDirectiveBundleUnlock() {
3592 checkForValidSection();
3594 if (getLexer().isNot(AsmToken::EndOfStatement))
3595 return TokError("unexpected token in '.bundle_unlock' directive");
3598 getStreamer().EmitBundleUnlock();
3602 /// parseDirectiveSpace
3603 /// ::= (.skip | .space) expression [ , expression ]
3604 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3605 checkForValidSection();
3608 if (parseAbsoluteExpression(NumBytes))
3611 int64_t FillExpr = 0;
3612 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3613 if (getLexer().isNot(AsmToken::Comma))
3614 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3617 if (parseAbsoluteExpression(FillExpr))
3620 if (getLexer().isNot(AsmToken::EndOfStatement))
3621 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3627 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3630 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3631 getStreamer().EmitFill(NumBytes, FillExpr);
3636 /// parseDirectiveLEB128
3637 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
3638 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3639 checkForValidSection();
3640 const MCExpr *Value;
3643 if (parseExpression(Value))
3647 getStreamer().EmitSLEB128Value(Value);
3649 getStreamer().EmitULEB128Value(Value);
3651 if (getLexer().is(AsmToken::EndOfStatement))
3654 if (getLexer().isNot(AsmToken::Comma))
3655 return TokError("unexpected token in directive");