1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCCodeView.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCDirectives.h"
28 #include "llvm/MC/MCDwarf.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCInstPrinter.h"
31 #include "llvm/MC/MCInstrDesc.h"
32 #include "llvm/MC/MCInstrInfo.h"
33 #include "llvm/MC/MCObjectFileInfo.h"
34 #include "llvm/MC/MCParser/AsmCond.h"
35 #include "llvm/MC/MCParser/AsmLexer.h"
36 #include "llvm/MC/MCParser/MCAsmLexer.h"
37 #include "llvm/MC/MCParser/MCAsmParser.h"
38 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
39 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
40 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
41 #include "llvm/MC/MCRegisterInfo.h"
42 #include "llvm/MC/MCSection.h"
43 #include "llvm/MC/MCStreamer.h"
44 #include "llvm/MC/MCSymbol.h"
45 #include "llvm/MC/MCValue.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Dwarf.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/MemoryBuffer.h"
52 #include "llvm/Support/SMLoc.h"
53 #include "llvm/Support/SourceMgr.h"
54 #include "llvm/Support/raw_ostream.h"
70 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
72 static cl::opt<unsigned> AsmMacroMaxNestingDepth(
73 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
74 cl::desc("The maximum nesting depth allowed for assembly macros."));
78 /// \brief Helper types for tracking macro definitions.
79 typedef std::vector<AsmToken> MCAsmMacroArgument;
80 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
82 struct MCAsmMacroParameter {
84 MCAsmMacroArgument Value;
88 MCAsmMacroParameter() : Required(false), Vararg(false) {}
91 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
96 MCAsmMacroParameters Parameters;
99 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
100 : Name(N), Body(B), Parameters(std::move(P)) {}
103 /// \brief Helper class for storing information about an active macro
105 struct MacroInstantiation {
106 /// The location of the instantiation.
107 SMLoc InstantiationLoc;
109 /// The buffer where parsing should resume upon instantiation completion.
112 /// The location where parsing should resume upon instantiation completion.
115 /// The depth of TheCondStack at the start of the instantiation.
116 size_t CondStackDepth;
119 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
122 struct ParseStatementInfo {
123 /// \brief The parsed operands from the last parsed statement.
124 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
126 /// \brief The opcode from the last parsed instruction.
129 /// \brief Was there an error parsing the inline assembly?
132 SmallVectorImpl<AsmRewrite> *AsmRewrites;
134 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
135 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
136 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
139 /// \brief The concrete assembly parser instance.
140 class AsmParser : public MCAsmParser {
141 AsmParser(const AsmParser &) = delete;
142 void operator=(const AsmParser &) = delete;
148 const MCAsmInfo &MAI;
150 SourceMgr::DiagHandlerTy SavedDiagHandler;
151 void *SavedDiagContext;
152 std::unique_ptr<MCAsmParserExtension> PlatformParser;
154 /// This is the current buffer index we're lexing from as managed by the
155 /// SourceMgr object.
158 AsmCond TheCondState;
159 std::vector<AsmCond> TheCondStack;
161 /// \brief maps directive names to handler methods in parser
162 /// extensions. Extensions register themselves in this map by calling
163 /// addDirectiveHandler.
164 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
166 /// \brief Map of currently defined macros.
167 StringMap<MCAsmMacro> MacroMap;
169 /// \brief Stack of active macro instantiations.
170 std::vector<MacroInstantiation*> ActiveMacros;
172 /// \brief List of bodies of anonymous macros.
173 std::deque<MCAsmMacro> MacroLikeBodies;
175 /// Boolean tracking whether macro substitution is enabled.
176 unsigned MacrosEnabledFlag : 1;
178 /// \brief Keeps track of how many .macro's have been instantiated.
179 unsigned NumOfMacroInstantiations;
181 /// The values from the last parsed cpp hash file line comment if any.
182 struct CppHashInfoTy {
184 int64_t LineNumber = 0;
188 CppHashInfoTy CppHashInfo;
190 /// \brief List of forward directional labels for diagnosis at the end.
191 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
193 /// When generating dwarf for assembly source files we need to calculate the
194 /// logical line number based on the last parsed cpp hash file line comment
195 /// and current line. Since this is slow and messes up the SourceMgr's
196 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
197 SMLoc LastQueryIDLoc;
198 unsigned LastQueryBuffer;
199 unsigned LastQueryLine;
201 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
202 unsigned AssemblerDialect;
204 /// \brief is Darwin compatibility enabled?
207 /// \brief Are we parsing ms-style inline assembly?
208 bool ParsingInlineAsm;
211 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
212 const MCAsmInfo &MAI);
213 ~AsmParser() override;
215 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
217 void addDirectiveHandler(StringRef Directive,
218 ExtensionDirectiveHandler Handler) override {
219 ExtensionDirectiveMap[Directive] = Handler;
222 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
223 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
227 /// @name MCAsmParser Interface
230 SourceMgr &getSourceManager() override { return SrcMgr; }
231 MCAsmLexer &getLexer() override { return Lexer; }
232 MCContext &getContext() override { return Ctx; }
233 MCStreamer &getStreamer() override { return Out; }
235 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
237 unsigned getAssemblerDialect() override {
238 if (AssemblerDialect == ~0U)
239 return MAI.getAssemblerDialect();
241 return AssemblerDialect;
243 void setAssemblerDialect(unsigned i) override {
244 AssemblerDialect = i;
247 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
248 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
249 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
251 const AsmToken &Lex() override;
253 void setParsingInlineAsm(bool V) override {
254 ParsingInlineAsm = V;
255 Lexer.setParsingMSInlineAsm(V);
257 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
259 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
260 unsigned &NumOutputs, unsigned &NumInputs,
261 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
262 SmallVectorImpl<std::string> &Constraints,
263 SmallVectorImpl<std::string> &Clobbers,
264 const MCInstrInfo *MII, const MCInstPrinter *IP,
265 MCAsmParserSemaCallback &SI) override;
267 bool parseExpression(const MCExpr *&Res);
268 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
269 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
270 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
271 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
272 SMLoc &EndLoc) override;
273 bool parseAbsoluteExpression(int64_t &Res) override;
275 /// \brief Parse a floating point expression using the float \p Semantics
276 /// and set \p Res to the value.
277 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
279 /// \brief Parse an identifier or string (as a quoted identifier)
280 /// and set \p Res to the identifier contents.
281 bool parseIdentifier(StringRef &Res) override;
282 void eatToEndOfStatement() override;
284 bool checkForValidSection() override;
289 bool parseStatement(ParseStatementInfo &Info,
290 MCAsmParserSemaCallback *SI);
291 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
292 bool parseCppHashLineFilenameComment(SMLoc L);
294 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
295 ArrayRef<MCAsmMacroParameter> Parameters);
296 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
297 ArrayRef<MCAsmMacroParameter> Parameters,
298 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
301 /// \brief Are macros enabled in the parser?
302 bool areMacrosEnabled() {return MacrosEnabledFlag;}
304 /// \brief Control a flag in the parser that enables or disables macros.
305 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
307 /// \brief Lookup a previously defined macro.
308 /// \param Name Macro name.
309 /// \returns Pointer to macro. NULL if no such macro was defined.
310 const MCAsmMacro* lookupMacro(StringRef Name);
312 /// \brief Define a new macro with the given name and information.
313 void defineMacro(StringRef Name, MCAsmMacro Macro);
315 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
316 void undefineMacro(StringRef Name);
318 /// \brief Are we inside a macro instantiation?
319 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
321 /// \brief Handle entry to macro instantiation.
323 /// \param M The macro.
324 /// \param NameLoc Instantiation location.
325 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
327 /// \brief Handle exit from macro instantiation.
328 void handleMacroExit();
330 /// \brief Extract AsmTokens for a macro argument.
331 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
333 /// \brief Parse all macro arguments for a given macro.
334 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
336 void printMacroInstantiations();
337 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
338 SMRange Range = None) const {
339 ArrayRef<SMRange> Ranges(Range);
340 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
342 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
344 /// \brief Enter the specified file. This returns true on failure.
345 bool enterIncludeFile(const std::string &Filename);
347 /// \brief Process the specified file for the .incbin directive.
348 /// This returns true on failure.
349 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
350 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
352 /// \brief Reset the current lexer position to that given by \p Loc. The
353 /// current token is not set; clients should ensure Lex() is called
356 /// \param InBuffer If not 0, should be the known buffer id that contains the
358 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
360 /// \brief Parse up to the end of statement and a return the contents from the
361 /// current token until the end of the statement; the current token on exit
362 /// will be either the EndOfStatement or EOF.
363 StringRef parseStringToEndOfStatement() override;
365 /// \brief Parse until the end of a statement or a comma is encountered,
366 /// return the contents from the current token up to the end or comma.
367 StringRef parseStringToComma();
369 bool parseAssignment(StringRef Name, bool allow_redef,
370 bool NoDeadStrip = false);
372 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
373 MCBinaryExpr::Opcode &Kind);
375 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
376 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
377 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
379 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
381 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
382 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
384 // Generic (target and platform independent) directive parsing.
386 DK_NO_DIRECTIVE, // Placeholder
387 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
389 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
390 DK_DC, DK_DC_A, DK_DC_B, DK_DC_D, DK_DC_L, DK_DC_S, DK_DC_W, DK_DC_X,
391 DK_DCB, DK_DCB_B, DK_DCB_D, DK_DCB_L, DK_DCB_S, DK_DCB_W, DK_DCB_X,
392 DK_DS, DK_DS_B, DK_DS_D, DK_DS_L, DK_DS_P, DK_DS_S, DK_DS_W, DK_DS_X,
393 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
394 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
395 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
396 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
397 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER,
398 DK_PRIVATE_EXTERN, DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
399 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
400 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
401 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
402 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
403 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
404 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
405 DK_CV_FILE, DK_CV_FUNC_ID, DK_CV_INLINE_SITE_ID, DK_CV_LOC, DK_CV_LINETABLE,
406 DK_CV_INLINE_LINETABLE, DK_CV_DEF_RANGE, DK_CV_STRINGTABLE,
408 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
409 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
410 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
411 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
412 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
413 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
414 DK_MACROS_ON, DK_MACROS_OFF,
415 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
416 DK_SLEB128, DK_ULEB128,
417 DK_ERR, DK_ERROR, DK_WARNING,
421 /// \brief Maps directive name --> DirectiveKind enum, for
422 /// directives parsed by this class.
423 StringMap<DirectiveKind> DirectiveKindMap;
425 // ".ascii", ".asciz", ".string"
426 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
427 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
428 bool parseDirectiveValue(StringRef IDVal,
429 unsigned Size); // ".byte", ".long", ...
430 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
431 bool parseDirectiveRealValue(StringRef IDVal,
432 const fltSemantics &); // ".single", ...
433 bool parseDirectiveFill(); // ".fill"
434 bool parseDirectiveZero(); // ".zero"
435 // ".set", ".equ", ".equiv"
436 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
437 bool parseDirectiveOrg(); // ".org"
438 // ".align{,32}", ".p2align{,w,l}"
439 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
441 // ".file", ".line", ".loc", ".stabs"
442 bool parseDirectiveFile(SMLoc DirectiveLoc);
443 bool parseDirectiveLine();
444 bool parseDirectiveLoc();
445 bool parseDirectiveStabs();
447 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
448 // ".cv_inline_linetable", ".cv_def_range"
449 bool parseDirectiveCVFile();
450 bool parseDirectiveCVFuncId();
451 bool parseDirectiveCVInlineSiteId();
452 bool parseDirectiveCVLoc();
453 bool parseDirectiveCVLinetable();
454 bool parseDirectiveCVInlineLinetable();
455 bool parseDirectiveCVDefRange();
456 bool parseDirectiveCVStringTable();
457 bool parseDirectiveCVFileChecksums();
460 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
461 bool parseDirectiveCFIWindowSave();
462 bool parseDirectiveCFISections();
463 bool parseDirectiveCFIStartProc();
464 bool parseDirectiveCFIEndProc();
465 bool parseDirectiveCFIDefCfaOffset();
466 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
467 bool parseDirectiveCFIAdjustCfaOffset();
468 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
469 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
470 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
471 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
472 bool parseDirectiveCFIRememberState();
473 bool parseDirectiveCFIRestoreState();
474 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
475 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
476 bool parseDirectiveCFIEscape();
477 bool parseDirectiveCFISignalFrame();
478 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
481 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
482 bool parseDirectiveExitMacro(StringRef Directive);
483 bool parseDirectiveEndMacro(StringRef Directive);
484 bool parseDirectiveMacro(SMLoc DirectiveLoc);
485 bool parseDirectiveMacrosOnOff(StringRef Directive);
487 // ".bundle_align_mode"
488 bool parseDirectiveBundleAlignMode();
490 bool parseDirectiveBundleLock();
492 bool parseDirectiveBundleUnlock();
495 bool parseDirectiveSpace(StringRef IDVal);
498 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
499 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
501 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
503 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
504 bool parseDirectiveLEB128(bool Signed);
506 /// \brief Parse a directive like ".globl" which
507 /// accepts a single symbol (which should be a label or an external).
508 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
510 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
512 bool parseDirectiveAbort(); // ".abort"
513 bool parseDirectiveInclude(); // ".include"
514 bool parseDirectiveIncbin(); // ".incbin"
516 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
517 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
518 // ".ifb" or ".ifnb", depending on ExpectBlank.
519 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
520 // ".ifc" or ".ifnc", depending on ExpectEqual.
521 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
522 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
523 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
524 // ".ifdef" or ".ifndef", depending on expect_defined
525 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
526 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
527 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
528 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
529 bool parseEscapedString(std::string &Data) override;
531 const MCExpr *applyModifierToExpr(const MCExpr *E,
532 MCSymbolRefExpr::VariantKind Variant);
534 // Macro-like directives
535 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
536 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
537 raw_svector_ostream &OS);
538 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
539 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
540 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
541 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
543 // "_emit" or "__emit"
544 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
548 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
551 bool parseDirectiveEnd(SMLoc DirectiveLoc);
553 // ".err" or ".error"
554 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
557 bool parseDirectiveWarning(SMLoc DirectiveLoc);
559 void initializeDirectiveKindMap();
562 } // end anonymous namespace
566 extern MCAsmParserExtension *createDarwinAsmParser();
567 extern MCAsmParserExtension *createELFAsmParser();
568 extern MCAsmParserExtension *createCOFFAsmParser();
570 } // end namespace llvm
572 enum { DEFAULT_ADDRSPACE = 0 };
574 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
575 const MCAsmInfo &MAI)
576 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
577 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
578 MacrosEnabledFlag(true), CppHashInfo(), AssemblerDialect(~0U),
579 IsDarwin(false), ParsingInlineAsm(false) {
581 // Save the old handler.
582 SavedDiagHandler = SrcMgr.getDiagHandler();
583 SavedDiagContext = SrcMgr.getDiagContext();
584 // Set our own handler which calls the saved handler.
585 SrcMgr.setDiagHandler(DiagHandler, this);
586 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
588 // Initialize the platform / file format parser.
589 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
590 case MCObjectFileInfo::IsCOFF:
591 PlatformParser.reset(createCOFFAsmParser());
593 case MCObjectFileInfo::IsMachO:
594 PlatformParser.reset(createDarwinAsmParser());
597 case MCObjectFileInfo::IsELF:
598 PlatformParser.reset(createELFAsmParser());
602 PlatformParser->Initialize(*this);
603 initializeDirectiveKindMap();
605 NumOfMacroInstantiations = 0;
608 AsmParser::~AsmParser() {
609 assert((HadError || ActiveMacros.empty()) &&
610 "Unexpected active macro instantiation!");
613 void AsmParser::printMacroInstantiations() {
614 // Print the active macro instantiation stack.
615 for (std::vector<MacroInstantiation *>::const_reverse_iterator
616 it = ActiveMacros.rbegin(),
617 ie = ActiveMacros.rend();
619 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
620 "while in macro instantiation");
623 void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
624 printPendingErrors();
625 printMessage(L, SourceMgr::DK_Note, Msg, Range);
626 printMacroInstantiations();
629 bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
630 if(getTargetParser().getTargetOptions().MCNoWarn)
632 if (getTargetParser().getTargetOptions().MCFatalWarnings)
633 return Error(L, Msg, Range);
634 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
635 printMacroInstantiations();
639 bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
641 printMessage(L, SourceMgr::DK_Error, Msg, Range);
642 printMacroInstantiations();
646 bool AsmParser::enterIncludeFile(const std::string &Filename) {
647 std::string IncludedFile;
649 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
654 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
658 /// Process the specified .incbin file by searching for it in the include paths
659 /// then just emitting the byte contents of the file to the streamer. This
660 /// returns true on failure.
661 bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
662 const MCExpr *Count, SMLoc Loc) {
663 std::string IncludedFile;
665 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
669 // Pick up the bytes from the file and emit them.
670 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
671 Bytes = Bytes.drop_front(Skip);
674 if (!Count->evaluateAsAbsolute(Res))
675 return Error(Loc, "expected absolute expression");
677 return Warning(Loc, "negative count has no effect");
678 Bytes = Bytes.take_front(Res);
680 getStreamer().EmitBytes(Bytes);
684 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
685 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
686 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
690 const AsmToken &AsmParser::Lex() {
691 if (Lexer.getTok().is(AsmToken::Error))
692 Error(Lexer.getErrLoc(), Lexer.getErr());
694 // if it's a end of statement with a comment in it
695 if (getTok().is(AsmToken::EndOfStatement)) {
696 // if this is a line comment output it.
697 if (getTok().getString().front() != '\n' &&
698 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
699 Out.addExplicitComment(Twine(getTok().getString()));
702 const AsmToken *tok = &Lexer.Lex();
704 // Parse comments here to be deferred until end of next statement.
705 while (tok->is(AsmToken::Comment)) {
706 if (MAI.preserveAsmComments())
707 Out.addExplicitComment(Twine(tok->getString()));
711 if (tok->is(AsmToken::Eof)) {
712 // If this is the end of an included file, pop the parent file off the
714 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
715 if (ParentIncludeLoc != SMLoc()) {
716 jumpToLoc(ParentIncludeLoc);
724 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
725 // Create the initial section, if requested.
726 if (!NoInitialTextSection)
727 Out.InitSections(false);
733 AsmCond StartingCondState = TheCondState;
735 // If we are generating dwarf for assembly source files save the initial text
736 // section and generate a .file directive.
737 if (getContext().getGenDwarfForAssembly()) {
738 MCSection *Sec = getStreamer().getCurrentSectionOnly();
739 if (!Sec->getBeginSymbol()) {
740 MCSymbol *SectionStartSym = getContext().createTempSymbol();
741 getStreamer().EmitLabel(SectionStartSym);
742 Sec->setBeginSymbol(SectionStartSym);
744 bool InsertResult = getContext().addGenDwarfSection(Sec);
745 assert(InsertResult && ".text section should not have debug info yet");
747 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
748 0, StringRef(), getContext().getMainFileName()));
751 // While we have input, parse each statement.
752 while (Lexer.isNot(AsmToken::Eof)) {
753 ParseStatementInfo Info;
754 if (!parseStatement(Info, nullptr))
757 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
758 // for printing ErrMsg via Lex() only if no (presumably better) parser error
760 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
764 // parseStatement returned true so may need to emit an error.
765 printPendingErrors();
767 // Skipping to the next line if needed.
768 if (!getLexer().isAtStartOfStatement())
769 eatToEndOfStatement();
772 // All errors should have been emitted.
773 assert(!hasPendingError() && "unexpected error from parseStatement");
775 getTargetParser().flushPendingInstructions(getStreamer());
777 if (TheCondState.TheCond != StartingCondState.TheCond ||
778 TheCondState.Ignore != StartingCondState.Ignore)
779 printError(getTok().getLoc(), "unmatched .ifs or .elses");
780 // Check to see there are no empty DwarfFile slots.
781 const auto &LineTables = getContext().getMCDwarfLineTables();
782 if (!LineTables.empty()) {
784 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
785 if (File.Name.empty() && Index != 0)
786 printError(getTok().getLoc(), "unassigned file number: " +
788 " for .file directives");
793 // Check to see that all assembler local symbols were actually defined.
794 // Targets that don't do subsections via symbols may not want this, though,
795 // so conservatively exclude them. Only do this if we're finalizing, though,
796 // as otherwise we won't necessarilly have seen everything yet.
798 if (MAI.hasSubsectionsViaSymbols()) {
799 for (const auto &TableEntry : getContext().getSymbols()) {
800 MCSymbol *Sym = TableEntry.getValue();
801 // Variable symbols may not be marked as defined, so check those
802 // explicitly. If we know it's a variable, we have a definition for
803 // the purposes of this check.
804 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
805 // FIXME: We would really like to refer back to where the symbol was
806 // first referenced for a source location. We need to add something
807 // to track that. Currently, we just point to the end of the file.
808 printError(getTok().getLoc(), "assembler local symbol '" +
809 Sym->getName() + "' not defined");
813 // Temporary symbols like the ones for directional jumps don't go in the
814 // symbol table. They also need to be diagnosed in all (final) cases.
815 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
816 if (std::get<2>(LocSym)->isUndefined()) {
817 // Reset the state of any "# line file" directives we've seen to the
818 // context as it was at the diagnostic site.
819 CppHashInfo = std::get<1>(LocSym);
820 printError(std::get<0>(LocSym), "directional label undefined");
825 // Finalize the output stream if there are no errors and if the client wants
827 if (!HadError && !NoFinalize)
830 return HadError || getContext().hadError();
833 bool AsmParser::checkForValidSection() {
834 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
835 Out.InitSections(false);
836 return Error(getTok().getLoc(),
837 "expected section directive before assembly directive");
842 /// \brief Throw away the rest of the line for testing purposes.
843 void AsmParser::eatToEndOfStatement() {
844 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
848 if (Lexer.is(AsmToken::EndOfStatement))
852 StringRef AsmParser::parseStringToEndOfStatement() {
853 const char *Start = getTok().getLoc().getPointer();
855 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
858 const char *End = getTok().getLoc().getPointer();
859 return StringRef(Start, End - Start);
862 StringRef AsmParser::parseStringToComma() {
863 const char *Start = getTok().getLoc().getPointer();
865 while (Lexer.isNot(AsmToken::EndOfStatement) &&
866 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
869 const char *End = getTok().getLoc().getPointer();
870 return StringRef(Start, End - Start);
873 /// \brief Parse a paren expression and return it.
874 /// NOTE: This assumes the leading '(' has already been consumed.
876 /// parenexpr ::= expr)
878 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
879 if (parseExpression(Res))
881 if (Lexer.isNot(AsmToken::RParen))
882 return TokError("expected ')' in parentheses expression");
883 EndLoc = Lexer.getTok().getEndLoc();
888 /// \brief Parse a bracket expression and return it.
889 /// NOTE: This assumes the leading '[' has already been consumed.
891 /// bracketexpr ::= expr]
893 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
894 if (parseExpression(Res))
896 EndLoc = getTok().getEndLoc();
897 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
902 /// \brief Parse a primary expression and return it.
903 /// primaryexpr ::= (parenexpr
904 /// primaryexpr ::= symbol
905 /// primaryexpr ::= number
906 /// primaryexpr ::= '.'
907 /// primaryexpr ::= ~,+,- primaryexpr
908 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
909 SMLoc FirstTokenLoc = getLexer().getLoc();
910 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
911 switch (FirstTokenKind) {
913 return TokError("unknown token in expression");
914 // If we have an error assume that we've already handled it.
915 case AsmToken::Error:
917 case AsmToken::Exclaim:
918 Lex(); // Eat the operator.
919 if (parsePrimaryExpr(Res, EndLoc))
921 Res = MCUnaryExpr::createLNot(Res, getContext());
923 case AsmToken::Dollar:
925 case AsmToken::String:
926 case AsmToken::Identifier: {
927 StringRef Identifier;
928 if (parseIdentifier(Identifier)) {
929 // We may have failed but $ may be a valid token.
930 if (getTok().is(AsmToken::Dollar)) {
931 if (Lexer.getMAI().getDollarIsPC()) {
933 // This is a '$' reference, which references the current PC. Emit a
934 // temporary label to the streamer and refer to it.
935 MCSymbol *Sym = Ctx.createTempSymbol();
937 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
939 EndLoc = FirstTokenLoc;
942 return Error(FirstTokenLoc, "invalid token in expression");
945 // Parse symbol variant
946 std::pair<StringRef, StringRef> Split;
947 if (!MAI.useParensForSymbolVariant()) {
948 if (FirstTokenKind == AsmToken::String) {
949 if (Lexer.is(AsmToken::At)) {
951 SMLoc AtLoc = getLexer().getLoc();
953 if (parseIdentifier(VName))
954 return Error(AtLoc, "expected symbol variant after '@'");
956 Split = std::make_pair(Identifier, VName);
959 Split = Identifier.split('@');
961 } else if (Lexer.is(AsmToken::LParen)) {
964 parseIdentifier(VName);
966 if (parseToken(AsmToken::RParen,
967 "unexpected token in variant, expected ')'"))
969 Split = std::make_pair(Identifier, VName);
972 EndLoc = SMLoc::getFromPointer(Identifier.end());
974 // This is a symbol reference.
975 StringRef SymbolName = Identifier;
976 if (SymbolName.empty())
979 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
981 // Lookup the symbol variant if used.
982 if (Split.second.size()) {
983 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
984 if (Variant != MCSymbolRefExpr::VK_Invalid) {
985 SymbolName = Split.first;
986 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
987 Variant = MCSymbolRefExpr::VK_None;
989 return Error(SMLoc::getFromPointer(Split.second.begin()),
990 "invalid variant '" + Split.second + "'");
994 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
996 // If this is an absolute variable reference, substitute it now to preserve
997 // semantics in the face of reassignment.
998 if (Sym->isVariable() &&
999 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
1001 return Error(EndLoc, "unexpected modifier on variable reference");
1003 Res = Sym->getVariableValue(/*SetUsed*/ false);
1007 // Otherwise create a symbol ref.
1008 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
1011 case AsmToken::BigNum:
1012 return TokError("literal value out of range for directive");
1013 case AsmToken::Integer: {
1014 SMLoc Loc = getTok().getLoc();
1015 int64_t IntVal = getTok().getIntVal();
1016 Res = MCConstantExpr::create(IntVal, getContext());
1017 EndLoc = Lexer.getTok().getEndLoc();
1018 Lex(); // Eat token.
1019 // Look for 'b' or 'f' following an Integer as a directional label
1020 if (Lexer.getKind() == AsmToken::Identifier) {
1021 StringRef IDVal = getTok().getString();
1022 // Lookup the symbol variant if used.
1023 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1024 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1025 if (Split.first.size() != IDVal.size()) {
1026 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
1027 if (Variant == MCSymbolRefExpr::VK_Invalid)
1028 return TokError("invalid variant '" + Split.second + "'");
1029 IDVal = Split.first;
1031 if (IDVal == "f" || IDVal == "b") {
1033 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
1034 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
1035 if (IDVal == "b" && Sym->isUndefined())
1036 return Error(Loc, "directional label undefined");
1037 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
1038 EndLoc = Lexer.getTok().getEndLoc();
1039 Lex(); // Eat identifier.
1044 case AsmToken::Real: {
1045 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
1046 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
1047 Res = MCConstantExpr::create(IntVal, getContext());
1048 EndLoc = Lexer.getTok().getEndLoc();
1049 Lex(); // Eat token.
1052 case AsmToken::Dot: {
1053 // This is a '.' reference, which references the current PC. Emit a
1054 // temporary label to the streamer and refer to it.
1055 MCSymbol *Sym = Ctx.createTempSymbol();
1057 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
1058 EndLoc = Lexer.getTok().getEndLoc();
1059 Lex(); // Eat identifier.
1062 case AsmToken::LParen:
1063 Lex(); // Eat the '('.
1064 return parseParenExpr(Res, EndLoc);
1065 case AsmToken::LBrac:
1066 if (!PlatformParser->HasBracketExpressions())
1067 return TokError("brackets expression not supported on this target");
1068 Lex(); // Eat the '['.
1069 return parseBracketExpr(Res, EndLoc);
1070 case AsmToken::Minus:
1071 Lex(); // Eat the operator.
1072 if (parsePrimaryExpr(Res, EndLoc))
1074 Res = MCUnaryExpr::createMinus(Res, getContext());
1076 case AsmToken::Plus:
1077 Lex(); // Eat the operator.
1078 if (parsePrimaryExpr(Res, EndLoc))
1080 Res = MCUnaryExpr::createPlus(Res, getContext());
1082 case AsmToken::Tilde:
1083 Lex(); // Eat the operator.
1084 if (parsePrimaryExpr(Res, EndLoc))
1086 Res = MCUnaryExpr::createNot(Res, getContext());
1088 // MIPS unary expression operators. The lexer won't generate these tokens if
1089 // MCAsmInfo::HasMipsExpressions is false for the target.
1090 case AsmToken::PercentCall16:
1091 case AsmToken::PercentCall_Hi:
1092 case AsmToken::PercentCall_Lo:
1093 case AsmToken::PercentDtprel_Hi:
1094 case AsmToken::PercentDtprel_Lo:
1095 case AsmToken::PercentGot:
1096 case AsmToken::PercentGot_Disp:
1097 case AsmToken::PercentGot_Hi:
1098 case AsmToken::PercentGot_Lo:
1099 case AsmToken::PercentGot_Ofst:
1100 case AsmToken::PercentGot_Page:
1101 case AsmToken::PercentGottprel:
1102 case AsmToken::PercentGp_Rel:
1103 case AsmToken::PercentHi:
1104 case AsmToken::PercentHigher:
1105 case AsmToken::PercentHighest:
1106 case AsmToken::PercentLo:
1107 case AsmToken::PercentNeg:
1108 case AsmToken::PercentPcrel_Hi:
1109 case AsmToken::PercentPcrel_Lo:
1110 case AsmToken::PercentTlsgd:
1111 case AsmToken::PercentTlsldm:
1112 case AsmToken::PercentTprel_Hi:
1113 case AsmToken::PercentTprel_Lo:
1114 Lex(); // Eat the operator.
1115 if (Lexer.isNot(AsmToken::LParen))
1116 return TokError("expected '(' after operator");
1117 Lex(); // Eat the operator.
1118 if (parseExpression(Res, EndLoc))
1120 if (Lexer.isNot(AsmToken::RParen))
1121 return TokError("expected ')'");
1122 Lex(); // Eat the operator.
1123 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1128 bool AsmParser::parseExpression(const MCExpr *&Res) {
1130 return parseExpression(Res, EndLoc);
1134 AsmParser::applyModifierToExpr(const MCExpr *E,
1135 MCSymbolRefExpr::VariantKind Variant) {
1136 // Ask the target implementation about this expression first.
1137 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1140 // Recurse over the given expression, rebuilding it to apply the given variant
1141 // if there is exactly one symbol.
1142 switch (E->getKind()) {
1143 case MCExpr::Target:
1144 case MCExpr::Constant:
1147 case MCExpr::SymbolRef: {
1148 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1150 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
1151 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1152 "' (already modified)");
1156 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
1159 case MCExpr::Unary: {
1160 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
1161 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
1164 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
1167 case MCExpr::Binary: {
1168 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1169 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1170 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1180 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1184 llvm_unreachable("Invalid expression kind!");
1187 /// \brief Parse an expression and return it.
1189 /// expr ::= expr &&,|| expr -> lowest.
1190 /// expr ::= expr |,^,&,! expr
1191 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1192 /// expr ::= expr <<,>> expr
1193 /// expr ::= expr +,- expr
1194 /// expr ::= expr *,/,% expr -> highest.
1195 /// expr ::= primaryexpr
1197 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1198 // Parse the expression.
1200 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1203 // As a special case, we support 'a op b @ modifier' by rewriting the
1204 // expression to include the modifier. This is inefficient, but in general we
1205 // expect users to use 'a@modifier op b'.
1206 if (Lexer.getKind() == AsmToken::At) {
1209 if (Lexer.isNot(AsmToken::Identifier))
1210 return TokError("unexpected symbol modifier following '@'");
1212 MCSymbolRefExpr::VariantKind Variant =
1213 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1214 if (Variant == MCSymbolRefExpr::VK_Invalid)
1215 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1217 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1219 return TokError("invalid modifier '" + getTok().getIdentifier() +
1220 "' (no symbols present)");
1227 // Try to constant fold it up front, if possible.
1229 if (Res->evaluateAsAbsolute(Value))
1230 Res = MCConstantExpr::create(Value, getContext());
1235 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1237 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1240 bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1242 if (parseParenExpr(Res, EndLoc))
1245 for (; ParenDepth > 0; --ParenDepth) {
1246 if (parseBinOpRHS(1, Res, EndLoc))
1249 // We don't Lex() the last RParen.
1250 // This is the same behavior as parseParenExpression().
1251 if (ParenDepth - 1 > 0) {
1252 EndLoc = getTok().getEndLoc();
1253 if (parseToken(AsmToken::RParen,
1254 "expected ')' in parentheses expression"))
1261 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1264 SMLoc StartLoc = Lexer.getLoc();
1265 if (parseExpression(Expr))
1268 if (!Expr->evaluateAsAbsolute(Res))
1269 return Error(StartLoc, "expected absolute expression");
1274 static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1275 MCBinaryExpr::Opcode &Kind,
1276 bool ShouldUseLogicalShr) {
1279 return 0; // not a binop.
1281 // Lowest Precedence: &&, ||
1282 case AsmToken::AmpAmp:
1283 Kind = MCBinaryExpr::LAnd;
1285 case AsmToken::PipePipe:
1286 Kind = MCBinaryExpr::LOr;
1289 // Low Precedence: |, &, ^
1291 // FIXME: gas seems to support '!' as an infix operator?
1292 case AsmToken::Pipe:
1293 Kind = MCBinaryExpr::Or;
1295 case AsmToken::Caret:
1296 Kind = MCBinaryExpr::Xor;
1299 Kind = MCBinaryExpr::And;
1302 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1303 case AsmToken::EqualEqual:
1304 Kind = MCBinaryExpr::EQ;
1306 case AsmToken::ExclaimEqual:
1307 case AsmToken::LessGreater:
1308 Kind = MCBinaryExpr::NE;
1310 case AsmToken::Less:
1311 Kind = MCBinaryExpr::LT;
1313 case AsmToken::LessEqual:
1314 Kind = MCBinaryExpr::LTE;
1316 case AsmToken::Greater:
1317 Kind = MCBinaryExpr::GT;
1319 case AsmToken::GreaterEqual:
1320 Kind = MCBinaryExpr::GTE;
1323 // Intermediate Precedence: <<, >>
1324 case AsmToken::LessLess:
1325 Kind = MCBinaryExpr::Shl;
1327 case AsmToken::GreaterGreater:
1328 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1331 // High Intermediate Precedence: +, -
1332 case AsmToken::Plus:
1333 Kind = MCBinaryExpr::Add;
1335 case AsmToken::Minus:
1336 Kind = MCBinaryExpr::Sub;
1339 // Highest Precedence: *, /, %
1340 case AsmToken::Star:
1341 Kind = MCBinaryExpr::Mul;
1343 case AsmToken::Slash:
1344 Kind = MCBinaryExpr::Div;
1346 case AsmToken::Percent:
1347 Kind = MCBinaryExpr::Mod;
1352 static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1353 MCBinaryExpr::Opcode &Kind,
1354 bool ShouldUseLogicalShr) {
1357 return 0; // not a binop.
1359 // Lowest Precedence: &&, ||
1360 case AsmToken::AmpAmp:
1361 Kind = MCBinaryExpr::LAnd;
1363 case AsmToken::PipePipe:
1364 Kind = MCBinaryExpr::LOr;
1367 // Low Precedence: ==, !=, <>, <, <=, >, >=
1368 case AsmToken::EqualEqual:
1369 Kind = MCBinaryExpr::EQ;
1371 case AsmToken::ExclaimEqual:
1372 case AsmToken::LessGreater:
1373 Kind = MCBinaryExpr::NE;
1375 case AsmToken::Less:
1376 Kind = MCBinaryExpr::LT;
1378 case AsmToken::LessEqual:
1379 Kind = MCBinaryExpr::LTE;
1381 case AsmToken::Greater:
1382 Kind = MCBinaryExpr::GT;
1384 case AsmToken::GreaterEqual:
1385 Kind = MCBinaryExpr::GTE;
1388 // Low Intermediate Precedence: +, -
1389 case AsmToken::Plus:
1390 Kind = MCBinaryExpr::Add;
1392 case AsmToken::Minus:
1393 Kind = MCBinaryExpr::Sub;
1396 // High Intermediate Precedence: |, &, ^
1398 // FIXME: gas seems to support '!' as an infix operator?
1399 case AsmToken::Pipe:
1400 Kind = MCBinaryExpr::Or;
1402 case AsmToken::Caret:
1403 Kind = MCBinaryExpr::Xor;
1406 Kind = MCBinaryExpr::And;
1409 // Highest Precedence: *, /, %, <<, >>
1410 case AsmToken::Star:
1411 Kind = MCBinaryExpr::Mul;
1413 case AsmToken::Slash:
1414 Kind = MCBinaryExpr::Div;
1416 case AsmToken::Percent:
1417 Kind = MCBinaryExpr::Mod;
1419 case AsmToken::LessLess:
1420 Kind = MCBinaryExpr::Shl;
1422 case AsmToken::GreaterGreater:
1423 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1428 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1429 MCBinaryExpr::Opcode &Kind) {
1430 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1431 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1432 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1435 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1436 /// Res contains the LHS of the expression on input.
1437 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1440 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1441 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1443 // If the next token is lower precedence than we are allowed to eat, return
1444 // successfully with what we ate already.
1445 if (TokPrec < Precedence)
1450 // Eat the next primary expression.
1452 if (parsePrimaryExpr(RHS, EndLoc))
1455 // If BinOp binds less tightly with RHS than the operator after RHS, let
1456 // the pending operator take RHS as its LHS.
1457 MCBinaryExpr::Opcode Dummy;
1458 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1459 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1462 // Merge LHS and RHS according to operator.
1463 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
1468 /// ::= EndOfStatement
1469 /// ::= Label* Directive ...Operands... EndOfStatement
1470 /// ::= Label* Identifier OperandList* EndOfStatement
1471 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1472 MCAsmParserSemaCallback *SI) {
1473 assert(!hasPendingError() && "parseStatement started with pending error");
1474 // Eat initial spaces and comments
1475 while (Lexer.is(AsmToken::Space))
1477 if (Lexer.is(AsmToken::EndOfStatement)) {
1478 // if this is a line comment we can drop it safely
1479 if (getTok().getString().front() == '\r' ||
1480 getTok().getString().front() == '\n')
1485 if (Lexer.is(AsmToken::Hash)) {
1486 // Seeing a hash here means that it was an end-of-line comment in
1487 // an asm syntax where hash's are not comment and the previous
1488 // statement parser did not check the end of statement. Relex as
1490 StringRef CommentStr = parseStringToEndOfStatement();
1492 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1495 // Statements always start with an identifier.
1496 AsmToken ID = getTok();
1497 SMLoc IDLoc = ID.getLoc();
1499 int64_t LocalLabelVal = -1;
1500 if (Lexer.is(AsmToken::HashDirective))
1501 return parseCppHashLineFilenameComment(IDLoc);
1502 // Allow an integer followed by a ':' as a directional local label.
1503 if (Lexer.is(AsmToken::Integer)) {
1504 LocalLabelVal = getTok().getIntVal();
1505 if (LocalLabelVal < 0) {
1506 if (!TheCondState.Ignore) {
1507 Lex(); // always eat a token
1508 return Error(IDLoc, "unexpected token at start of statement");
1512 IDVal = getTok().getString();
1513 Lex(); // Consume the integer token to be used as an identifier token.
1514 if (Lexer.getKind() != AsmToken::Colon) {
1515 if (!TheCondState.Ignore) {
1516 Lex(); // always eat a token
1517 return Error(IDLoc, "unexpected token at start of statement");
1521 } else if (Lexer.is(AsmToken::Dot)) {
1522 // Treat '.' as a valid identifier in this context.
1525 } else if (Lexer.is(AsmToken::LCurly)) {
1526 // Treat '{' as a valid identifier in this context.
1530 } else if (Lexer.is(AsmToken::RCurly)) {
1531 // Treat '}' as a valid identifier in this context.
1534 } else if (parseIdentifier(IDVal)) {
1535 if (!TheCondState.Ignore) {
1536 Lex(); // always eat a token
1537 return Error(IDLoc, "unexpected token at start of statement");
1542 // Handle conditional assembly here before checking for skipping. We
1543 // have to do this so that .endif isn't skipped in a ".if 0" block for
1545 StringMap<DirectiveKind>::const_iterator DirKindIt =
1546 DirectiveKindMap.find(IDVal);
1547 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1549 : DirKindIt->getValue();
1560 return parseDirectiveIf(IDLoc, DirKind);
1562 return parseDirectiveIfb(IDLoc, true);
1564 return parseDirectiveIfb(IDLoc, false);
1566 return parseDirectiveIfc(IDLoc, true);
1568 return parseDirectiveIfeqs(IDLoc, true);
1570 return parseDirectiveIfc(IDLoc, false);
1572 return parseDirectiveIfeqs(IDLoc, false);
1574 return parseDirectiveIfdef(IDLoc, true);
1577 return parseDirectiveIfdef(IDLoc, false);
1579 return parseDirectiveElseIf(IDLoc);
1581 return parseDirectiveElse(IDLoc);
1583 return parseDirectiveEndIf(IDLoc);
1586 // Ignore the statement if in the middle of inactive conditional
1588 if (TheCondState.Ignore) {
1589 eatToEndOfStatement();
1593 // FIXME: Recurse on local labels?
1595 // See what kind of statement we have.
1596 switch (Lexer.getKind()) {
1597 case AsmToken::Colon: {
1598 if (!getTargetParser().isLabel(ID))
1600 if (checkForValidSection())
1603 // identifier ':' -> Label.
1606 // Diagnose attempt to use '.' as a label.
1608 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1610 // Diagnose attempt to use a variable as a label.
1612 // FIXME: Diagnostics. Note the location of the definition as a label.
1613 // FIXME: This doesn't diagnose assignment to a symbol which has been
1614 // implicitly marked as external.
1616 if (LocalLabelVal == -1) {
1617 if (ParsingInlineAsm && SI) {
1618 StringRef RewrittenLabel =
1619 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1620 assert(RewrittenLabel.size() &&
1621 "We should have an internal name here.");
1622 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1624 IDVal = RewrittenLabel;
1626 Sym = getContext().getOrCreateSymbol(IDVal);
1628 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1630 Sym->redefineIfPossible();
1632 if (!Sym->isUndefined() || Sym->isVariable())
1633 return Error(IDLoc, "invalid symbol redefinition");
1635 // End of Labels should be treated as end of line for lexing
1636 // purposes but that information is not available to the Lexer who
1637 // does not understand Labels. This may cause us to see a Hash
1638 // here instead of a preprocessor line comment.
1639 if (getTok().is(AsmToken::Hash)) {
1640 StringRef CommentStr = parseStringToEndOfStatement();
1642 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1645 // Consume any end of statement token, if present, to avoid spurious
1646 // AddBlankLine calls().
1647 if (getTok().is(AsmToken::EndOfStatement)) {
1652 if (!ParsingInlineAsm)
1655 // If we are generating dwarf for assembly source files then gather the
1656 // info to make a dwarf label entry for this label if needed.
1657 if (getContext().getGenDwarfForAssembly())
1658 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1661 getTargetParser().onLabelParsed(Sym);
1666 case AsmToken::Equal:
1667 if (!getTargetParser().equalIsAsmAssignment())
1669 // identifier '=' ... -> assignment statement
1672 return parseAssignment(IDVal, true);
1674 default: // Normal instruction or directive.
1678 // If macros are enabled, check to see if this is a macro instantiation.
1679 if (areMacrosEnabled())
1680 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1681 return handleMacroEntry(M, IDLoc);
1684 // Otherwise, we have a normal instruction or directive.
1686 // Directives start with "."
1687 if (IDVal[0] == '.' && IDVal != ".") {
1688 // There are several entities interested in parsing directives:
1690 // 1. The target-specific assembly parser. Some directives are target
1691 // specific or may potentially behave differently on certain targets.
1692 // 2. Asm parser extensions. For example, platform-specific parsers
1693 // (like the ELF parser) register themselves as extensions.
1694 // 3. The generic directive parser implemented by this class. These are
1695 // all the directives that behave in a target and platform independent
1696 // manner, or at least have a default behavior that's shared between
1697 // all targets and platforms.
1699 getTargetParser().flushPendingInstructions(getStreamer());
1701 SMLoc StartTokLoc = getTok().getLoc();
1702 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1704 if (hasPendingError())
1706 // Currently the return value should be true if we are
1707 // uninterested but as this is at odds with the standard parsing
1708 // convention (return true = error) we have instances of a parsed
1709 // directive that fails returning true as an error. Catch these
1710 // cases as best as possible errors here.
1711 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1713 // Return if we did some parsing or believe we succeeded.
1714 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
1717 // Next, check the extension directive map to see if any extension has
1718 // registered itself to parse this directive.
1719 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1720 ExtensionDirectiveMap.lookup(IDVal);
1722 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1724 // Finally, if no one else is interested in this directive, it must be
1725 // generic and familiar to this class.
1731 return parseDirectiveSet(IDVal, true);
1733 return parseDirectiveSet(IDVal, false);
1735 return parseDirectiveAscii(IDVal, false);
1738 return parseDirectiveAscii(IDVal, true);
1741 return parseDirectiveValue(IDVal, 1);
1747 return parseDirectiveValue(IDVal, 2);
1752 return parseDirectiveValue(IDVal, 4);
1755 return parseDirectiveValue(IDVal, 8);
1757 return parseDirectiveValue(IDVal,
1758 getContext().getAsmInfo()->getPointerSize());
1760 return parseDirectiveOctaValue(IDVal);
1764 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
1767 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
1769 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1770 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1773 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1774 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1777 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1779 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1781 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1783 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1785 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1787 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1789 return parseDirectiveOrg();
1791 return parseDirectiveFill();
1793 return parseDirectiveZero();
1795 eatToEndOfStatement(); // .extern is the default, ignore it.
1799 return parseDirectiveSymbolAttribute(MCSA_Global);
1800 case DK_LAZY_REFERENCE:
1801 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1802 case DK_NO_DEAD_STRIP:
1803 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1804 case DK_SYMBOL_RESOLVER:
1805 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1806 case DK_PRIVATE_EXTERN:
1807 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1809 return parseDirectiveSymbolAttribute(MCSA_Reference);
1810 case DK_WEAK_DEFINITION:
1811 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1812 case DK_WEAK_REFERENCE:
1813 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1814 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1815 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1818 return parseDirectiveComm(/*IsLocal=*/false);
1820 return parseDirectiveComm(/*IsLocal=*/true);
1822 return parseDirectiveAbort();
1824 return parseDirectiveInclude();
1826 return parseDirectiveIncbin();
1829 return TokError(Twine(IDVal) +
1830 " not currently supported for this target");
1832 return parseDirectiveRept(IDLoc, IDVal);
1834 return parseDirectiveIrp(IDLoc);
1836 return parseDirectiveIrpc(IDLoc);
1838 return parseDirectiveEndr(IDLoc);
1839 case DK_BUNDLE_ALIGN_MODE:
1840 return parseDirectiveBundleAlignMode();
1841 case DK_BUNDLE_LOCK:
1842 return parseDirectiveBundleLock();
1843 case DK_BUNDLE_UNLOCK:
1844 return parseDirectiveBundleUnlock();
1846 return parseDirectiveLEB128(true);
1848 return parseDirectiveLEB128(false);
1851 return parseDirectiveSpace(IDVal);
1853 return parseDirectiveFile(IDLoc);
1855 return parseDirectiveLine();
1857 return parseDirectiveLoc();
1859 return parseDirectiveStabs();
1861 return parseDirectiveCVFile();
1863 return parseDirectiveCVFuncId();
1864 case DK_CV_INLINE_SITE_ID:
1865 return parseDirectiveCVInlineSiteId();
1867 return parseDirectiveCVLoc();
1868 case DK_CV_LINETABLE:
1869 return parseDirectiveCVLinetable();
1870 case DK_CV_INLINE_LINETABLE:
1871 return parseDirectiveCVInlineLinetable();
1872 case DK_CV_DEF_RANGE:
1873 return parseDirectiveCVDefRange();
1874 case DK_CV_STRINGTABLE:
1875 return parseDirectiveCVStringTable();
1876 case DK_CV_FILECHECKSUMS:
1877 return parseDirectiveCVFileChecksums();
1878 case DK_CFI_SECTIONS:
1879 return parseDirectiveCFISections();
1880 case DK_CFI_STARTPROC:
1881 return parseDirectiveCFIStartProc();
1882 case DK_CFI_ENDPROC:
1883 return parseDirectiveCFIEndProc();
1884 case DK_CFI_DEF_CFA:
1885 return parseDirectiveCFIDefCfa(IDLoc);
1886 case DK_CFI_DEF_CFA_OFFSET:
1887 return parseDirectiveCFIDefCfaOffset();
1888 case DK_CFI_ADJUST_CFA_OFFSET:
1889 return parseDirectiveCFIAdjustCfaOffset();
1890 case DK_CFI_DEF_CFA_REGISTER:
1891 return parseDirectiveCFIDefCfaRegister(IDLoc);
1893 return parseDirectiveCFIOffset(IDLoc);
1894 case DK_CFI_REL_OFFSET:
1895 return parseDirectiveCFIRelOffset(IDLoc);
1896 case DK_CFI_PERSONALITY:
1897 return parseDirectiveCFIPersonalityOrLsda(true);
1899 return parseDirectiveCFIPersonalityOrLsda(false);
1900 case DK_CFI_REMEMBER_STATE:
1901 return parseDirectiveCFIRememberState();
1902 case DK_CFI_RESTORE_STATE:
1903 return parseDirectiveCFIRestoreState();
1904 case DK_CFI_SAME_VALUE:
1905 return parseDirectiveCFISameValue(IDLoc);
1906 case DK_CFI_RESTORE:
1907 return parseDirectiveCFIRestore(IDLoc);
1909 return parseDirectiveCFIEscape();
1910 case DK_CFI_SIGNAL_FRAME:
1911 return parseDirectiveCFISignalFrame();
1912 case DK_CFI_UNDEFINED:
1913 return parseDirectiveCFIUndefined(IDLoc);
1914 case DK_CFI_REGISTER:
1915 return parseDirectiveCFIRegister(IDLoc);
1916 case DK_CFI_WINDOW_SAVE:
1917 return parseDirectiveCFIWindowSave();
1920 return parseDirectiveMacrosOnOff(IDVal);
1922 return parseDirectiveMacro(IDLoc);
1924 return parseDirectiveExitMacro(IDVal);
1927 return parseDirectiveEndMacro(IDVal);
1929 return parseDirectivePurgeMacro(IDLoc);
1931 return parseDirectiveEnd(IDLoc);
1933 return parseDirectiveError(IDLoc, false);
1935 return parseDirectiveError(IDLoc, true);
1937 return parseDirectiveWarning(IDLoc);
1939 return parseDirectiveReloc(IDLoc);
1942 return parseDirectiveDCB(IDVal, 2);
1944 return parseDirectiveDCB(IDVal, 1);
1946 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
1948 return parseDirectiveDCB(IDVal, 4);
1950 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
1953 return TokError(Twine(IDVal) +
1954 " not currently supported for this target");
1957 return parseDirectiveDS(IDVal, 2);
1959 return parseDirectiveDS(IDVal, 1);
1961 return parseDirectiveDS(IDVal, 8);
1964 return parseDirectiveDS(IDVal, 4);
1967 return parseDirectiveDS(IDVal, 12);
1970 return Error(IDLoc, "unknown directive");
1973 // __asm _emit or __asm __emit
1974 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1975 IDVal == "_EMIT" || IDVal == "__EMIT"))
1976 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1979 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1980 return parseDirectiveMSAlign(IDLoc, Info);
1982 if (ParsingInlineAsm && (IDVal == "even"))
1983 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
1984 if (checkForValidSection())
1987 // Canonicalize the opcode to lower case.
1988 std::string OpcodeStr = IDVal.lower();
1989 ParseInstructionInfo IInfo(Info.AsmRewrites);
1990 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
1991 Info.ParsedOperands);
1992 Info.ParseError = ParseHadError;
1994 // Dump the parsed representation, if requested.
1995 if (getShowParsedOperands()) {
1996 SmallString<256> Str;
1997 raw_svector_ostream OS(Str);
1998 OS << "parsed instruction: [";
1999 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
2002 Info.ParsedOperands[i]->print(OS);
2006 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
2009 // Fail even if ParseInstruction erroneously returns false.
2010 if (hasPendingError() || ParseHadError)
2013 // If we are generating dwarf for the current section then generate a .loc
2014 // directive for the instruction.
2015 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
2016 getContext().getGenDwarfSectionSyms().count(
2017 getStreamer().getCurrentSectionOnly())) {
2019 if (ActiveMacros.empty())
2020 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2022 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2023 ActiveMacros.front()->ExitBuffer);
2025 // If we previously parsed a cpp hash file line comment then make sure the
2026 // current Dwarf File is for the CppHashFilename if not then emit the
2027 // Dwarf File table for it and adjust the line number for the .loc.
2028 if (CppHashInfo.Filename.size()) {
2029 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
2030 0, StringRef(), CppHashInfo.Filename);
2031 getContext().setGenDwarfFileNumber(FileNumber);
2033 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2034 // cache with the different Loc from the call above we save the last
2035 // info we queried here with SrcMgr.FindLineNumber().
2036 unsigned CppHashLocLineNo;
2037 if (LastQueryIDLoc == CppHashInfo.Loc &&
2038 LastQueryBuffer == CppHashInfo.Buf)
2039 CppHashLocLineNo = LastQueryLine;
2042 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
2043 LastQueryLine = CppHashLocLineNo;
2044 LastQueryIDLoc = CppHashInfo.Loc;
2045 LastQueryBuffer = CppHashInfo.Buf;
2047 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
2050 getStreamer().EmitDwarfLocDirective(
2051 getContext().getGenDwarfFileNumber(), Line, 0,
2052 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2056 // If parsing succeeded, match the instruction.
2057 if (!ParseHadError) {
2059 if (getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
2060 Info.ParsedOperands, Out,
2061 ErrorInfo, ParsingInlineAsm))
2067 // Parse and erase curly braces marking block start/end
2069 AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2070 // Identify curly brace marking block start/end
2071 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2074 SMLoc StartLoc = Lexer.getLoc();
2075 Lex(); // Eat the brace
2076 if (Lexer.is(AsmToken::EndOfStatement))
2077 Lex(); // Eat EndOfStatement following the brace
2079 // Erase the block start/end brace from the output asm string
2080 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2081 StartLoc.getPointer());
2085 /// parseCppHashLineFilenameComment as this:
2086 /// ::= # number "filename"
2087 bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
2088 Lex(); // Eat the hash token.
2089 // Lexer only ever emits HashDirective if it fully formed if it's
2090 // done the checking already so this is an internal error.
2091 assert(getTok().is(AsmToken::Integer) &&
2092 "Lexing Cpp line comment: Expected Integer");
2093 int64_t LineNumber = getTok().getIntVal();
2095 assert(getTok().is(AsmToken::String) &&
2096 "Lexing Cpp line comment: Expected String");
2097 StringRef Filename = getTok().getString();
2100 // Get rid of the enclosing quotes.
2101 Filename = Filename.substr(1, Filename.size() - 2);
2103 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
2104 CppHashInfo.Loc = L;
2105 CppHashInfo.Filename = Filename;
2106 CppHashInfo.LineNumber = LineNumber;
2107 CppHashInfo.Buf = CurBuffer;
2111 /// \brief will use the last parsed cpp hash line filename comment
2112 /// for the Filename and LineNo if any in the diagnostic.
2113 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
2114 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
2115 raw_ostream &OS = errs();
2117 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
2118 SMLoc DiagLoc = Diag.getLoc();
2119 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2120 unsigned CppHashBuf =
2121 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
2123 // Like SourceMgr::printMessage() we need to print the include stack if any
2124 // before printing the message.
2125 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2126 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2127 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
2128 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2129 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
2132 // If we have not parsed a cpp hash line filename comment or the source
2133 // manager changed or buffer changed (like in a nested include) then just
2134 // print the normal diagnostic using its Filename and LineNo.
2135 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
2136 DiagBuf != CppHashBuf) {
2137 if (Parser->SavedDiagHandler)
2138 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2140 Diag.print(nullptr, OS);
2144 // Use the CppHashFilename and calculate a line number based on the
2145 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2146 // for the diagnostic.
2147 const std::string &Filename = Parser->CppHashInfo.Filename;
2149 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2150 int CppHashLocLineNo =
2151 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
2153 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
2155 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2156 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
2157 Diag.getLineContents(), Diag.getRanges());
2159 if (Parser->SavedDiagHandler)
2160 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2162 NewDiag.print(nullptr, OS);
2165 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2166 // difference being that that function accepts '@' as part of identifiers and
2167 // we can't do that. AsmLexer.cpp should probably be changed to handle
2168 // '@' as a special case when needed.
2169 static bool isIdentifierChar(char c) {
2170 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2174 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
2175 ArrayRef<MCAsmMacroParameter> Parameters,
2176 ArrayRef<MCAsmMacroArgument> A,
2177 bool EnableAtPseudoVariable, SMLoc L) {
2178 unsigned NParameters = Parameters.size();
2179 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
2180 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
2181 return Error(L, "Wrong number of arguments");
2183 // A macro without parameters is handled differently on Darwin:
2184 // gas accepts no arguments and does no substitutions
2185 while (!Body.empty()) {
2186 // Scan for the next substitution.
2187 std::size_t End = Body.size(), Pos = 0;
2188 for (; Pos != End; ++Pos) {
2189 // Check for a substitution or escape.
2190 if (IsDarwin && !NParameters) {
2191 // This macro has no parameters, look for $0, $1, etc.
2192 if (Body[Pos] != '$' || Pos + 1 == End)
2195 char Next = Body[Pos + 1];
2196 if (Next == '$' || Next == 'n' ||
2197 isdigit(static_cast<unsigned char>(Next)))
2200 // This macro has parameters, look for \foo, \bar, etc.
2201 if (Body[Pos] == '\\' && Pos + 1 != End)
2207 OS << Body.slice(0, Pos);
2209 // Check if we reached the end.
2213 if (IsDarwin && !NParameters) {
2214 switch (Body[Pos + 1]) {
2220 // $n => number of arguments
2225 // $[0-9] => argument
2227 // Missing arguments are ignored.
2228 unsigned Index = Body[Pos + 1] - '0';
2229 if (Index >= A.size())
2232 // Otherwise substitute with the token values, with spaces eliminated.
2233 for (const AsmToken &Token : A[Index])
2234 OS << Token.getString();
2240 unsigned I = Pos + 1;
2242 // Check for the \@ pseudo-variable.
2243 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
2246 while (isIdentifierChar(Body[I]) && I + 1 != End)
2249 const char *Begin = Body.data() + Pos + 1;
2250 StringRef Argument(Begin, I - (Pos + 1));
2253 if (Argument == "@") {
2254 OS << NumOfMacroInstantiations;
2257 for (; Index < NParameters; ++Index)
2258 if (Parameters[Index].Name == Argument)
2261 if (Index == NParameters) {
2262 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2265 OS << '\\' << Argument;
2269 bool VarargParameter = HasVararg && Index == (NParameters - 1);
2270 for (const AsmToken &Token : A[Index])
2271 // We expect no quotes around the string's contents when
2272 // parsing for varargs.
2273 if (Token.getKind() != AsmToken::String || VarargParameter)
2274 OS << Token.getString();
2276 OS << Token.getStringContents();
2278 Pos += 1 + Argument.size();
2282 // Update the scan point.
2283 Body = Body.substr(Pos);
2289 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
2290 size_t CondStackDepth)
2291 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
2292 CondStackDepth(CondStackDepth) {}
2294 static bool isOperator(AsmToken::TokenKind kind) {
2298 case AsmToken::Plus:
2299 case AsmToken::Minus:
2300 case AsmToken::Tilde:
2301 case AsmToken::Slash:
2302 case AsmToken::Star:
2304 case AsmToken::Equal:
2305 case AsmToken::EqualEqual:
2306 case AsmToken::Pipe:
2307 case AsmToken::PipePipe:
2308 case AsmToken::Caret:
2310 case AsmToken::AmpAmp:
2311 case AsmToken::Exclaim:
2312 case AsmToken::ExclaimEqual:
2313 case AsmToken::Less:
2314 case AsmToken::LessEqual:
2315 case AsmToken::LessLess:
2316 case AsmToken::LessGreater:
2317 case AsmToken::Greater:
2318 case AsmToken::GreaterEqual:
2319 case AsmToken::GreaterGreater:
2326 class AsmLexerSkipSpaceRAII {
2328 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2329 Lexer.setSkipSpace(SkipSpace);
2332 ~AsmLexerSkipSpaceRAII() {
2333 Lexer.setSkipSpace(true);
2340 } // end anonymous namespace
2342 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2345 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2346 StringRef Str = parseStringToEndOfStatement();
2347 MA.emplace_back(AsmToken::String, Str);
2352 unsigned ParenLevel = 0;
2354 // Darwin doesn't use spaces to delmit arguments.
2355 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
2361 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
2362 return TokError("unexpected token in macro instantiation");
2364 if (ParenLevel == 0) {
2366 if (Lexer.is(AsmToken::Comma))
2369 if (Lexer.is(AsmToken::Space)) {
2371 Lexer.Lex(); // Eat spaces
2374 // Spaces can delimit parameters, but could also be part an expression.
2375 // If the token after a space is an operator, add the token and the next
2376 // one into this argument
2378 if (isOperator(Lexer.getKind())) {
2379 MA.push_back(getTok());
2382 // Whitespace after an operator can be ignored.
2383 if (Lexer.is(AsmToken::Space))
2393 // handleMacroEntry relies on not advancing the lexer here
2394 // to be able to fill in the remaining default parameter values
2395 if (Lexer.is(AsmToken::EndOfStatement))
2398 // Adjust the current parentheses level.
2399 if (Lexer.is(AsmToken::LParen))
2401 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2404 // Append the token to the current argument list.
2405 MA.push_back(getTok());
2409 if (ParenLevel != 0)
2410 return TokError("unbalanced parentheses in macro argument");
2414 // Parse the macro instantiation arguments.
2415 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2416 MCAsmMacroArguments &A) {
2417 const unsigned NParameters = M ? M->Parameters.size() : 0;
2418 bool NamedParametersFound = false;
2419 SmallVector<SMLoc, 4> FALocs;
2421 A.resize(NParameters);
2422 FALocs.resize(NParameters);
2424 // Parse two kinds of macro invocations:
2425 // - macros defined without any parameters accept an arbitrary number of them
2426 // - macros defined with parameters accept at most that many of them
2427 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2428 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2430 SMLoc IDLoc = Lexer.getLoc();
2431 MCAsmMacroParameter FA;
2433 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2434 if (parseIdentifier(FA.Name))
2435 return Error(IDLoc, "invalid argument identifier for formal argument");
2437 if (Lexer.isNot(AsmToken::Equal))
2438 return TokError("expected '=' after formal parameter identifier");
2442 NamedParametersFound = true;
2445 if (NamedParametersFound && FA.Name.empty())
2446 return Error(IDLoc, "cannot mix positional and keyword arguments");
2448 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2449 if (parseMacroArgument(FA.Value, Vararg))
2452 unsigned PI = Parameter;
2453 if (!FA.Name.empty()) {
2455 for (FAI = 0; FAI < NParameters; ++FAI)
2456 if (M->Parameters[FAI].Name == FA.Name)
2459 if (FAI >= NParameters) {
2460 assert(M && "expected macro to be defined");
2461 return Error(IDLoc, "parameter named '" + FA.Name +
2462 "' does not exist for macro '" + M->Name + "'");
2467 if (!FA.Value.empty()) {
2472 if (FALocs.size() <= PI)
2473 FALocs.resize(PI + 1);
2475 FALocs[PI] = Lexer.getLoc();
2478 // At the end of the statement, fill in remaining arguments that have
2479 // default values. If there aren't any, then the next argument is
2480 // required but missing
2481 if (Lexer.is(AsmToken::EndOfStatement)) {
2482 bool Failure = false;
2483 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2484 if (A[FAI].empty()) {
2485 if (M->Parameters[FAI].Required) {
2486 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2487 "missing value for required parameter "
2488 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2492 if (!M->Parameters[FAI].Value.empty())
2493 A[FAI] = M->Parameters[FAI].Value;
2499 if (Lexer.is(AsmToken::Comma))
2503 return TokError("too many positional arguments");
2506 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2507 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2508 return (I == MacroMap.end()) ? nullptr : &I->getValue();
2511 void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2512 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2515 void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2517 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2518 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2519 // eliminate this, although we should protect against infinite loops.
2520 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2521 if (ActiveMacros.size() == MaxNestingDepth) {
2522 std::ostringstream MaxNestingDepthError;
2523 MaxNestingDepthError << "macros cannot be nested more than "
2524 << MaxNestingDepth << " levels deep."
2525 << " Use -asm-macro-max-nesting-depth to increase "
2527 return TokError(MaxNestingDepthError.str());
2530 MCAsmMacroArguments A;
2531 if (parseMacroArguments(M, A))
2534 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2535 // to hold the macro body with substitutions.
2536 SmallString<256> Buf;
2537 StringRef Body = M->Body;
2538 raw_svector_ostream OS(Buf);
2540 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2543 // We include the .endmacro in the buffer as our cue to exit the macro
2545 OS << ".endmacro\n";
2547 std::unique_ptr<MemoryBuffer> Instantiation =
2548 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2550 // Create the macro instantiation object and add to the current macro
2551 // instantiation stack.
2552 MacroInstantiation *MI = new MacroInstantiation(
2553 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2554 ActiveMacros.push_back(MI);
2556 ++NumOfMacroInstantiations;
2558 // Jump to the macro instantiation and prime the lexer.
2559 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2560 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2566 void AsmParser::handleMacroExit() {
2567 // Jump to the EndOfStatement we should return to, and consume it.
2568 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2571 // Pop the instantiation entry.
2572 delete ActiveMacros.back();
2573 ActiveMacros.pop_back();
2576 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2579 const MCExpr *Value;
2580 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2585 // In the case where we parse an expression starting with a '.', we will
2586 // not generate an error, nor will we create a symbol. In this case we
2587 // should just return out.
2591 // Do the assignment.
2592 Out.EmitAssignment(Sym, Value);
2594 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2599 /// parseIdentifier:
2602 bool AsmParser::parseIdentifier(StringRef &Res) {
2603 // The assembler has relaxed rules for accepting identifiers, in particular we
2604 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2605 // separate tokens. At this level, we have already lexed so we cannot (currently)
2606 // handle this as a context dependent token, instead we detect adjacent tokens
2607 // and return the combined identifier.
2608 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2609 SMLoc PrefixLoc = getLexer().getLoc();
2611 // Consume the prefix character, and check for a following identifier.
2614 Lexer.peekTokens(Buf, false);
2616 if (Buf[0].isNot(AsmToken::Identifier))
2619 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2620 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
2624 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
2625 // Construct the joined identifier and consume the token.
2627 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2628 Lex(); // Parser Lex to maintain invariants.
2632 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2635 Res = getTok().getIdentifier();
2637 Lex(); // Consume the identifier token.
2642 /// parseDirectiveSet:
2643 /// ::= .equ identifier ',' expression
2644 /// ::= .equiv identifier ',' expression
2645 /// ::= .set identifier ',' expression
2646 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2648 if (check(parseIdentifier(Name), "expected identifier") ||
2649 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2650 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2654 bool AsmParser::parseEscapedString(std::string &Data) {
2655 if (check(getTok().isNot(AsmToken::String), "expected string"))
2659 StringRef Str = getTok().getStringContents();
2660 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2661 if (Str[i] != '\\') {
2666 // Recognize escaped characters. Note that this escape semantics currently
2667 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2670 return TokError("unexpected backslash at end of string");
2672 // Recognize octal sequences.
2673 if ((unsigned)(Str[i] - '0') <= 7) {
2674 // Consume up to three octal characters.
2675 unsigned Value = Str[i] - '0';
2677 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2679 Value = Value * 8 + (Str[i] - '0');
2681 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2683 Value = Value * 8 + (Str[i] - '0');
2688 return TokError("invalid octal escape sequence (out of range)");
2690 Data += (unsigned char)Value;
2694 // Otherwise recognize individual escapes.
2697 // Just reject invalid escape sequences for now.
2698 return TokError("invalid escape sequence (unrecognized character)");
2700 case 'b': Data += '\b'; break;
2701 case 'f': Data += '\f'; break;
2702 case 'n': Data += '\n'; break;
2703 case 'r': Data += '\r'; break;
2704 case 't': Data += '\t'; break;
2705 case '"': Data += '"'; break;
2706 case '\\': Data += '\\'; break;
2714 /// parseDirectiveAscii:
2715 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2716 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2717 auto parseOp = [&]() -> bool {
2719 if (checkForValidSection() || parseEscapedString(Data))
2721 getStreamer().EmitBytes(Data);
2723 getStreamer().EmitBytes(StringRef("\0", 1));
2727 if (parseMany(parseOp))
2728 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2732 /// parseDirectiveReloc
2733 /// ::= .reloc expression , identifier [ , expression ]
2734 bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2735 const MCExpr *Offset;
2736 const MCExpr *Expr = nullptr;
2738 SMLoc OffsetLoc = Lexer.getTok().getLoc();
2739 int64_t OffsetValue;
2740 // We can only deal with constant expressions at the moment.
2742 if (parseExpression(Offset))
2745 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2746 "expression is not a constant value") ||
2747 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2748 parseToken(AsmToken::Comma, "expected comma") ||
2749 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2752 SMLoc NameLoc = Lexer.getTok().getLoc();
2753 StringRef Name = Lexer.getTok().getIdentifier();
2756 if (Lexer.is(AsmToken::Comma)) {
2758 SMLoc ExprLoc = Lexer.getLoc();
2759 if (parseExpression(Expr))
2763 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2764 return Error(ExprLoc, "expression must be relocatable");
2767 if (parseToken(AsmToken::EndOfStatement,
2768 "unexpected token in .reloc directive"))
2771 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2772 return Error(NameLoc, "unknown relocation name");
2777 /// parseDirectiveValue
2778 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2779 bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2780 auto parseOp = [&]() -> bool {
2781 const MCExpr *Value;
2782 SMLoc ExprLoc = getLexer().getLoc();
2783 if (checkForValidSection() || parseExpression(Value))
2785 // Special case constant expressions to match code generator.
2786 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2787 assert(Size <= 8 && "Invalid size");
2788 uint64_t IntValue = MCE->getValue();
2789 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2790 return Error(ExprLoc, "out of range literal value");
2791 getStreamer().EmitIntValue(IntValue, Size);
2793 getStreamer().EmitValue(Value, Size, ExprLoc);
2797 if (parseMany(parseOp))
2798 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2802 /// ParseDirectiveOctaValue
2803 /// ::= .octa [ hexconstant (, hexconstant)* ]
2805 bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2806 auto parseOp = [&]() -> bool {
2807 if (checkForValidSection())
2809 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
2810 return TokError("unknown token in expression");
2811 SMLoc ExprLoc = getTok().getLoc();
2812 APInt IntValue = getTok().getAPIntVal();
2815 if (!IntValue.isIntN(128))
2816 return Error(ExprLoc, "out of range literal value");
2817 if (!IntValue.isIntN(64)) {
2818 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2819 lo = IntValue.getLoBits(64).getZExtValue();
2822 lo = IntValue.getZExtValue();
2824 if (MAI.isLittleEndian()) {
2825 getStreamer().EmitIntValue(lo, 8);
2826 getStreamer().EmitIntValue(hi, 8);
2828 getStreamer().EmitIntValue(hi, 8);
2829 getStreamer().EmitIntValue(lo, 8);
2834 if (parseMany(parseOp))
2835 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2839 bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
2840 // We don't truly support arithmetic on floating point expressions, so we
2841 // have to manually parse unary prefixes.
2843 if (getLexer().is(AsmToken::Minus)) {
2846 } else if (getLexer().is(AsmToken::Plus))
2849 if (Lexer.is(AsmToken::Error))
2850 return TokError(Lexer.getErr());
2851 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2852 Lexer.isNot(AsmToken::Identifier))
2853 return TokError("unexpected token in directive");
2855 // Convert to an APFloat.
2856 APFloat Value(Semantics);
2857 StringRef IDVal = getTok().getString();
2858 if (getLexer().is(AsmToken::Identifier)) {
2859 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2860 Value = APFloat::getInf(Semantics);
2861 else if (!IDVal.compare_lower("nan"))
2862 Value = APFloat::getNaN(Semantics, false, ~0);
2864 return TokError("invalid floating point literal");
2865 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2866 APFloat::opInvalidOp)
2867 return TokError("invalid floating point literal");
2871 // Consume the numeric token.
2874 Res = Value.bitcastToAPInt();
2879 /// parseDirectiveRealValue
2880 /// ::= (.single | .double) [ expression (, expression)* ]
2881 bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
2882 const fltSemantics &Semantics) {
2883 auto parseOp = [&]() -> bool {
2885 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
2887 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2888 AsInt.getBitWidth() / 8);
2892 if (parseMany(parseOp))
2893 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2897 /// parseDirectiveZero
2898 /// ::= .zero expression
2899 bool AsmParser::parseDirectiveZero() {
2900 SMLoc NumBytesLoc = Lexer.getLoc();
2901 const MCExpr *NumBytes;
2902 if (checkForValidSection() || parseExpression(NumBytes))
2906 if (getLexer().is(AsmToken::Comma)) {
2908 if (parseAbsoluteExpression(Val))
2912 if (parseToken(AsmToken::EndOfStatement,
2913 "unexpected token in '.zero' directive"))
2915 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
2920 /// parseDirectiveFill
2921 /// ::= .fill expression [ , expression [ , expression ] ]
2922 bool AsmParser::parseDirectiveFill() {
2923 SMLoc NumValuesLoc = Lexer.getLoc();
2924 const MCExpr *NumValues;
2925 if (checkForValidSection() || parseExpression(NumValues))
2928 int64_t FillSize = 1;
2929 int64_t FillExpr = 0;
2931 SMLoc SizeLoc, ExprLoc;
2933 if (parseOptionalToken(AsmToken::Comma)) {
2934 SizeLoc = getTok().getLoc();
2935 if (parseAbsoluteExpression(FillSize))
2937 if (parseOptionalToken(AsmToken::Comma)) {
2938 ExprLoc = getTok().getLoc();
2939 if (parseAbsoluteExpression(FillExpr))
2943 if (parseToken(AsmToken::EndOfStatement,
2944 "unexpected token in '.fill' directive"))
2948 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2952 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2956 if (!isUInt<32>(FillExpr) && FillSize > 4)
2957 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2959 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
2964 /// parseDirectiveOrg
2965 /// ::= .org expression [ , expression ]
2966 bool AsmParser::parseDirectiveOrg() {
2967 const MCExpr *Offset;
2968 SMLoc OffsetLoc = Lexer.getLoc();
2969 if (checkForValidSection() || parseExpression(Offset))
2972 // Parse optional fill expression.
2973 int64_t FillExpr = 0;
2974 if (parseOptionalToken(AsmToken::Comma))
2975 if (parseAbsoluteExpression(FillExpr))
2976 return addErrorSuffix(" in '.org' directive");
2977 if (parseToken(AsmToken::EndOfStatement))
2978 return addErrorSuffix(" in '.org' directive");
2980 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
2984 /// parseDirectiveAlign
2985 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2986 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2987 SMLoc AlignmentLoc = getLexer().getLoc();
2990 bool HasFillExpr = false;
2991 int64_t FillExpr = 0;
2992 int64_t MaxBytesToFill = 0;
2994 auto parseAlign = [&]() -> bool {
2995 if (checkForValidSection() || parseAbsoluteExpression(Alignment))
2997 if (parseOptionalToken(AsmToken::Comma)) {
2998 // The fill expression can be omitted while specifying a maximum number of
2999 // alignment bytes, e.g:
3001 if (getTok().isNot(AsmToken::Comma)) {
3003 if (parseAbsoluteExpression(FillExpr))
3006 if (parseOptionalToken(AsmToken::Comma))
3007 if (parseTokenLoc(MaxBytesLoc) ||
3008 parseAbsoluteExpression(MaxBytesToFill))
3011 return parseToken(AsmToken::EndOfStatement);
3015 return addErrorSuffix(" in directive");
3017 // Always emit an alignment here even if we thrown an error.
3018 bool ReturnVal = false;
3020 // Compute alignment in bytes.
3022 // FIXME: Diagnose overflow.
3023 if (Alignment >= 32) {
3024 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
3028 Alignment = 1ULL << Alignment;
3030 // Reject alignments that aren't either a power of two or zero,
3031 // for gas compatibility. Alignment of zero is silently rounded
3035 if (!isPowerOf2_64(Alignment))
3036 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
3039 // Diagnose non-sensical max bytes to align.
3040 if (MaxBytesLoc.isValid()) {
3041 if (MaxBytesToFill < 1) {
3042 ReturnVal |= Error(MaxBytesLoc,
3043 "alignment directive can never be satisfied in this "
3044 "many bytes, ignoring maximum bytes expression");
3048 if (MaxBytesToFill >= Alignment) {
3049 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
3055 // Check whether we should use optimal code alignment for this .align
3057 const MCSection *Section = getStreamer().getCurrentSectionOnly();
3058 assert(Section && "must have section to emit alignment");
3059 bool UseCodeAlign = Section->UseCodeAlign();
3060 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3061 ValueSize == 1 && UseCodeAlign) {
3062 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
3064 // FIXME: Target specific behavior about how the "extra" bytes are filled.
3065 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3072 /// parseDirectiveFile
3073 /// ::= .file [number] filename
3074 /// ::= .file number directory filename
3075 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
3076 // FIXME: I'm not sure what this is.
3077 int64_t FileNumber = -1;
3078 SMLoc FileNumberLoc = getLexer().getLoc();
3079 if (getLexer().is(AsmToken::Integer)) {
3080 FileNumber = getTok().getIntVal();
3084 return TokError("file number less than one");
3087 std::string Path = getTok().getString();
3089 // Usually the directory and filename together, otherwise just the directory.
3090 // Allow the strings to have escaped octal character sequence.
3091 if (check(getTok().isNot(AsmToken::String),
3092 "unexpected token in '.file' directive") ||
3093 parseEscapedString(Path))
3096 StringRef Directory;
3098 std::string FilenameData;
3099 if (getLexer().is(AsmToken::String)) {
3100 if (check(FileNumber == -1,
3101 "explicit path specified, but no file number") ||
3102 parseEscapedString(FilenameData))
3104 Filename = FilenameData;
3110 if (parseToken(AsmToken::EndOfStatement,
3111 "unexpected token in '.file' directive"))
3114 if (FileNumber == -1)
3115 getStreamer().EmitFileDirective(Filename);
3117 // If there is -g option as well as debug info from directive file,
3118 // we turn off -g option, directly use the existing debug info instead.
3119 if (getContext().getGenDwarfForAssembly())
3120 getContext().setGenDwarfForAssembly(false);
3121 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
3123 return Error(FileNumberLoc, "file number already allocated");
3129 /// parseDirectiveLine
3130 /// ::= .line [number]
3131 bool AsmParser::parseDirectiveLine() {
3133 if (getLexer().is(AsmToken::Integer)) {
3134 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3137 // FIXME: Do something with the .line.
3139 if (parseToken(AsmToken::EndOfStatement,
3140 "unexpected token in '.line' directive"))
3146 /// parseDirectiveLoc
3147 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3148 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3149 /// The first number is a file number, must have been previously assigned with
3150 /// a .file directive, the second number is the line number and optionally the
3151 /// third number is a column position (zero if not specified). The remaining
3152 /// optional items are .loc sub-directives.
3153 bool AsmParser::parseDirectiveLoc() {
3154 int64_t FileNumber = 0, LineNumber = 0;
3155 SMLoc Loc = getTok().getLoc();
3156 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3157 check(FileNumber < 1, Loc,
3158 "file number less than one in '.loc' directive") ||
3159 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3160 "unassigned file number in '.loc' directive"))
3164 if (getLexer().is(AsmToken::Integer)) {
3165 LineNumber = getTok().getIntVal();
3167 return TokError("line number less than zero in '.loc' directive");
3171 int64_t ColumnPos = 0;
3172 if (getLexer().is(AsmToken::Integer)) {
3173 ColumnPos = getTok().getIntVal();
3175 return TokError("column position less than zero in '.loc' directive");
3179 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3181 int64_t Discriminator = 0;
3183 auto parseLocOp = [&]() -> bool {
3185 SMLoc Loc = getTok().getLoc();
3186 if (parseIdentifier(Name))
3187 return TokError("unexpected token in '.loc' directive");
3189 if (Name == "basic_block")
3190 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3191 else if (Name == "prologue_end")
3192 Flags |= DWARF2_FLAG_PROLOGUE_END;
3193 else if (Name == "epilogue_begin")
3194 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3195 else if (Name == "is_stmt") {
3196 Loc = getTok().getLoc();
3197 const MCExpr *Value;
3198 if (parseExpression(Value))
3200 // The expression must be the constant 0 or 1.
3201 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3202 int Value = MCE->getValue();
3204 Flags &= ~DWARF2_FLAG_IS_STMT;
3205 else if (Value == 1)
3206 Flags |= DWARF2_FLAG_IS_STMT;
3208 return Error(Loc, "is_stmt value not 0 or 1");
3210 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3212 } else if (Name == "isa") {
3213 Loc = getTok().getLoc();
3214 const MCExpr *Value;
3215 if (parseExpression(Value))
3217 // The expression must be a constant greater or equal to 0.
3218 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3219 int Value = MCE->getValue();
3221 return Error(Loc, "isa number less than zero");
3224 return Error(Loc, "isa number not a constant value");
3226 } else if (Name == "discriminator") {
3227 if (parseAbsoluteExpression(Discriminator))
3230 return Error(Loc, "unknown sub-directive in '.loc' directive");
3235 if (parseMany(parseLocOp, false /*hasComma*/))
3238 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3239 Isa, Discriminator, StringRef());
3244 /// parseDirectiveStabs
3245 /// ::= .stabs string, number, number, number
3246 bool AsmParser::parseDirectiveStabs() {
3247 return TokError("unsupported directive '.stabs'");
3250 /// parseDirectiveCVFile
3251 /// ::= .cv_file number filename
3252 bool AsmParser::parseDirectiveCVFile() {
3253 SMLoc FileNumberLoc = getTok().getLoc();
3255 std::string Filename;
3257 if (parseIntToken(FileNumber,
3258 "expected file number in '.cv_file' directive") ||
3259 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3260 check(getTok().isNot(AsmToken::String),
3261 "unexpected token in '.cv_file' directive") ||
3262 // Usually directory and filename are together, otherwise just
3263 // directory. Allow the strings to have escaped octal character sequence.
3264 parseEscapedString(Filename) ||
3265 parseToken(AsmToken::EndOfStatement,
3266 "unexpected token in '.cv_file' directive"))
3269 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename))
3270 return Error(FileNumberLoc, "file number already allocated");
3275 bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3276 StringRef DirectiveName) {
3278 return parseTokenLoc(Loc) ||
3279 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3281 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3282 "expected function id within range [0, UINT_MAX)");
3285 bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3287 return parseTokenLoc(Loc) ||
3288 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3290 check(FileNumber < 1, Loc, "file number less than one in '" +
3291 DirectiveName + "' directive") ||
3292 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3293 "unassigned file number in '" + DirectiveName + "' directive");
3296 /// parseDirectiveCVFuncId
3297 /// ::= .cv_func_id FunctionId
3299 /// Introduces a function ID that can be used with .cv_loc.
3300 bool AsmParser::parseDirectiveCVFuncId() {
3301 SMLoc FunctionIdLoc = getTok().getLoc();
3304 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3305 parseToken(AsmToken::EndOfStatement,
3306 "unexpected token in '.cv_func_id' directive"))
3309 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
3310 return Error(FunctionIdLoc, "function id already allocated");
3315 /// parseDirectiveCVInlineSiteId
3316 /// ::= .cv_inline_site_id FunctionId
3318 /// "inlined_at" IAFile IALine [IACol]
3320 /// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3321 /// at" source location information for use in the line table of the caller,
3322 /// whether the caller is a real function or another inlined call site.
3323 bool AsmParser::parseDirectiveCVInlineSiteId() {
3324 SMLoc FunctionIdLoc = getTok().getLoc();
3332 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3336 if (check((getLexer().isNot(AsmToken::Identifier) ||
3337 getTok().getIdentifier() != "within"),
3338 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3343 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3347 if (check((getLexer().isNot(AsmToken::Identifier) ||
3348 getTok().getIdentifier() != "inlined_at"),
3349 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3355 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3356 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3360 if (getLexer().is(AsmToken::Integer)) {
3361 IACol = getTok().getIntVal();
3365 if (parseToken(AsmToken::EndOfStatement,
3366 "unexpected token in '.cv_inline_site_id' directive"))
3369 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3370 IALine, IACol, FunctionIdLoc))
3371 return Error(FunctionIdLoc, "function id already allocated");
3376 /// parseDirectiveCVLoc
3377 /// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3379 /// The first number is a file number, must have been previously assigned with
3380 /// a .file directive, the second number is the line number and optionally the
3381 /// third number is a column position (zero if not specified). The remaining
3382 /// optional items are .loc sub-directives.
3383 bool AsmParser::parseDirectiveCVLoc() {
3384 SMLoc DirectiveLoc = getTok().getLoc();
3386 int64_t FunctionId, FileNumber;
3387 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3388 parseCVFileId(FileNumber, ".cv_loc"))
3391 int64_t LineNumber = 0;
3392 if (getLexer().is(AsmToken::Integer)) {
3393 LineNumber = getTok().getIntVal();
3395 return TokError("line number less than zero in '.cv_loc' directive");
3399 int64_t ColumnPos = 0;
3400 if (getLexer().is(AsmToken::Integer)) {
3401 ColumnPos = getTok().getIntVal();
3403 return TokError("column position less than zero in '.cv_loc' directive");
3407 bool PrologueEnd = false;
3408 uint64_t IsStmt = 0;
3410 auto parseOp = [&]() -> bool {
3412 SMLoc Loc = getTok().getLoc();
3413 if (parseIdentifier(Name))
3414 return TokError("unexpected token in '.cv_loc' directive");
3415 if (Name == "prologue_end")
3417 else if (Name == "is_stmt") {
3418 Loc = getTok().getLoc();
3419 const MCExpr *Value;
3420 if (parseExpression(Value))
3422 // The expression must be the constant 0 or 1.
3424 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3425 IsStmt = MCE->getValue();
3428 return Error(Loc, "is_stmt value not 0 or 1");
3430 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3435 if (parseMany(parseOp, false /*hasComma*/))
3438 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
3439 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3444 /// parseDirectiveCVLinetable
3445 /// ::= .cv_linetable FunctionId, FnStart, FnEnd
3446 bool AsmParser::parseDirectiveCVLinetable() {
3448 StringRef FnStartName, FnEndName;
3449 SMLoc Loc = getTok().getLoc();
3450 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
3451 parseToken(AsmToken::Comma,
3452 "unexpected token in '.cv_linetable' directive") ||
3453 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3454 "expected identifier in directive") ||
3455 parseToken(AsmToken::Comma,
3456 "unexpected token in '.cv_linetable' directive") ||
3457 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3458 "expected identifier in directive"))
3461 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3462 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3464 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3468 /// parseDirectiveCVInlineLinetable
3469 /// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
3470 bool AsmParser::parseDirectiveCVInlineLinetable() {
3471 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3472 StringRef FnStartName, FnEndName;
3473 SMLoc Loc = getTok().getLoc();
3474 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
3475 parseTokenLoc(Loc) ||
3478 "expected SourceField in '.cv_inline_linetable' directive") ||
3479 check(SourceFileId <= 0, Loc,
3480 "File id less than zero in '.cv_inline_linetable' directive") ||
3481 parseTokenLoc(Loc) ||
3484 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3485 check(SourceLineNum < 0, Loc,
3486 "Line number less than zero in '.cv_inline_linetable' directive") ||
3487 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3488 "expected identifier in directive") ||
3489 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3490 "expected identifier in directive"))
3493 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3496 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3497 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3498 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3499 SourceLineNum, FnStartSym,
3504 /// parseDirectiveCVDefRange
3505 /// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3506 bool AsmParser::parseDirectiveCVDefRange() {
3508 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3509 while (getLexer().is(AsmToken::Identifier)) {
3510 Loc = getLexer().getLoc();
3511 StringRef GapStartName;
3512 if (parseIdentifier(GapStartName))
3513 return Error(Loc, "expected identifier in directive");
3514 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3516 Loc = getLexer().getLoc();
3517 StringRef GapEndName;
3518 if (parseIdentifier(GapEndName))
3519 return Error(Loc, "expected identifier in directive");
3520 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3522 Ranges.push_back({GapStartSym, GapEndSym});
3525 std::string FixedSizePortion;
3526 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3527 parseEscapedString(FixedSizePortion))
3530 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3534 /// parseDirectiveCVStringTable
3535 /// ::= .cv_stringtable
3536 bool AsmParser::parseDirectiveCVStringTable() {
3537 getStreamer().EmitCVStringTableDirective();
3541 /// parseDirectiveCVFileChecksums
3542 /// ::= .cv_filechecksums
3543 bool AsmParser::parseDirectiveCVFileChecksums() {
3544 getStreamer().EmitCVFileChecksumsDirective();
3548 /// parseDirectiveCFISections
3549 /// ::= .cfi_sections section [, section]
3550 bool AsmParser::parseDirectiveCFISections() {
3555 if (parseIdentifier(Name))
3556 return TokError("Expected an identifier");
3558 if (Name == ".eh_frame")
3560 else if (Name == ".debug_frame")
3563 if (getLexer().is(AsmToken::Comma)) {
3566 if (parseIdentifier(Name))
3567 return TokError("Expected an identifier");
3569 if (Name == ".eh_frame")
3571 else if (Name == ".debug_frame")
3575 getStreamer().EmitCFISections(EH, Debug);
3579 /// parseDirectiveCFIStartProc
3580 /// ::= .cfi_startproc [simple]
3581 bool AsmParser::parseDirectiveCFIStartProc() {
3583 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3584 if (check(parseIdentifier(Simple) || Simple != "simple",
3585 "unexpected token") ||
3586 parseToken(AsmToken::EndOfStatement))
3587 return addErrorSuffix(" in '.cfi_startproc' directive");
3590 getStreamer().EmitCFIStartProc(!Simple.empty());
3594 /// parseDirectiveCFIEndProc
3595 /// ::= .cfi_endproc
3596 bool AsmParser::parseDirectiveCFIEndProc() {
3597 getStreamer().EmitCFIEndProc();
3601 /// \brief parse register name or number.
3602 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
3603 SMLoc DirectiveLoc) {
3606 if (getLexer().isNot(AsmToken::Integer)) {
3607 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3609 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
3611 return parseAbsoluteExpression(Register);
3616 /// parseDirectiveCFIDefCfa
3617 /// ::= .cfi_def_cfa register, offset
3618 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3619 int64_t Register = 0, Offset = 0;
3620 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3621 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3622 parseAbsoluteExpression(Offset))
3625 getStreamer().EmitCFIDefCfa(Register, Offset);
3629 /// parseDirectiveCFIDefCfaOffset
3630 /// ::= .cfi_def_cfa_offset offset
3631 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3633 if (parseAbsoluteExpression(Offset))
3636 getStreamer().EmitCFIDefCfaOffset(Offset);
3640 /// parseDirectiveCFIRegister
3641 /// ::= .cfi_register register, register
3642 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3643 int64_t Register1 = 0, Register2 = 0;
3644 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3645 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3646 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3649 getStreamer().EmitCFIRegister(Register1, Register2);
3653 /// parseDirectiveCFIWindowSave
3654 /// ::= .cfi_window_save
3655 bool AsmParser::parseDirectiveCFIWindowSave() {
3656 getStreamer().EmitCFIWindowSave();
3660 /// parseDirectiveCFIAdjustCfaOffset
3661 /// ::= .cfi_adjust_cfa_offset adjustment
3662 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3663 int64_t Adjustment = 0;
3664 if (parseAbsoluteExpression(Adjustment))
3667 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3671 /// parseDirectiveCFIDefCfaRegister
3672 /// ::= .cfi_def_cfa_register register
3673 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3674 int64_t Register = 0;
3675 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3678 getStreamer().EmitCFIDefCfaRegister(Register);
3682 /// parseDirectiveCFIOffset
3683 /// ::= .cfi_offset register, offset
3684 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3685 int64_t Register = 0;
3688 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3689 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3690 parseAbsoluteExpression(Offset))
3693 getStreamer().EmitCFIOffset(Register, Offset);
3697 /// parseDirectiveCFIRelOffset
3698 /// ::= .cfi_rel_offset register, offset
3699 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3700 int64_t Register = 0, Offset = 0;
3702 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3703 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3704 parseAbsoluteExpression(Offset))
3707 getStreamer().EmitCFIRelOffset(Register, Offset);
3711 static bool isValidEncoding(int64_t Encoding) {
3712 if (Encoding & ~0xff)
3715 if (Encoding == dwarf::DW_EH_PE_omit)
3718 const unsigned Format = Encoding & 0xf;
3719 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3720 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3721 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3722 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3725 const unsigned Application = Encoding & 0x70;
3726 if (Application != dwarf::DW_EH_PE_absptr &&
3727 Application != dwarf::DW_EH_PE_pcrel)
3733 /// parseDirectiveCFIPersonalityOrLsda
3734 /// IsPersonality true for cfi_personality, false for cfi_lsda
3735 /// ::= .cfi_personality encoding, [symbol_name]
3736 /// ::= .cfi_lsda encoding, [symbol_name]
3737 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3738 int64_t Encoding = 0;
3739 if (parseAbsoluteExpression(Encoding))
3741 if (Encoding == dwarf::DW_EH_PE_omit)
3745 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3746 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3747 check(parseIdentifier(Name), "expected identifier in directive"))
3750 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3753 getStreamer().EmitCFIPersonality(Sym, Encoding);
3755 getStreamer().EmitCFILsda(Sym, Encoding);
3759 /// parseDirectiveCFIRememberState
3760 /// ::= .cfi_remember_state
3761 bool AsmParser::parseDirectiveCFIRememberState() {
3762 getStreamer().EmitCFIRememberState();
3766 /// parseDirectiveCFIRestoreState
3767 /// ::= .cfi_remember_state
3768 bool AsmParser::parseDirectiveCFIRestoreState() {
3769 getStreamer().EmitCFIRestoreState();
3773 /// parseDirectiveCFISameValue
3774 /// ::= .cfi_same_value register
3775 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3776 int64_t Register = 0;
3778 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3781 getStreamer().EmitCFISameValue(Register);
3785 /// parseDirectiveCFIRestore
3786 /// ::= .cfi_restore register
3787 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3788 int64_t Register = 0;
3789 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3792 getStreamer().EmitCFIRestore(Register);
3796 /// parseDirectiveCFIEscape
3797 /// ::= .cfi_escape expression[,...]
3798 bool AsmParser::parseDirectiveCFIEscape() {
3801 if (parseAbsoluteExpression(CurrValue))
3804 Values.push_back((uint8_t)CurrValue);
3806 while (getLexer().is(AsmToken::Comma)) {
3809 if (parseAbsoluteExpression(CurrValue))
3812 Values.push_back((uint8_t)CurrValue);
3815 getStreamer().EmitCFIEscape(Values);
3819 /// parseDirectiveCFISignalFrame
3820 /// ::= .cfi_signal_frame
3821 bool AsmParser::parseDirectiveCFISignalFrame() {
3822 if (parseToken(AsmToken::EndOfStatement,
3823 "unexpected token in '.cfi_signal_frame'"))
3826 getStreamer().EmitCFISignalFrame();
3830 /// parseDirectiveCFIUndefined
3831 /// ::= .cfi_undefined register
3832 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3833 int64_t Register = 0;
3835 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3838 getStreamer().EmitCFIUndefined(Register);
3842 /// parseDirectiveMacrosOnOff
3845 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3846 if (parseToken(AsmToken::EndOfStatement,
3847 "unexpected token in '" + Directive + "' directive"))
3850 setMacrosEnabled(Directive == ".macros_on");
3854 /// parseDirectiveMacro
3855 /// ::= .macro name[,] [parameters]
3856 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3858 if (parseIdentifier(Name))
3859 return TokError("expected identifier in '.macro' directive");
3861 if (getLexer().is(AsmToken::Comma))
3864 MCAsmMacroParameters Parameters;
3865 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3867 if (!Parameters.empty() && Parameters.back().Vararg)
3868 return Error(Lexer.getLoc(),
3869 "Vararg parameter '" + Parameters.back().Name +
3870 "' should be last one in the list of parameters.");
3872 MCAsmMacroParameter Parameter;
3873 if (parseIdentifier(Parameter.Name))
3874 return TokError("expected identifier in '.macro' directive");
3876 if (Lexer.is(AsmToken::Colon)) {
3877 Lex(); // consume ':'
3880 StringRef Qualifier;
3882 QualLoc = Lexer.getLoc();
3883 if (parseIdentifier(Qualifier))
3884 return Error(QualLoc, "missing parameter qualifier for "
3885 "'" + Parameter.Name + "' in macro '" + Name + "'");
3887 if (Qualifier == "req")
3888 Parameter.Required = true;
3889 else if (Qualifier == "vararg")
3890 Parameter.Vararg = true;
3892 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3893 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3896 if (getLexer().is(AsmToken::Equal)) {
3901 ParamLoc = Lexer.getLoc();
3902 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3905 if (Parameter.Required)
3906 Warning(ParamLoc, "pointless default value for required parameter "
3907 "'" + Parameter.Name + "' in macro '" + Name + "'");
3910 Parameters.push_back(std::move(Parameter));
3912 if (getLexer().is(AsmToken::Comma))
3916 // Eat just the end of statement.
3919 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
3920 AsmToken EndToken, StartToken = getTok();
3921 unsigned MacroDepth = 0;
3922 // Lex the macro definition.
3924 // Ignore Lexing errors in macros.
3925 while (Lexer.is(AsmToken::Error)) {
3929 // Check whether we have reached the end of the file.
3930 if (getLexer().is(AsmToken::Eof))
3931 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3933 // Otherwise, check whether we have reach the .endmacro.
3934 if (getLexer().is(AsmToken::Identifier)) {
3935 if (getTok().getIdentifier() == ".endm" ||
3936 getTok().getIdentifier() == ".endmacro") {
3937 if (MacroDepth == 0) { // Outermost macro.
3938 EndToken = getTok();
3940 if (getLexer().isNot(AsmToken::EndOfStatement))
3941 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3945 // Otherwise we just found the end of an inner macro.
3948 } else if (getTok().getIdentifier() == ".macro") {
3949 // We allow nested macros. Those aren't instantiated until the outermost
3950 // macro is expanded so just ignore them for now.
3955 // Otherwise, scan til the end of the statement.
3956 eatToEndOfStatement();
3959 if (lookupMacro(Name)) {
3960 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3963 const char *BodyStart = StartToken.getLoc().getPointer();
3964 const char *BodyEnd = EndToken.getLoc().getPointer();
3965 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3966 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3967 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
3971 /// checkForBadMacro
3973 /// With the support added for named parameters there may be code out there that
3974 /// is transitioning from positional parameters. In versions of gas that did
3975 /// not support named parameters they would be ignored on the macro definition.
3976 /// But to support both styles of parameters this is not possible so if a macro
3977 /// definition has named parameters but does not use them and has what appears
3978 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3979 /// warning that the positional parameter found in body which have no effect.
3980 /// Hoping the developer will either remove the named parameters from the macro
3981 /// definition so the positional parameters get used if that was what was
3982 /// intended or change the macro to use the named parameters. It is possible
3983 /// this warning will trigger when the none of the named parameters are used
3984 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3985 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3987 ArrayRef<MCAsmMacroParameter> Parameters) {
3988 // If this macro is not defined with named parameters the warning we are
3989 // checking for here doesn't apply.
3990 unsigned NParameters = Parameters.size();
3991 if (NParameters == 0)
3994 bool NamedParametersFound = false;
3995 bool PositionalParametersFound = false;
3997 // Look at the body of the macro for use of both the named parameters and what
3998 // are likely to be positional parameters. This is what expandMacro() is
3999 // doing when it finds the parameters in the body.
4000 while (!Body.empty()) {
4001 // Scan for the next possible parameter.
4002 std::size_t End = Body.size(), Pos = 0;
4003 for (; Pos != End; ++Pos) {
4004 // Check for a substitution or escape.
4005 // This macro is defined with parameters, look for \foo, \bar, etc.
4006 if (Body[Pos] == '\\' && Pos + 1 != End)
4009 // This macro should have parameters, but look for $0, $1, ..., $n too.
4010 if (Body[Pos] != '$' || Pos + 1 == End)
4012 char Next = Body[Pos + 1];
4013 if (Next == '$' || Next == 'n' ||
4014 isdigit(static_cast<unsigned char>(Next)))
4018 // Check if we reached the end.
4022 if (Body[Pos] == '$') {
4023 switch (Body[Pos + 1]) {
4028 // $n => number of arguments
4030 PositionalParametersFound = true;
4033 // $[0-9] => argument
4035 PositionalParametersFound = true;
4041 unsigned I = Pos + 1;
4042 while (isIdentifierChar(Body[I]) && I + 1 != End)
4045 const char *Begin = Body.data() + Pos + 1;
4046 StringRef Argument(Begin, I - (Pos + 1));
4048 for (; Index < NParameters; ++Index)
4049 if (Parameters[Index].Name == Argument)
4052 if (Index == NParameters) {
4053 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4059 NamedParametersFound = true;
4060 Pos += 1 + Argument.size();
4063 // Update the scan point.
4064 Body = Body.substr(Pos);
4067 if (!NamedParametersFound && PositionalParametersFound)
4068 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4069 "used in macro body, possible positional parameter "
4070 "found in body which will have no effect");
4073 /// parseDirectiveExitMacro
4075 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
4076 if (parseToken(AsmToken::EndOfStatement,
4077 "unexpected token in '" + Directive + "' directive"))
4080 if (!isInsideMacroInstantiation())
4081 return TokError("unexpected '" + Directive + "' in file, "
4082 "no current macro definition");
4084 // Exit all conditionals that are active in the current macro.
4085 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4086 TheCondState = TheCondStack.back();
4087 TheCondStack.pop_back();
4094 /// parseDirectiveEndMacro
4097 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
4098 if (getLexer().isNot(AsmToken::EndOfStatement))
4099 return TokError("unexpected token in '" + Directive + "' directive");
4101 // If we are inside a macro instantiation, terminate the current
4103 if (isInsideMacroInstantiation()) {
4108 // Otherwise, this .endmacro is a stray entry in the file; well formed
4109 // .endmacro directives are handled during the macro definition parsing.
4110 return TokError("unexpected '" + Directive + "' in file, "
4111 "no current macro definition");
4114 /// parseDirectivePurgeMacro
4116 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
4119 if (parseTokenLoc(Loc) ||
4120 check(parseIdentifier(Name), Loc,
4121 "expected identifier in '.purgem' directive") ||
4122 parseToken(AsmToken::EndOfStatement,
4123 "unexpected token in '.purgem' directive"))
4126 if (!lookupMacro(Name))
4127 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4129 undefineMacro(Name);
4133 /// parseDirectiveBundleAlignMode
4134 /// ::= {.bundle_align_mode} expression
4135 bool AsmParser::parseDirectiveBundleAlignMode() {
4136 // Expect a single argument: an expression that evaluates to a constant
4137 // in the inclusive range 0-30.
4138 SMLoc ExprLoc = getLexer().getLoc();
4139 int64_t AlignSizePow2;
4140 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
4141 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4142 "in '.bundle_align_mode' "
4144 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4145 "invalid bundle alignment size (expected between 0 and 30)"))
4148 // Because of AlignSizePow2's verified range we can safely truncate it to
4150 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4154 /// parseDirectiveBundleLock
4155 /// ::= {.bundle_lock} [align_to_end]
4156 bool AsmParser::parseDirectiveBundleLock() {
4157 if (checkForValidSection())
4159 bool AlignToEnd = false;
4162 SMLoc Loc = getTok().getLoc();
4163 const char *kInvalidOptionError =
4164 "invalid option for '.bundle_lock' directive";
4166 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4167 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4168 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
4169 parseToken(AsmToken::EndOfStatement,
4170 "unexpected token after '.bundle_lock' directive option"))
4175 getStreamer().EmitBundleLock(AlignToEnd);
4179 /// parseDirectiveBundleLock
4180 /// ::= {.bundle_lock}
4181 bool AsmParser::parseDirectiveBundleUnlock() {
4182 if (checkForValidSection() ||
4183 parseToken(AsmToken::EndOfStatement,
4184 "unexpected token in '.bundle_unlock' directive"))
4187 getStreamer().EmitBundleUnlock();
4191 /// parseDirectiveSpace
4192 /// ::= (.skip | .space) expression [ , expression ]
4193 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
4195 SMLoc NumBytesLoc = Lexer.getLoc();
4196 const MCExpr *NumBytes;
4197 if (checkForValidSection() || parseExpression(NumBytes))
4200 int64_t FillExpr = 0;
4201 if (parseOptionalToken(AsmToken::Comma))
4202 if (parseAbsoluteExpression(FillExpr))
4203 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4204 if (parseToken(AsmToken::EndOfStatement))
4205 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4207 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
4208 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
4213 /// parseDirectiveDCB
4214 /// ::= .dcb.{b, l, w} expression, expression
4215 bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
4216 SMLoc NumValuesLoc = Lexer.getLoc();
4218 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4221 if (NumValues < 0) {
4222 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4226 if (parseToken(AsmToken::Comma,
4227 "unexpected token in '" + Twine(IDVal) + "' directive"))
4230 const MCExpr *Value;
4231 SMLoc ExprLoc = getLexer().getLoc();
4232 if (parseExpression(Value))
4235 // Special case constant expressions to match code generator.
4236 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4237 assert(Size <= 8 && "Invalid size");
4238 uint64_t IntValue = MCE->getValue();
4239 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4240 return Error(ExprLoc, "literal value out of range for directive");
4241 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4242 getStreamer().EmitIntValue(IntValue, Size);
4244 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4245 getStreamer().EmitValue(Value, Size, ExprLoc);
4248 if (parseToken(AsmToken::EndOfStatement,
4249 "unexpected token in '" + Twine(IDVal) + "' directive"))
4255 /// parseDirectiveRealDCB
4256 /// ::= .dcb.{d, s} expression, expression
4257 bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
4258 SMLoc NumValuesLoc = Lexer.getLoc();
4260 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4263 if (NumValues < 0) {
4264 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4268 if (parseToken(AsmToken::Comma,
4269 "unexpected token in '" + Twine(IDVal) + "' directive"))
4273 if (parseRealValue(Semantics, AsInt))
4276 if (parseToken(AsmToken::EndOfStatement,
4277 "unexpected token in '" + Twine(IDVal) + "' directive"))
4280 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4281 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4282 AsInt.getBitWidth() / 8);
4287 /// parseDirectiveDS
4288 /// ::= .ds.{b, d, l, p, s, w, x} expression
4289 bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
4291 SMLoc NumValuesLoc = Lexer.getLoc();
4293 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4296 if (NumValues < 0) {
4297 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4301 if (parseToken(AsmToken::EndOfStatement,
4302 "unexpected token in '" + Twine(IDVal) + "' directive"))
4305 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4306 getStreamer().emitFill(Size, 0);
4311 /// parseDirectiveLEB128
4312 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
4313 bool AsmParser::parseDirectiveLEB128(bool Signed) {
4314 if (checkForValidSection())
4317 auto parseOp = [&]() -> bool {
4318 const MCExpr *Value;
4319 if (parseExpression(Value))
4322 getStreamer().EmitSLEB128Value(Value);
4324 getStreamer().EmitULEB128Value(Value);
4328 if (parseMany(parseOp))
4329 return addErrorSuffix(" in directive");
4334 /// parseDirectiveSymbolAttribute
4335 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
4336 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
4337 auto parseOp = [&]() -> bool {
4339 SMLoc Loc = getTok().getLoc();
4340 if (parseIdentifier(Name))
4341 return Error(Loc, "expected identifier");
4342 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4344 // Assembler local symbols don't make any sense here. Complain loudly.
4345 if (Sym->isTemporary())
4346 return Error(Loc, "non-local symbol required");
4348 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4349 return Error(Loc, "unable to emit symbol attribute");
4353 if (parseMany(parseOp))
4354 return addErrorSuffix(" in directive");
4358 /// parseDirectiveComm
4359 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
4360 bool AsmParser::parseDirectiveComm(bool IsLocal) {
4361 if (checkForValidSection())
4364 SMLoc IDLoc = getLexer().getLoc();
4366 if (parseIdentifier(Name))
4367 return TokError("expected identifier in directive");
4369 // Handle the identifier as the key symbol.
4370 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4372 if (getLexer().isNot(AsmToken::Comma))
4373 return TokError("unexpected token in directive");
4377 SMLoc SizeLoc = getLexer().getLoc();
4378 if (parseAbsoluteExpression(Size))
4381 int64_t Pow2Alignment = 0;
4382 SMLoc Pow2AlignmentLoc;
4383 if (getLexer().is(AsmToken::Comma)) {
4385 Pow2AlignmentLoc = getLexer().getLoc();
4386 if (parseAbsoluteExpression(Pow2Alignment))
4389 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4390 if (IsLocal && LCOMM == LCOMM::NoAlignment)
4391 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4393 // If this target takes alignments in bytes (not log) validate and convert.
4394 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4395 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
4396 if (!isPowerOf2_64(Pow2Alignment))
4397 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4398 Pow2Alignment = Log2_64(Pow2Alignment);
4402 if (parseToken(AsmToken::EndOfStatement,
4403 "unexpected token in '.comm' or '.lcomm' directive"))
4406 // NOTE: a size of zero for a .comm should create a undefined symbol
4407 // but a size of .lcomm creates a bss symbol of size zero.
4409 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
4410 "be less than zero");
4412 // NOTE: The alignment in the directive is a power of 2 value, the assembler
4413 // may internally end up wanting an alignment in bytes.
4414 // FIXME: Diagnose overflow.
4415 if (Pow2Alignment < 0)
4416 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
4417 "alignment, can't be less than zero");
4419 if (!Sym->isUndefined())
4420 return Error(IDLoc, "invalid symbol redefinition");
4422 // Create the Symbol as a common or local common with Size and Pow2Alignment
4424 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4428 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4432 /// parseDirectiveAbort
4433 /// ::= .abort [... message ...]
4434 bool AsmParser::parseDirectiveAbort() {
4435 // FIXME: Use loc from directive.
4436 SMLoc Loc = getLexer().getLoc();
4438 StringRef Str = parseStringToEndOfStatement();
4439 if (parseToken(AsmToken::EndOfStatement,
4440 "unexpected token in '.abort' directive"))
4444 return Error(Loc, ".abort detected. Assembly stopping.");
4446 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
4447 // FIXME: Actually abort assembly here.
4452 /// parseDirectiveInclude
4453 /// ::= .include "filename"
4454 bool AsmParser::parseDirectiveInclude() {
4455 // Allow the strings to have escaped octal character sequence.
4456 std::string Filename;
4457 SMLoc IncludeLoc = getTok().getLoc();
4459 if (check(getTok().isNot(AsmToken::String),
4460 "expected string in '.include' directive") ||
4461 parseEscapedString(Filename) ||
4462 check(getTok().isNot(AsmToken::EndOfStatement),
4463 "unexpected token in '.include' directive") ||
4464 // Attempt to switch the lexer to the included file before consuming the
4465 // end of statement to avoid losing it when we switch.
4466 check(enterIncludeFile(Filename), IncludeLoc,
4467 "Could not find include file '" + Filename + "'"))
4473 /// parseDirectiveIncbin
4474 /// ::= .incbin "filename" [ , skip [ , count ] ]
4475 bool AsmParser::parseDirectiveIncbin() {
4476 // Allow the strings to have escaped octal character sequence.
4477 std::string Filename;
4478 SMLoc IncbinLoc = getTok().getLoc();
4479 if (check(getTok().isNot(AsmToken::String),
4480 "expected string in '.incbin' directive") ||
4481 parseEscapedString(Filename))
4485 const MCExpr *Count = nullptr;
4486 SMLoc SkipLoc, CountLoc;
4487 if (parseOptionalToken(AsmToken::Comma)) {
4488 // The skip expression can be omitted while specifying the count, e.g:
4489 // .incbin "filename",,4
4490 if (getTok().isNot(AsmToken::Comma)) {
4491 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4494 if (parseOptionalToken(AsmToken::Comma)) {
4495 CountLoc = getTok().getLoc();
4496 if (parseExpression(Count))
4501 if (parseToken(AsmToken::EndOfStatement,
4502 "unexpected token in '.incbin' directive"))
4505 if (check(Skip < 0, SkipLoc, "skip is negative"))
4508 // Attempt to process the included file.
4509 if (processIncbinFile(Filename, Skip, Count, CountLoc))
4510 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
4514 /// parseDirectiveIf
4515 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
4516 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
4517 TheCondStack.push_back(TheCondState);
4518 TheCondState.TheCond = AsmCond::IfCond;
4519 if (TheCondState.Ignore) {
4520 eatToEndOfStatement();
4523 if (parseAbsoluteExpression(ExprValue) ||
4524 parseToken(AsmToken::EndOfStatement,
4525 "unexpected token in '.if' directive"))
4530 llvm_unreachable("unsupported directive");
4535 ExprValue = ExprValue == 0;
4538 ExprValue = ExprValue >= 0;
4541 ExprValue = ExprValue > 0;
4544 ExprValue = ExprValue <= 0;
4547 ExprValue = ExprValue < 0;
4551 TheCondState.CondMet = ExprValue;
4552 TheCondState.Ignore = !TheCondState.CondMet;
4558 /// parseDirectiveIfb
4560 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
4561 TheCondStack.push_back(TheCondState);
4562 TheCondState.TheCond = AsmCond::IfCond;
4564 if (TheCondState.Ignore) {
4565 eatToEndOfStatement();
4567 StringRef Str = parseStringToEndOfStatement();
4569 if (parseToken(AsmToken::EndOfStatement,
4570 "unexpected token in '.ifb' directive"))
4573 TheCondState.CondMet = ExpectBlank == Str.empty();
4574 TheCondState.Ignore = !TheCondState.CondMet;
4580 /// parseDirectiveIfc
4581 /// ::= .ifc string1, string2
4582 /// ::= .ifnc string1, string2
4583 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
4584 TheCondStack.push_back(TheCondState);
4585 TheCondState.TheCond = AsmCond::IfCond;
4587 if (TheCondState.Ignore) {
4588 eatToEndOfStatement();
4590 StringRef Str1 = parseStringToComma();
4592 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4595 StringRef Str2 = parseStringToEndOfStatement();
4597 if (parseToken(AsmToken::EndOfStatement,
4598 "unexpected token in '.ifc' directive"))
4601 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
4602 TheCondState.Ignore = !TheCondState.CondMet;
4608 /// parseDirectiveIfeqs
4609 /// ::= .ifeqs string1, string2
4610 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
4611 if (Lexer.isNot(AsmToken::String)) {
4613 return TokError("expected string parameter for '.ifeqs' directive");
4614 return TokError("expected string parameter for '.ifnes' directive");
4617 StringRef String1 = getTok().getStringContents();
4620 if (Lexer.isNot(AsmToken::Comma)) {
4623 "expected comma after first string for '.ifeqs' directive");
4624 return TokError("expected comma after first string for '.ifnes' directive");
4629 if (Lexer.isNot(AsmToken::String)) {
4631 return TokError("expected string parameter for '.ifeqs' directive");
4632 return TokError("expected string parameter for '.ifnes' directive");
4635 StringRef String2 = getTok().getStringContents();
4638 TheCondStack.push_back(TheCondState);
4639 TheCondState.TheCond = AsmCond::IfCond;
4640 TheCondState.CondMet = ExpectEqual == (String1 == String2);
4641 TheCondState.Ignore = !TheCondState.CondMet;
4646 /// parseDirectiveIfdef
4647 /// ::= .ifdef symbol
4648 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
4650 TheCondStack.push_back(TheCondState);
4651 TheCondState.TheCond = AsmCond::IfCond;
4653 if (TheCondState.Ignore) {
4654 eatToEndOfStatement();
4656 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4657 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4660 MCSymbol *Sym = getContext().lookupSymbol(Name);
4663 TheCondState.CondMet = (Sym && !Sym->isUndefined());
4665 TheCondState.CondMet = (!Sym || Sym->isUndefined());
4666 TheCondState.Ignore = !TheCondState.CondMet;
4672 /// parseDirectiveElseIf
4673 /// ::= .elseif expression
4674 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4675 if (TheCondState.TheCond != AsmCond::IfCond &&
4676 TheCondState.TheCond != AsmCond::ElseIfCond)
4677 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4678 " .if or an .elseif");
4679 TheCondState.TheCond = AsmCond::ElseIfCond;
4681 bool LastIgnoreState = false;
4682 if (!TheCondStack.empty())
4683 LastIgnoreState = TheCondStack.back().Ignore;
4684 if (LastIgnoreState || TheCondState.CondMet) {
4685 TheCondState.Ignore = true;
4686 eatToEndOfStatement();
4689 if (parseAbsoluteExpression(ExprValue))
4692 if (parseToken(AsmToken::EndOfStatement,
4693 "unexpected token in '.elseif' directive"))
4696 TheCondState.CondMet = ExprValue;
4697 TheCondState.Ignore = !TheCondState.CondMet;
4703 /// parseDirectiveElse
4705 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4706 if (parseToken(AsmToken::EndOfStatement,
4707 "unexpected token in '.else' directive"))
4710 if (TheCondState.TheCond != AsmCond::IfCond &&
4711 TheCondState.TheCond != AsmCond::ElseIfCond)
4712 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
4713 " an .if or an .elseif");
4714 TheCondState.TheCond = AsmCond::ElseCond;
4715 bool LastIgnoreState = false;
4716 if (!TheCondStack.empty())
4717 LastIgnoreState = TheCondStack.back().Ignore;
4718 if (LastIgnoreState || TheCondState.CondMet)
4719 TheCondState.Ignore = true;
4721 TheCondState.Ignore = false;
4726 /// parseDirectiveEnd
4728 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4729 if (parseToken(AsmToken::EndOfStatement,
4730 "unexpected token in '.end' directive"))
4733 while (Lexer.isNot(AsmToken::Eof))
4739 /// parseDirectiveError
4741 /// ::= .error [string]
4742 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4743 if (!TheCondStack.empty()) {
4744 if (TheCondStack.back().Ignore) {
4745 eatToEndOfStatement();
4751 return Error(L, ".err encountered");
4753 StringRef Message = ".error directive invoked in source file";
4754 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4755 if (Lexer.isNot(AsmToken::String))
4756 return TokError(".error argument must be a string");
4758 Message = getTok().getStringContents();
4762 return Error(L, Message);
4765 /// parseDirectiveWarning
4766 /// ::= .warning [string]
4767 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4768 if (!TheCondStack.empty()) {
4769 if (TheCondStack.back().Ignore) {
4770 eatToEndOfStatement();
4775 StringRef Message = ".warning directive invoked in source file";
4777 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4778 if (Lexer.isNot(AsmToken::String))
4779 return TokError(".warning argument must be a string");
4781 Message = getTok().getStringContents();
4783 if (parseToken(AsmToken::EndOfStatement,
4784 "expected end of statement in '.warning' directive"))
4788 return Warning(L, Message);
4791 /// parseDirectiveEndIf
4793 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4794 if (parseToken(AsmToken::EndOfStatement,
4795 "unexpected token in '.endif' directive"))
4798 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4799 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
4801 if (!TheCondStack.empty()) {
4802 TheCondState = TheCondStack.back();
4803 TheCondStack.pop_back();
4809 void AsmParser::initializeDirectiveKindMap() {
4810 DirectiveKindMap[".set"] = DK_SET;
4811 DirectiveKindMap[".equ"] = DK_EQU;
4812 DirectiveKindMap[".equiv"] = DK_EQUIV;
4813 DirectiveKindMap[".ascii"] = DK_ASCII;
4814 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4815 DirectiveKindMap[".string"] = DK_STRING;
4816 DirectiveKindMap[".byte"] = DK_BYTE;
4817 DirectiveKindMap[".short"] = DK_SHORT;
4818 DirectiveKindMap[".value"] = DK_VALUE;
4819 DirectiveKindMap[".2byte"] = DK_2BYTE;
4820 DirectiveKindMap[".long"] = DK_LONG;
4821 DirectiveKindMap[".int"] = DK_INT;
4822 DirectiveKindMap[".4byte"] = DK_4BYTE;
4823 DirectiveKindMap[".quad"] = DK_QUAD;
4824 DirectiveKindMap[".8byte"] = DK_8BYTE;
4825 DirectiveKindMap[".octa"] = DK_OCTA;
4826 DirectiveKindMap[".single"] = DK_SINGLE;
4827 DirectiveKindMap[".float"] = DK_FLOAT;
4828 DirectiveKindMap[".double"] = DK_DOUBLE;
4829 DirectiveKindMap[".align"] = DK_ALIGN;
4830 DirectiveKindMap[".align32"] = DK_ALIGN32;
4831 DirectiveKindMap[".balign"] = DK_BALIGN;
4832 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4833 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4834 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4835 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4836 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4837 DirectiveKindMap[".org"] = DK_ORG;
4838 DirectiveKindMap[".fill"] = DK_FILL;
4839 DirectiveKindMap[".zero"] = DK_ZERO;
4840 DirectiveKindMap[".extern"] = DK_EXTERN;
4841 DirectiveKindMap[".globl"] = DK_GLOBL;
4842 DirectiveKindMap[".global"] = DK_GLOBAL;
4843 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4844 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4845 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4846 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4847 DirectiveKindMap[".reference"] = DK_REFERENCE;
4848 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4849 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4850 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4851 DirectiveKindMap[".comm"] = DK_COMM;
4852 DirectiveKindMap[".common"] = DK_COMMON;
4853 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4854 DirectiveKindMap[".abort"] = DK_ABORT;
4855 DirectiveKindMap[".include"] = DK_INCLUDE;
4856 DirectiveKindMap[".incbin"] = DK_INCBIN;
4857 DirectiveKindMap[".code16"] = DK_CODE16;
4858 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4859 DirectiveKindMap[".rept"] = DK_REPT;
4860 DirectiveKindMap[".rep"] = DK_REPT;
4861 DirectiveKindMap[".irp"] = DK_IRP;
4862 DirectiveKindMap[".irpc"] = DK_IRPC;
4863 DirectiveKindMap[".endr"] = DK_ENDR;
4864 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4865 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4866 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4867 DirectiveKindMap[".if"] = DK_IF;
4868 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4869 DirectiveKindMap[".ifge"] = DK_IFGE;
4870 DirectiveKindMap[".ifgt"] = DK_IFGT;
4871 DirectiveKindMap[".ifle"] = DK_IFLE;
4872 DirectiveKindMap[".iflt"] = DK_IFLT;
4873 DirectiveKindMap[".ifne"] = DK_IFNE;
4874 DirectiveKindMap[".ifb"] = DK_IFB;
4875 DirectiveKindMap[".ifnb"] = DK_IFNB;
4876 DirectiveKindMap[".ifc"] = DK_IFC;
4877 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4878 DirectiveKindMap[".ifnc"] = DK_IFNC;
4879 DirectiveKindMap[".ifnes"] = DK_IFNES;
4880 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4881 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4882 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4883 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4884 DirectiveKindMap[".else"] = DK_ELSE;
4885 DirectiveKindMap[".end"] = DK_END;
4886 DirectiveKindMap[".endif"] = DK_ENDIF;
4887 DirectiveKindMap[".skip"] = DK_SKIP;
4888 DirectiveKindMap[".space"] = DK_SPACE;
4889 DirectiveKindMap[".file"] = DK_FILE;
4890 DirectiveKindMap[".line"] = DK_LINE;
4891 DirectiveKindMap[".loc"] = DK_LOC;
4892 DirectiveKindMap[".stabs"] = DK_STABS;
4893 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
4894 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
4895 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4896 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
4897 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
4898 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
4899 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
4900 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4901 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
4902 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4903 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4904 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4905 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4906 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4907 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4908 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4909 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4910 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4911 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4912 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4913 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4914 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4915 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4916 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4917 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4918 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4919 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4920 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4921 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4922 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4923 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4924 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4925 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4926 DirectiveKindMap[".macro"] = DK_MACRO;
4927 DirectiveKindMap[".exitm"] = DK_EXITM;
4928 DirectiveKindMap[".endm"] = DK_ENDM;
4929 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4930 DirectiveKindMap[".purgem"] = DK_PURGEM;
4931 DirectiveKindMap[".err"] = DK_ERR;
4932 DirectiveKindMap[".error"] = DK_ERROR;
4933 DirectiveKindMap[".warning"] = DK_WARNING;
4934 DirectiveKindMap[".reloc"] = DK_RELOC;
4935 DirectiveKindMap[".dc"] = DK_DC;
4936 DirectiveKindMap[".dc.a"] = DK_DC_A;
4937 DirectiveKindMap[".dc.b"] = DK_DC_B;
4938 DirectiveKindMap[".dc.d"] = DK_DC_D;
4939 DirectiveKindMap[".dc.l"] = DK_DC_L;
4940 DirectiveKindMap[".dc.s"] = DK_DC_S;
4941 DirectiveKindMap[".dc.w"] = DK_DC_W;
4942 DirectiveKindMap[".dc.x"] = DK_DC_X;
4943 DirectiveKindMap[".dcb"] = DK_DCB;
4944 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
4945 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
4946 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
4947 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
4948 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
4949 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
4950 DirectiveKindMap[".ds"] = DK_DS;
4951 DirectiveKindMap[".ds.b"] = DK_DS_B;
4952 DirectiveKindMap[".ds.d"] = DK_DS_D;
4953 DirectiveKindMap[".ds.l"] = DK_DS_L;
4954 DirectiveKindMap[".ds.p"] = DK_DS_P;
4955 DirectiveKindMap[".ds.s"] = DK_DS_S;
4956 DirectiveKindMap[".ds.w"] = DK_DS_W;
4957 DirectiveKindMap[".ds.x"] = DK_DS_X;
4960 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4961 AsmToken EndToken, StartToken = getTok();
4963 unsigned NestLevel = 0;
4965 // Check whether we have reached the end of the file.
4966 if (getLexer().is(AsmToken::Eof)) {
4967 printError(DirectiveLoc, "no matching '.endr' in definition");
4971 if (Lexer.is(AsmToken::Identifier) &&
4972 (getTok().getIdentifier() == ".rept" ||
4973 getTok().getIdentifier() == ".irp" ||
4974 getTok().getIdentifier() == ".irpc")) {
4978 // Otherwise, check whether we have reached the .endr.
4979 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4980 if (NestLevel == 0) {
4981 EndToken = getTok();
4983 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4984 printError(getTok().getLoc(),
4985 "unexpected token in '.endr' directive");
4993 // Otherwise, scan till the end of the statement.
4994 eatToEndOfStatement();
4997 const char *BodyStart = StartToken.getLoc().getPointer();
4998 const char *BodyEnd = EndToken.getLoc().getPointer();
4999 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5001 // We Are Anonymous.
5002 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
5003 return &MacroLikeBodies.back();
5006 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
5007 raw_svector_ostream &OS) {
5010 std::unique_ptr<MemoryBuffer> Instantiation =
5011 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
5013 // Create the macro instantiation object and add to the current macro
5014 // instantiation stack.
5015 MacroInstantiation *MI = new MacroInstantiation(
5016 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
5017 ActiveMacros.push_back(MI);
5019 // Jump to the macro instantiation and prime the lexer.
5020 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
5021 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
5025 /// parseDirectiveRept
5026 /// ::= .rep | .rept count
5027 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
5028 const MCExpr *CountExpr;
5029 SMLoc CountLoc = getTok().getLoc();
5030 if (parseExpression(CountExpr))
5034 if (!CountExpr->evaluateAsAbsolute(Count)) {
5035 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5038 if (check(Count < 0, CountLoc, "Count is negative") ||
5039 parseToken(AsmToken::EndOfStatement,
5040 "unexpected token in '" + Dir + "' directive"))
5043 // Lex the rept definition.
5044 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5048 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5049 // to hold the macro body with substitutions.
5050 SmallString<256> Buf;
5051 raw_svector_ostream OS(Buf);
5053 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5054 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
5057 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5062 /// parseDirectiveIrp
5063 /// ::= .irp symbol,values
5064 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
5065 MCAsmMacroParameter Parameter;
5066 MCAsmMacroArguments A;
5067 if (check(parseIdentifier(Parameter.Name),
5068 "expected identifier in '.irp' directive") ||
5069 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5070 parseMacroArguments(nullptr, A) ||
5071 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
5074 // Lex the irp definition.
5075 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5079 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5080 // to hold the macro body with substitutions.
5081 SmallString<256> Buf;
5082 raw_svector_ostream OS(Buf);
5084 for (const MCAsmMacroArgument &Arg : A) {
5085 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5086 // This is undocumented, but GAS seems to support it.
5087 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5091 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5096 /// parseDirectiveIrpc
5097 /// ::= .irpc symbol,values
5098 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
5099 MCAsmMacroParameter Parameter;
5100 MCAsmMacroArguments A;
5102 if (check(parseIdentifier(Parameter.Name),
5103 "expected identifier in '.irpc' directive") ||
5104 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5105 parseMacroArguments(nullptr, A))
5108 if (A.size() != 1 || A.front().size() != 1)
5109 return TokError("unexpected token in '.irpc' directive");
5111 // Eat the end of statement.
5112 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5115 // Lex the irpc definition.
5116 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5120 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5121 // to hold the macro body with substitutions.
5122 SmallString<256> Buf;
5123 raw_svector_ostream OS(Buf);
5125 StringRef Values = A.front().front().getString();
5126 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
5127 MCAsmMacroArgument Arg;
5128 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
5130 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5131 // This is undocumented, but GAS seems to support it.
5132 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5136 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5141 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
5142 if (ActiveMacros.empty())
5143 return TokError("unmatched '.endr' directive");
5145 // The only .repl that should get here are the ones created by
5146 // instantiateMacroLikeBody.
5147 assert(getLexer().is(AsmToken::EndOfStatement));
5153 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
5155 const MCExpr *Value;
5156 SMLoc ExprLoc = getLexer().getLoc();
5157 if (parseExpression(Value))
5159 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5161 return Error(ExprLoc, "unexpected expression in _emit");
5162 uint64_t IntValue = MCE->getValue();
5163 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
5164 return Error(ExprLoc, "literal value out of range for directive");
5166 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
5170 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
5171 const MCExpr *Value;
5172 SMLoc ExprLoc = getLexer().getLoc();
5173 if (parseExpression(Value))
5175 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5177 return Error(ExprLoc, "unexpected expression in align");
5178 uint64_t IntValue = MCE->getValue();
5179 if (!isPowerOf2_64(IntValue))
5180 return Error(ExprLoc, "literal value not a power of two greater then zero");
5182 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
5186 // We are comparing pointers, but the pointers are relative to a single string.
5187 // Thus, this should always be deterministic.
5188 static int rewritesSort(const AsmRewrite *AsmRewriteA,
5189 const AsmRewrite *AsmRewriteB) {
5190 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5192 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5195 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5196 // rewrite to the same location. Make sure the SizeDirective rewrite is
5197 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5198 // ensures the sort algorithm is stable.
5199 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5200 AsmRewritePrecedence[AsmRewriteB->Kind])
5203 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5204 AsmRewritePrecedence[AsmRewriteB->Kind])
5206 llvm_unreachable("Unstable rewrite sort.");
5209 bool AsmParser::parseMSInlineAsm(
5210 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
5211 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
5212 SmallVectorImpl<std::string> &Constraints,
5213 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5214 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
5215 SmallVector<void *, 4> InputDecls;
5216 SmallVector<void *, 4> OutputDecls;
5217 SmallVector<bool, 4> InputDeclsAddressOf;
5218 SmallVector<bool, 4> OutputDeclsAddressOf;
5219 SmallVector<std::string, 4> InputConstraints;
5220 SmallVector<std::string, 4> OutputConstraints;
5221 SmallVector<unsigned, 4> ClobberRegs;
5223 SmallVector<AsmRewrite, 4> AsmStrRewrites;
5228 // While we have input, parse each statement.
5229 unsigned InputIdx = 0;
5230 unsigned OutputIdx = 0;
5231 while (getLexer().isNot(AsmToken::Eof)) {
5232 // Parse curly braces marking block start/end
5233 if (parseCurlyBlockScope(AsmStrRewrites))
5236 ParseStatementInfo Info(&AsmStrRewrites);
5237 bool StatementErr = parseStatement(Info, &SI);
5239 if (StatementErr || Info.ParseError) {
5240 // Emit pending errors if any exist.
5241 printPendingErrors();
5245 // No pending error should exist here.
5246 assert(!hasPendingError() && "unexpected error from parseStatement");
5248 if (Info.Opcode == ~0U)
5251 const MCInstrDesc &Desc = MII->get(Info.Opcode);
5253 // Build the list of clobbers, outputs and inputs.
5254 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
5255 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
5258 if (Operand.isImm())
5261 // Register operand.
5262 if (Operand.isReg() && !Operand.needAddressOf() &&
5263 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
5264 unsigned NumDefs = Desc.getNumDefs();
5266 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5267 ClobberRegs.push_back(Operand.getReg());
5271 // Expr/Input or Output.
5272 StringRef SymName = Operand.getSymName();
5273 if (SymName.empty())
5276 void *OpDecl = Operand.getOpDecl();
5280 bool isOutput = (i == 1) && Desc.mayStore();
5281 SMLoc Start = SMLoc::getFromPointer(SymName.data());
5284 OutputDecls.push_back(OpDecl);
5285 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
5286 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
5287 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
5289 InputDecls.push_back(OpDecl);
5290 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5291 InputConstraints.push_back(Operand.getConstraint().str());
5292 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
5296 // Consider implicit defs to be clobbers. Think of cpuid and push.
5297 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5298 Desc.getNumImplicitDefs());
5299 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
5302 // Set the number of Outputs and Inputs.
5303 NumOutputs = OutputDecls.size();
5304 NumInputs = InputDecls.size();
5306 // Set the unique clobbers.
5307 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5308 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5310 Clobbers.assign(ClobberRegs.size(), std::string());
5311 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5312 raw_string_ostream OS(Clobbers[I]);
5313 IP->printRegName(OS, ClobberRegs[I]);
5316 // Merge the various outputs and inputs. Output are expected first.
5317 if (NumOutputs || NumInputs) {
5318 unsigned NumExprs = NumOutputs + NumInputs;
5319 OpDecls.resize(NumExprs);
5320 Constraints.resize(NumExprs);
5321 for (unsigned i = 0; i < NumOutputs; ++i) {
5322 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
5323 Constraints[i] = OutputConstraints[i];
5325 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
5326 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
5327 Constraints[j] = InputConstraints[i];
5331 // Build the IR assembly string.
5332 std::string AsmStringIR;
5333 raw_string_ostream OS(AsmStringIR);
5334 StringRef ASMString =
5335 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5336 const char *AsmStart = ASMString.begin();
5337 const char *AsmEnd = ASMString.end();
5338 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
5339 for (const AsmRewrite &AR : AsmStrRewrites) {
5340 AsmRewriteKind Kind = AR.Kind;
5341 if (Kind == AOK_Delete)
5344 const char *Loc = AR.Loc.getPointer();
5345 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
5347 // Emit everything up to the immediate/expression.
5348 if (unsigned Len = Loc - AsmStart)
5349 OS << StringRef(AsmStart, Len);
5351 // Skip the original expression.
5352 if (Kind == AOK_Skip) {
5353 AsmStart = Loc + AR.Len;
5357 unsigned AdditionalSkip = 0;
5358 // Rewrite expressions in $N notation.
5363 OS << "$$" << AR.Val;
5369 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
5372 OS << '$' << InputIdx++;
5375 OS << '$' << OutputIdx++;
5377 case AOK_SizeDirective:
5380 case 8: OS << "byte ptr "; break;
5381 case 16: OS << "word ptr "; break;
5382 case 32: OS << "dword ptr "; break;
5383 case 64: OS << "qword ptr "; break;
5384 case 80: OS << "xword ptr "; break;
5385 case 128: OS << "xmmword ptr "; break;
5386 case 256: OS << "ymmword ptr "; break;
5393 // MS alignment directives are measured in bytes. If the native assembler
5394 // measures alignment in bytes, we can pass it straight through.
5396 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5399 // Alignment is in log2 form, so print that instead and skip the original
5401 unsigned Val = AR.Val;
5403 assert(Val < 10 && "Expected alignment less then 2^10.");
5404 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5410 case AOK_DotOperator:
5411 // Insert the dot if the user omitted it.
5413 if (AsmStringIR.back() != '.')
5417 case AOK_EndOfStatement:
5422 // Skip the original expression.
5423 AsmStart = Loc + AR.Len + AdditionalSkip;
5426 // Emit the remainder of the asm string.
5427 if (AsmStart != AsmEnd)
5428 OS << StringRef(AsmStart, AsmEnd - AsmStart);
5430 AsmString = OS.str();
5435 namespace MCParserUtils {
5437 /// Returns whether the given symbol is used anywhere in the given expression,
5438 /// or subexpressions.
5439 static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5440 switch (Value->getKind()) {
5441 case MCExpr::Binary: {
5442 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5443 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5444 isSymbolUsedInExpression(Sym, BE->getRHS());
5446 case MCExpr::Target:
5447 case MCExpr::Constant:
5449 case MCExpr::SymbolRef: {
5451 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5453 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5457 return isSymbolUsedInExpression(
5458 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5461 llvm_unreachable("Unknown expr kind!");
5464 bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5465 MCAsmParser &Parser, MCSymbol *&Sym,
5466 const MCExpr *&Value) {
5468 // FIXME: Use better location, we should use proper tokens.
5469 SMLoc EqualLoc = Parser.getTok().getLoc();
5471 if (Parser.parseExpression(Value)) {
5472 return Parser.TokError("missing expression");
5475 // Note: we don't count b as used in "a = b". This is to allow
5479 if (Parser.parseToken(AsmToken::EndOfStatement))
5482 // Validate that the LHS is allowed to be a variable (either it has not been
5483 // used as a symbol, or it is an absolute symbol).
5484 Sym = Parser.getContext().lookupSymbol(Name);
5486 // Diagnose assignment to a label.
5488 // FIXME: Diagnostics. Note the location of the definition as a label.
5489 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5490 if (isSymbolUsedInExpression(Sym, Value))
5491 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
5492 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5494 ; // Allow redefinitions of undefined symbols only used in directives.
5495 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5496 ; // Allow redefinitions of variables that haven't yet been used.
5497 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5498 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5499 else if (!Sym->isVariable())
5500 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5501 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5502 return Parser.Error(EqualLoc,
5503 "invalid reassignment of non-absolute variable '" +
5505 } else if (Name == ".") {
5506 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
5509 Sym = Parser.getContext().getOrCreateSymbol(Name);
5511 Sym->setRedefinable(allow_redef);
5516 } // end namespace MCParserUtils
5517 } // end namespace llvm
5519 /// \brief Create an MCAsmParser instance.
5520 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5521 MCStreamer &Out, const MCAsmInfo &MAI) {
5522 return new AsmParser(SM, C, Out, MAI);