1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCParser/AsmCond.h"
27 #include "llvm/MC/MCParser/AsmLexer.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCTargetAsmParser.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/raw_ostream.h"
48 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
51 /// \brief Helper types for tracking macro definitions.
52 typedef std::vector<AsmToken> MCAsmMacroArgument;
53 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
55 struct MCAsmMacroParameter {
57 MCAsmMacroArgument Value;
61 MCAsmMacroParameter() : Required(false), Vararg(false) {}
64 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
69 MCAsmMacroParameters Parameters;
72 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
73 : Name(N), Body(B), Parameters(std::move(P)) {}
76 /// \brief Helper class for storing information about an active macro
78 struct MacroInstantiation {
79 /// The location of the instantiation.
80 SMLoc InstantiationLoc;
82 /// The buffer where parsing should resume upon instantiation completion.
85 /// The location where parsing should resume upon instantiation completion.
88 /// The depth of TheCondStack at the start of the instantiation.
89 size_t CondStackDepth;
92 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
95 struct ParseStatementInfo {
96 /// \brief The parsed operands from the last parsed statement.
97 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
99 /// \brief The opcode from the last parsed instruction.
102 /// \brief Was there an error parsing the inline assembly?
105 SmallVectorImpl<AsmRewrite> *AsmRewrites;
107 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
108 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
109 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
112 /// \brief The concrete assembly parser instance.
113 class AsmParser : public MCAsmParser {
114 AsmParser(const AsmParser &) = delete;
115 void operator=(const AsmParser &) = delete;
120 const MCAsmInfo &MAI;
122 SourceMgr::DiagHandlerTy SavedDiagHandler;
123 void *SavedDiagContext;
124 std::unique_ptr<MCAsmParserExtension> PlatformParser;
126 /// This is the current buffer index we're lexing from as managed by the
127 /// SourceMgr object.
130 AsmCond TheCondState;
131 std::vector<AsmCond> TheCondStack;
133 /// \brief maps directive names to handler methods in parser
134 /// extensions. Extensions register themselves in this map by calling
135 /// addDirectiveHandler.
136 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
138 /// \brief Map of currently defined macros.
139 StringMap<MCAsmMacro> MacroMap;
141 /// \brief Stack of active macro instantiations.
142 std::vector<MacroInstantiation*> ActiveMacros;
144 /// \brief List of bodies of anonymous macros.
145 std::deque<MCAsmMacro> MacroLikeBodies;
147 /// Boolean tracking whether macro substitution is enabled.
148 unsigned MacrosEnabledFlag : 1;
150 /// \brief Keeps track of how many .macro's have been instantiated.
151 unsigned NumOfMacroInstantiations;
153 /// Flag tracking whether any errors have been encountered.
154 unsigned HadError : 1;
156 /// The values from the last parsed cpp hash file line comment if any.
157 StringRef CppHashFilename;
158 int64_t CppHashLineNumber;
161 /// When generating dwarf for assembly source files we need to calculate the
162 /// logical line number based on the last parsed cpp hash file line comment
163 /// and current line. Since this is slow and messes up the SourceMgr's
164 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
165 SMLoc LastQueryIDLoc;
166 unsigned LastQueryBuffer;
167 unsigned LastQueryLine;
169 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
170 unsigned AssemblerDialect;
172 /// \brief is Darwin compatibility enabled?
175 /// \brief Are we parsing ms-style inline assembly?
176 bool ParsingInlineAsm;
179 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
180 const MCAsmInfo &MAI);
181 ~AsmParser() override;
183 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
185 void addDirectiveHandler(StringRef Directive,
186 ExtensionDirectiveHandler Handler) override {
187 ExtensionDirectiveMap[Directive] = Handler;
190 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
191 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
195 /// @name MCAsmParser Interface
198 SourceMgr &getSourceManager() override { return SrcMgr; }
199 MCAsmLexer &getLexer() override { return Lexer; }
200 MCContext &getContext() override { return Ctx; }
201 MCStreamer &getStreamer() override { return Out; }
202 unsigned getAssemblerDialect() override {
203 if (AssemblerDialect == ~0U)
204 return MAI.getAssemblerDialect();
206 return AssemblerDialect;
208 void setAssemblerDialect(unsigned i) override {
209 AssemblerDialect = i;
212 void Note(SMLoc L, const Twine &Msg,
213 ArrayRef<SMRange> Ranges = None) override;
214 bool Warning(SMLoc L, const Twine &Msg,
215 ArrayRef<SMRange> Ranges = None) override;
216 bool Error(SMLoc L, const Twine &Msg,
217 ArrayRef<SMRange> Ranges = None) override;
219 const AsmToken &Lex() override;
221 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
222 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
224 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
225 unsigned &NumOutputs, unsigned &NumInputs,
226 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
227 SmallVectorImpl<std::string> &Constraints,
228 SmallVectorImpl<std::string> &Clobbers,
229 const MCInstrInfo *MII, const MCInstPrinter *IP,
230 MCAsmParserSemaCallback &SI) override;
232 bool parseExpression(const MCExpr *&Res);
233 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
234 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
235 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
236 bool parseAbsoluteExpression(int64_t &Res) override;
238 /// \brief Parse an identifier or string (as a quoted identifier)
239 /// and set \p Res to the identifier contents.
240 bool parseIdentifier(StringRef &Res) override;
241 void eatToEndOfStatement() override;
243 void checkForValidSection() override;
248 bool parseStatement(ParseStatementInfo &Info,
249 MCAsmParserSemaCallback *SI);
250 void eatToEndOfLine();
251 bool parseCppHashLineFilenameComment(const SMLoc &L);
253 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
254 ArrayRef<MCAsmMacroParameter> Parameters);
255 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
256 ArrayRef<MCAsmMacroParameter> Parameters,
257 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
260 /// \brief Are macros enabled in the parser?
261 bool areMacrosEnabled() {return MacrosEnabledFlag;}
263 /// \brief Control a flag in the parser that enables or disables macros.
264 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
266 /// \brief Lookup a previously defined macro.
267 /// \param Name Macro name.
268 /// \returns Pointer to macro. NULL if no such macro was defined.
269 const MCAsmMacro* lookupMacro(StringRef Name);
271 /// \brief Define a new macro with the given name and information.
272 void defineMacro(StringRef Name, MCAsmMacro Macro);
274 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
275 void undefineMacro(StringRef Name);
277 /// \brief Are we inside a macro instantiation?
278 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
280 /// \brief Handle entry to macro instantiation.
282 /// \param M The macro.
283 /// \param NameLoc Instantiation location.
284 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
286 /// \brief Handle exit from macro instantiation.
287 void handleMacroExit();
289 /// \brief Extract AsmTokens for a macro argument.
290 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
292 /// \brief Parse all macro arguments for a given macro.
293 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
295 void printMacroInstantiations();
296 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
297 ArrayRef<SMRange> Ranges = None) const {
298 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
300 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
302 /// \brief Enter the specified file. This returns true on failure.
303 bool enterIncludeFile(const std::string &Filename);
305 /// \brief Process the specified file for the .incbin directive.
306 /// This returns true on failure.
307 bool processIncbinFile(const std::string &Filename);
309 /// \brief Reset the current lexer position to that given by \p Loc. The
310 /// current token is not set; clients should ensure Lex() is called
313 /// \param InBuffer If not 0, should be the known buffer id that contains the
315 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
317 /// \brief Parse up to the end of statement and a return the contents from the
318 /// current token until the end of the statement; the current token on exit
319 /// will be either the EndOfStatement or EOF.
320 StringRef parseStringToEndOfStatement() override;
322 /// \brief Parse until the end of a statement or a comma is encountered,
323 /// return the contents from the current token up to the end or comma.
324 StringRef parseStringToComma();
326 bool parseAssignment(StringRef Name, bool allow_redef,
327 bool NoDeadStrip = false);
329 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
330 MCBinaryExpr::Opcode &Kind);
332 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
333 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
334 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
336 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
338 // Generic (target and platform independent) directive parsing.
340 DK_NO_DIRECTIVE, // Placeholder
341 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
342 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
343 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
344 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
345 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
346 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
347 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
348 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
349 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
350 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
351 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
352 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
353 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
354 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
355 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
356 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
357 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
358 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
359 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
360 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
361 DK_MACROS_ON, DK_MACROS_OFF,
362 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
363 DK_SLEB128, DK_ULEB128,
364 DK_ERR, DK_ERROR, DK_WARNING,
368 /// \brief Maps directive name --> DirectiveKind enum, for
369 /// directives parsed by this class.
370 StringMap<DirectiveKind> DirectiveKindMap;
372 // ".ascii", ".asciz", ".string"
373 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
374 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
375 bool parseDirectiveOctaValue(); // ".octa"
376 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
377 bool parseDirectiveFill(); // ".fill"
378 bool parseDirectiveZero(); // ".zero"
379 // ".set", ".equ", ".equiv"
380 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
381 bool parseDirectiveOrg(); // ".org"
382 // ".align{,32}", ".p2align{,w,l}"
383 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
385 // ".file", ".line", ".loc", ".stabs"
386 bool parseDirectiveFile(SMLoc DirectiveLoc);
387 bool parseDirectiveLine();
388 bool parseDirectiveLoc();
389 bool parseDirectiveStabs();
392 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
393 bool parseDirectiveCFIWindowSave();
394 bool parseDirectiveCFISections();
395 bool parseDirectiveCFIStartProc();
396 bool parseDirectiveCFIEndProc();
397 bool parseDirectiveCFIDefCfaOffset();
398 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
399 bool parseDirectiveCFIAdjustCfaOffset();
400 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
401 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
403 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
404 bool parseDirectiveCFIRememberState();
405 bool parseDirectiveCFIRestoreState();
406 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
407 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
408 bool parseDirectiveCFIEscape();
409 bool parseDirectiveCFISignalFrame();
410 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
413 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
414 bool parseDirectiveExitMacro(StringRef Directive);
415 bool parseDirectiveEndMacro(StringRef Directive);
416 bool parseDirectiveMacro(SMLoc DirectiveLoc);
417 bool parseDirectiveMacrosOnOff(StringRef Directive);
419 // ".bundle_align_mode"
420 bool parseDirectiveBundleAlignMode();
422 bool parseDirectiveBundleLock();
424 bool parseDirectiveBundleUnlock();
427 bool parseDirectiveSpace(StringRef IDVal);
429 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
430 bool parseDirectiveLEB128(bool Signed);
432 /// \brief Parse a directive like ".globl" which
433 /// accepts a single symbol (which should be a label or an external).
434 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
436 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
438 bool parseDirectiveAbort(); // ".abort"
439 bool parseDirectiveInclude(); // ".include"
440 bool parseDirectiveIncbin(); // ".incbin"
442 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
443 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
444 // ".ifb" or ".ifnb", depending on ExpectBlank.
445 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
446 // ".ifc" or ".ifnc", depending on ExpectEqual.
447 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
448 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
449 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
450 // ".ifdef" or ".ifndef", depending on expect_defined
451 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
452 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
453 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
454 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
455 bool parseEscapedString(std::string &Data) override;
457 const MCExpr *applyModifierToExpr(const MCExpr *E,
458 MCSymbolRefExpr::VariantKind Variant);
460 // Macro-like directives
461 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
462 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
463 raw_svector_ostream &OS);
464 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
465 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
466 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
467 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
469 // "_emit" or "__emit"
470 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
474 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
477 bool parseDirectiveEnd(SMLoc DirectiveLoc);
479 // ".err" or ".error"
480 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
483 bool parseDirectiveWarning(SMLoc DirectiveLoc);
485 void initializeDirectiveKindMap();
491 extern MCAsmParserExtension *createDarwinAsmParser();
492 extern MCAsmParserExtension *createELFAsmParser();
493 extern MCAsmParserExtension *createCOFFAsmParser();
497 enum { DEFAULT_ADDRSPACE = 0 };
499 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
500 const MCAsmInfo &MAI)
501 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
502 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
503 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
504 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
505 // Save the old handler.
506 SavedDiagHandler = SrcMgr.getDiagHandler();
507 SavedDiagContext = SrcMgr.getDiagContext();
508 // Set our own handler which calls the saved handler.
509 SrcMgr.setDiagHandler(DiagHandler, this);
510 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
512 // Initialize the platform / file format parser.
513 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
514 case MCObjectFileInfo::IsCOFF:
515 PlatformParser.reset(createCOFFAsmParser());
517 case MCObjectFileInfo::IsMachO:
518 PlatformParser.reset(createDarwinAsmParser());
521 case MCObjectFileInfo::IsELF:
522 PlatformParser.reset(createELFAsmParser());
526 PlatformParser->Initialize(*this);
527 initializeDirectiveKindMap();
529 NumOfMacroInstantiations = 0;
532 AsmParser::~AsmParser() {
533 assert((HadError || ActiveMacros.empty()) &&
534 "Unexpected active macro instantiation!");
537 void AsmParser::printMacroInstantiations() {
538 // Print the active macro instantiation stack.
539 for (std::vector<MacroInstantiation *>::const_reverse_iterator
540 it = ActiveMacros.rbegin(),
541 ie = ActiveMacros.rend();
543 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
544 "while in macro instantiation");
547 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
548 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
549 printMacroInstantiations();
552 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
553 if (getTargetParser().getTargetOptions().MCFatalWarnings)
554 return Error(L, Msg, Ranges);
555 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
556 printMacroInstantiations();
560 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
562 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
563 printMacroInstantiations();
567 bool AsmParser::enterIncludeFile(const std::string &Filename) {
568 std::string IncludedFile;
570 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
575 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
579 /// Process the specified .incbin file by searching for it in the include paths
580 /// then just emitting the byte contents of the file to the streamer. This
581 /// returns true on failure.
582 bool AsmParser::processIncbinFile(const std::string &Filename) {
583 std::string IncludedFile;
585 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
589 // Pick up the bytes from the file and emit them.
590 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
594 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
595 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
596 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
600 const AsmToken &AsmParser::Lex() {
601 const AsmToken *tok = &Lexer.Lex();
603 if (tok->is(AsmToken::Eof)) {
604 // If this is the end of an included file, pop the parent file off the
606 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
607 if (ParentIncludeLoc != SMLoc()) {
608 jumpToLoc(ParentIncludeLoc);
613 if (tok->is(AsmToken::Error))
614 Error(Lexer.getErrLoc(), Lexer.getErr());
619 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
620 // Create the initial section, if requested.
621 if (!NoInitialTextSection)
622 Out.InitSections(false);
628 AsmCond StartingCondState = TheCondState;
630 // If we are generating dwarf for assembly source files save the initial text
631 // section and generate a .file directive.
632 if (getContext().getGenDwarfForAssembly()) {
633 MCSymbol *SectionStartSym = getContext().createTempSymbol();
634 getStreamer().EmitLabel(SectionStartSym);
635 MCSection *Sec = getStreamer().getCurrentSection().first;
636 bool InsertResult = getContext().addGenDwarfSection(Sec);
637 assert(InsertResult && ".text section should not have debug info yet");
639 Sec->setBeginSymbol(SectionStartSym);
640 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
641 0, StringRef(), getContext().getMainFileName()));
644 // While we have input, parse each statement.
645 while (Lexer.isNot(AsmToken::Eof)) {
646 ParseStatementInfo Info;
647 if (!parseStatement(Info, nullptr))
650 // We had an error, validate that one was emitted and recover by skipping to
652 assert(HadError && "Parse statement returned an error, but none emitted!");
653 eatToEndOfStatement();
656 if (TheCondState.TheCond != StartingCondState.TheCond ||
657 TheCondState.Ignore != StartingCondState.Ignore)
658 return TokError("unmatched .ifs or .elses");
660 // Check to see there are no empty DwarfFile slots.
661 const auto &LineTables = getContext().getMCDwarfLineTables();
662 if (!LineTables.empty()) {
664 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
665 if (File.Name.empty() && Index != 0)
666 TokError("unassigned file number: " + Twine(Index) +
667 " for .file directives");
672 // Check to see that all assembler local symbols were actually defined.
673 // Targets that don't do subsections via symbols may not want this, though,
674 // so conservatively exclude them. Only do this if we're finalizing, though,
675 // as otherwise we won't necessarilly have seen everything yet.
676 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
677 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
678 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
681 MCSymbol *Sym = i->getValue();
682 // Variable symbols may not be marked as defined, so check those
683 // explicitly. If we know it's a variable, we have a definition for
684 // the purposes of this check.
685 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
686 // FIXME: We would really like to refer back to where the symbol was
687 // first referenced for a source location. We need to add something
688 // to track that. Currently, we just point to the end of the file.
690 getLexer().getLoc(), SourceMgr::DK_Error,
691 "assembler local symbol '" + Sym->getName() + "' not defined");
695 // Finalize the output stream if there are no errors and if the client wants
697 if (!HadError && !NoFinalize)
703 void AsmParser::checkForValidSection() {
704 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
705 TokError("expected section directive before assembly directive");
706 Out.InitSections(false);
710 /// \brief Throw away the rest of the line for testing purposes.
711 void AsmParser::eatToEndOfStatement() {
712 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
716 if (Lexer.is(AsmToken::EndOfStatement))
720 StringRef AsmParser::parseStringToEndOfStatement() {
721 const char *Start = getTok().getLoc().getPointer();
723 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
726 const char *End = getTok().getLoc().getPointer();
727 return StringRef(Start, End - Start);
730 StringRef AsmParser::parseStringToComma() {
731 const char *Start = getTok().getLoc().getPointer();
733 while (Lexer.isNot(AsmToken::EndOfStatement) &&
734 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
737 const char *End = getTok().getLoc().getPointer();
738 return StringRef(Start, End - Start);
741 /// \brief Parse a paren expression and return it.
742 /// NOTE: This assumes the leading '(' has already been consumed.
744 /// parenexpr ::= expr)
746 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
747 if (parseExpression(Res))
749 if (Lexer.isNot(AsmToken::RParen))
750 return TokError("expected ')' in parentheses expression");
751 EndLoc = Lexer.getTok().getEndLoc();
756 /// \brief Parse a bracket expression and return it.
757 /// NOTE: This assumes the leading '[' has already been consumed.
759 /// bracketexpr ::= expr]
761 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
762 if (parseExpression(Res))
764 if (Lexer.isNot(AsmToken::RBrac))
765 return TokError("expected ']' in brackets expression");
766 EndLoc = Lexer.getTok().getEndLoc();
771 /// \brief Parse a primary expression and return it.
772 /// primaryexpr ::= (parenexpr
773 /// primaryexpr ::= symbol
774 /// primaryexpr ::= number
775 /// primaryexpr ::= '.'
776 /// primaryexpr ::= ~,+,- primaryexpr
777 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
778 SMLoc FirstTokenLoc = getLexer().getLoc();
779 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
780 switch (FirstTokenKind) {
782 return TokError("unknown token in expression");
783 // If we have an error assume that we've already handled it.
784 case AsmToken::Error:
786 case AsmToken::Exclaim:
787 Lex(); // Eat the operator.
788 if (parsePrimaryExpr(Res, EndLoc))
790 Res = MCUnaryExpr::CreateLNot(Res, getContext());
792 case AsmToken::Dollar:
794 case AsmToken::String:
795 case AsmToken::Identifier: {
796 StringRef Identifier;
797 if (parseIdentifier(Identifier)) {
798 if (FirstTokenKind == AsmToken::Dollar) {
799 if (Lexer.getMAI().getDollarIsPC()) {
800 // This is a '$' reference, which references the current PC. Emit a
801 // temporary label to the streamer and refer to it.
802 MCSymbol *Sym = Ctx.createTempSymbol();
804 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
806 EndLoc = FirstTokenLoc;
809 return Error(FirstTokenLoc, "invalid token in expression");
812 // Parse symbol variant
813 std::pair<StringRef, StringRef> Split;
814 if (!MAI.useParensForSymbolVariant()) {
815 if (FirstTokenKind == AsmToken::String) {
816 if (Lexer.is(AsmToken::At)) {
817 Lexer.Lex(); // eat @
818 SMLoc AtLoc = getLexer().getLoc();
820 if (parseIdentifier(VName))
821 return Error(AtLoc, "expected symbol variant after '@'");
823 Split = std::make_pair(Identifier, VName);
826 Split = Identifier.split('@');
828 } else if (Lexer.is(AsmToken::LParen)) {
829 Lexer.Lex(); // eat (
831 parseIdentifier(VName);
832 if (Lexer.isNot(AsmToken::RParen)) {
833 return Error(Lexer.getTok().getLoc(),
834 "unexpected token in variant, expected ')'");
836 Lexer.Lex(); // eat )
837 Split = std::make_pair(Identifier, VName);
840 EndLoc = SMLoc::getFromPointer(Identifier.end());
842 // This is a symbol reference.
843 StringRef SymbolName = Identifier;
844 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
846 // Lookup the symbol variant if used.
847 if (Split.second.size()) {
848 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
849 if (Variant != MCSymbolRefExpr::VK_Invalid) {
850 SymbolName = Split.first;
851 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
852 Variant = MCSymbolRefExpr::VK_None;
854 return Error(SMLoc::getFromPointer(Split.second.begin()),
855 "invalid variant '" + Split.second + "'");
859 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
861 // If this is an absolute variable reference, substitute it now to preserve
862 // semantics in the face of reassignment.
863 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
865 return Error(EndLoc, "unexpected modifier on variable reference");
867 Res = Sym->getVariableValue();
871 // Otherwise create a symbol ref.
872 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
875 case AsmToken::BigNum:
876 return TokError("literal value out of range for directive");
877 case AsmToken::Integer: {
878 SMLoc Loc = getTok().getLoc();
879 int64_t IntVal = getTok().getIntVal();
880 Res = MCConstantExpr::Create(IntVal, getContext());
881 EndLoc = Lexer.getTok().getEndLoc();
883 // Look for 'b' or 'f' following an Integer as a directional label
884 if (Lexer.getKind() == AsmToken::Identifier) {
885 StringRef IDVal = getTok().getString();
886 // Lookup the symbol variant if used.
887 std::pair<StringRef, StringRef> Split = IDVal.split('@');
888 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
889 if (Split.first.size() != IDVal.size()) {
890 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
891 if (Variant == MCSymbolRefExpr::VK_Invalid)
892 return TokError("invalid variant '" + Split.second + "'");
895 if (IDVal == "f" || IDVal == "b") {
897 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
898 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
899 if (IDVal == "b" && Sym->isUndefined())
900 return Error(Loc, "invalid reference to undefined symbol");
901 EndLoc = Lexer.getTok().getEndLoc();
902 Lex(); // Eat identifier.
907 case AsmToken::Real: {
908 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
909 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
910 Res = MCConstantExpr::Create(IntVal, getContext());
911 EndLoc = Lexer.getTok().getEndLoc();
915 case AsmToken::Dot: {
916 // This is a '.' reference, which references the current PC. Emit a
917 // temporary label to the streamer and refer to it.
918 MCSymbol *Sym = Ctx.createTempSymbol();
920 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
921 EndLoc = Lexer.getTok().getEndLoc();
922 Lex(); // Eat identifier.
925 case AsmToken::LParen:
926 Lex(); // Eat the '('.
927 return parseParenExpr(Res, EndLoc);
928 case AsmToken::LBrac:
929 if (!PlatformParser->HasBracketExpressions())
930 return TokError("brackets expression not supported on this target");
931 Lex(); // Eat the '['.
932 return parseBracketExpr(Res, EndLoc);
933 case AsmToken::Minus:
934 Lex(); // Eat the operator.
935 if (parsePrimaryExpr(Res, EndLoc))
937 Res = MCUnaryExpr::CreateMinus(Res, getContext());
940 Lex(); // Eat the operator.
941 if (parsePrimaryExpr(Res, EndLoc))
943 Res = MCUnaryExpr::CreatePlus(Res, getContext());
945 case AsmToken::Tilde:
946 Lex(); // Eat the operator.
947 if (parsePrimaryExpr(Res, EndLoc))
949 Res = MCUnaryExpr::CreateNot(Res, getContext());
954 bool AsmParser::parseExpression(const MCExpr *&Res) {
956 return parseExpression(Res, EndLoc);
960 AsmParser::applyModifierToExpr(const MCExpr *E,
961 MCSymbolRefExpr::VariantKind Variant) {
962 // Ask the target implementation about this expression first.
963 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
966 // Recurse over the given expression, rebuilding it to apply the given variant
967 // if there is exactly one symbol.
968 switch (E->getKind()) {
970 case MCExpr::Constant:
973 case MCExpr::SymbolRef: {
974 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
976 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
977 TokError("invalid variant on expression '" + getTok().getIdentifier() +
978 "' (already modified)");
982 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
985 case MCExpr::Unary: {
986 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
987 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
990 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
993 case MCExpr::Binary: {
994 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
995 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
996 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1006 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
1010 llvm_unreachable("Invalid expression kind!");
1013 /// \brief Parse an expression and return it.
1015 /// expr ::= expr &&,|| expr -> lowest.
1016 /// expr ::= expr |,^,&,! expr
1017 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1018 /// expr ::= expr <<,>> expr
1019 /// expr ::= expr +,- expr
1020 /// expr ::= expr *,/,% expr -> highest.
1021 /// expr ::= primaryexpr
1023 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1024 // Parse the expression.
1026 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1029 // As a special case, we support 'a op b @ modifier' by rewriting the
1030 // expression to include the modifier. This is inefficient, but in general we
1031 // expect users to use 'a@modifier op b'.
1032 if (Lexer.getKind() == AsmToken::At) {
1035 if (Lexer.isNot(AsmToken::Identifier))
1036 return TokError("unexpected symbol modifier following '@'");
1038 MCSymbolRefExpr::VariantKind Variant =
1039 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1040 if (Variant == MCSymbolRefExpr::VK_Invalid)
1041 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1043 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1045 return TokError("invalid modifier '" + getTok().getIdentifier() +
1046 "' (no symbols present)");
1053 // Try to constant fold it up front, if possible.
1055 if (Res->EvaluateAsAbsolute(Value))
1056 Res = MCConstantExpr::Create(Value, getContext());
1061 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1063 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1066 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1069 SMLoc StartLoc = Lexer.getLoc();
1070 if (parseExpression(Expr))
1073 if (!Expr->EvaluateAsAbsolute(Res))
1074 return Error(StartLoc, "expected absolute expression");
1079 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1080 MCBinaryExpr::Opcode &Kind) {
1083 return 0; // not a binop.
1085 // Lowest Precedence: &&, ||
1086 case AsmToken::AmpAmp:
1087 Kind = MCBinaryExpr::LAnd;
1089 case AsmToken::PipePipe:
1090 Kind = MCBinaryExpr::LOr;
1093 // Low Precedence: |, &, ^
1095 // FIXME: gas seems to support '!' as an infix operator?
1096 case AsmToken::Pipe:
1097 Kind = MCBinaryExpr::Or;
1099 case AsmToken::Caret:
1100 Kind = MCBinaryExpr::Xor;
1103 Kind = MCBinaryExpr::And;
1106 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1107 case AsmToken::EqualEqual:
1108 Kind = MCBinaryExpr::EQ;
1110 case AsmToken::ExclaimEqual:
1111 case AsmToken::LessGreater:
1112 Kind = MCBinaryExpr::NE;
1114 case AsmToken::Less:
1115 Kind = MCBinaryExpr::LT;
1117 case AsmToken::LessEqual:
1118 Kind = MCBinaryExpr::LTE;
1120 case AsmToken::Greater:
1121 Kind = MCBinaryExpr::GT;
1123 case AsmToken::GreaterEqual:
1124 Kind = MCBinaryExpr::GTE;
1127 // Intermediate Precedence: <<, >>
1128 case AsmToken::LessLess:
1129 Kind = MCBinaryExpr::Shl;
1131 case AsmToken::GreaterGreater:
1132 Kind = MAI.shouldUseLogicalShr() ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1135 // High Intermediate Precedence: +, -
1136 case AsmToken::Plus:
1137 Kind = MCBinaryExpr::Add;
1139 case AsmToken::Minus:
1140 Kind = MCBinaryExpr::Sub;
1143 // Highest Precedence: *, /, %
1144 case AsmToken::Star:
1145 Kind = MCBinaryExpr::Mul;
1147 case AsmToken::Slash:
1148 Kind = MCBinaryExpr::Div;
1150 case AsmToken::Percent:
1151 Kind = MCBinaryExpr::Mod;
1156 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1157 /// Res contains the LHS of the expression on input.
1158 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1161 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1162 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1164 // If the next token is lower precedence than we are allowed to eat, return
1165 // successfully with what we ate already.
1166 if (TokPrec < Precedence)
1171 // Eat the next primary expression.
1173 if (parsePrimaryExpr(RHS, EndLoc))
1176 // If BinOp binds less tightly with RHS than the operator after RHS, let
1177 // the pending operator take RHS as its LHS.
1178 MCBinaryExpr::Opcode Dummy;
1179 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1180 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1183 // Merge LHS and RHS according to operator.
1184 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1189 /// ::= EndOfStatement
1190 /// ::= Label* Directive ...Operands... EndOfStatement
1191 /// ::= Label* Identifier OperandList* EndOfStatement
1192 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1193 MCAsmParserSemaCallback *SI) {
1194 if (Lexer.is(AsmToken::EndOfStatement)) {
1200 // Statements always start with an identifier or are a full line comment.
1201 AsmToken ID = getTok();
1202 SMLoc IDLoc = ID.getLoc();
1204 int64_t LocalLabelVal = -1;
1205 // A full line comment is a '#' as the first token.
1206 if (Lexer.is(AsmToken::Hash))
1207 return parseCppHashLineFilenameComment(IDLoc);
1209 // Allow an integer followed by a ':' as a directional local label.
1210 if (Lexer.is(AsmToken::Integer)) {
1211 LocalLabelVal = getTok().getIntVal();
1212 if (LocalLabelVal < 0) {
1213 if (!TheCondState.Ignore)
1214 return TokError("unexpected token at start of statement");
1217 IDVal = getTok().getString();
1218 Lex(); // Consume the integer token to be used as an identifier token.
1219 if (Lexer.getKind() != AsmToken::Colon) {
1220 if (!TheCondState.Ignore)
1221 return TokError("unexpected token at start of statement");
1224 } else if (Lexer.is(AsmToken::Dot)) {
1225 // Treat '.' as a valid identifier in this context.
1228 } else if (parseIdentifier(IDVal)) {
1229 if (!TheCondState.Ignore)
1230 return TokError("unexpected token at start of statement");
1234 // Handle conditional assembly here before checking for skipping. We
1235 // have to do this so that .endif isn't skipped in a ".if 0" block for
1237 StringMap<DirectiveKind>::const_iterator DirKindIt =
1238 DirectiveKindMap.find(IDVal);
1239 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1241 : DirKindIt->getValue();
1252 return parseDirectiveIf(IDLoc, DirKind);
1254 return parseDirectiveIfb(IDLoc, true);
1256 return parseDirectiveIfb(IDLoc, false);
1258 return parseDirectiveIfc(IDLoc, true);
1260 return parseDirectiveIfeqs(IDLoc, true);
1262 return parseDirectiveIfc(IDLoc, false);
1264 return parseDirectiveIfeqs(IDLoc, false);
1266 return parseDirectiveIfdef(IDLoc, true);
1269 return parseDirectiveIfdef(IDLoc, false);
1271 return parseDirectiveElseIf(IDLoc);
1273 return parseDirectiveElse(IDLoc);
1275 return parseDirectiveEndIf(IDLoc);
1278 // Ignore the statement if in the middle of inactive conditional
1280 if (TheCondState.Ignore) {
1281 eatToEndOfStatement();
1285 // FIXME: Recurse on local labels?
1287 // See what kind of statement we have.
1288 switch (Lexer.getKind()) {
1289 case AsmToken::Colon: {
1290 checkForValidSection();
1292 // identifier ':' -> Label.
1295 // Diagnose attempt to use '.' as a label.
1297 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1299 // Diagnose attempt to use a variable as a label.
1301 // FIXME: Diagnostics. Note the location of the definition as a label.
1302 // FIXME: This doesn't diagnose assignment to a symbol which has been
1303 // implicitly marked as external.
1305 if (LocalLabelVal == -1) {
1306 if (ParsingInlineAsm && SI) {
1307 StringRef RewrittenLabel = SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1308 assert(RewrittenLabel.size() && "We should have an internal name here.");
1309 Info.AsmRewrites->push_back(AsmRewrite(AOK_Label, IDLoc,
1310 IDVal.size(), RewrittenLabel));
1311 IDVal = RewrittenLabel;
1313 Sym = getContext().getOrCreateSymbol(IDVal);
1315 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1317 Sym->redefineIfPossible();
1319 if (!Sym->isUndefined() || Sym->isVariable())
1320 return Error(IDLoc, "invalid symbol redefinition");
1323 if (!ParsingInlineAsm)
1326 // If we are generating dwarf for assembly source files then gather the
1327 // info to make a dwarf label entry for this label if needed.
1328 if (getContext().getGenDwarfForAssembly())
1329 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1332 getTargetParser().onLabelParsed(Sym);
1334 // Consume any end of statement token, if present, to avoid spurious
1335 // AddBlankLine calls().
1336 if (Lexer.is(AsmToken::EndOfStatement)) {
1338 if (Lexer.is(AsmToken::Eof))
1345 case AsmToken::Equal:
1346 // identifier '=' ... -> assignment statement
1349 return parseAssignment(IDVal, true);
1351 default: // Normal instruction or directive.
1355 // If macros are enabled, check to see if this is a macro instantiation.
1356 if (areMacrosEnabled())
1357 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1358 return handleMacroEntry(M, IDLoc);
1361 // Otherwise, we have a normal instruction or directive.
1363 // Directives start with "."
1364 if (IDVal[0] == '.' && IDVal != ".") {
1365 // There are several entities interested in parsing directives:
1367 // 1. The target-specific assembly parser. Some directives are target
1368 // specific or may potentially behave differently on certain targets.
1369 // 2. Asm parser extensions. For example, platform-specific parsers
1370 // (like the ELF parser) register themselves as extensions.
1371 // 3. The generic directive parser implemented by this class. These are
1372 // all the directives that behave in a target and platform independent
1373 // manner, or at least have a default behavior that's shared between
1374 // all targets and platforms.
1376 // First query the target-specific parser. It will return 'true' if it
1377 // isn't interested in this directive.
1378 if (!getTargetParser().ParseDirective(ID))
1381 // Next, check the extension directive map to see if any extension has
1382 // registered itself to parse this directive.
1383 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1384 ExtensionDirectiveMap.lookup(IDVal);
1386 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1388 // Finally, if no one else is interested in this directive, it must be
1389 // generic and familiar to this class.
1395 return parseDirectiveSet(IDVal, true);
1397 return parseDirectiveSet(IDVal, false);
1399 return parseDirectiveAscii(IDVal, false);
1402 return parseDirectiveAscii(IDVal, true);
1404 return parseDirectiveValue(1);
1408 return parseDirectiveValue(2);
1412 return parseDirectiveValue(4);
1415 return parseDirectiveValue(8);
1417 return parseDirectiveOctaValue();
1420 return parseDirectiveRealValue(APFloat::IEEEsingle);
1422 return parseDirectiveRealValue(APFloat::IEEEdouble);
1424 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1425 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1428 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1429 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1432 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1434 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1436 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1438 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1440 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1442 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1444 return parseDirectiveOrg();
1446 return parseDirectiveFill();
1448 return parseDirectiveZero();
1450 eatToEndOfStatement(); // .extern is the default, ignore it.
1454 return parseDirectiveSymbolAttribute(MCSA_Global);
1455 case DK_LAZY_REFERENCE:
1456 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1457 case DK_NO_DEAD_STRIP:
1458 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1459 case DK_SYMBOL_RESOLVER:
1460 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1461 case DK_PRIVATE_EXTERN:
1462 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1464 return parseDirectiveSymbolAttribute(MCSA_Reference);
1465 case DK_WEAK_DEFINITION:
1466 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1467 case DK_WEAK_REFERENCE:
1468 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1469 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1470 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1473 return parseDirectiveComm(/*IsLocal=*/false);
1475 return parseDirectiveComm(/*IsLocal=*/true);
1477 return parseDirectiveAbort();
1479 return parseDirectiveInclude();
1481 return parseDirectiveIncbin();
1484 return TokError(Twine(IDVal) + " not supported yet");
1486 return parseDirectiveRept(IDLoc, IDVal);
1488 return parseDirectiveIrp(IDLoc);
1490 return parseDirectiveIrpc(IDLoc);
1492 return parseDirectiveEndr(IDLoc);
1493 case DK_BUNDLE_ALIGN_MODE:
1494 return parseDirectiveBundleAlignMode();
1495 case DK_BUNDLE_LOCK:
1496 return parseDirectiveBundleLock();
1497 case DK_BUNDLE_UNLOCK:
1498 return parseDirectiveBundleUnlock();
1500 return parseDirectiveLEB128(true);
1502 return parseDirectiveLEB128(false);
1505 return parseDirectiveSpace(IDVal);
1507 return parseDirectiveFile(IDLoc);
1509 return parseDirectiveLine();
1511 return parseDirectiveLoc();
1513 return parseDirectiveStabs();
1514 case DK_CFI_SECTIONS:
1515 return parseDirectiveCFISections();
1516 case DK_CFI_STARTPROC:
1517 return parseDirectiveCFIStartProc();
1518 case DK_CFI_ENDPROC:
1519 return parseDirectiveCFIEndProc();
1520 case DK_CFI_DEF_CFA:
1521 return parseDirectiveCFIDefCfa(IDLoc);
1522 case DK_CFI_DEF_CFA_OFFSET:
1523 return parseDirectiveCFIDefCfaOffset();
1524 case DK_CFI_ADJUST_CFA_OFFSET:
1525 return parseDirectiveCFIAdjustCfaOffset();
1526 case DK_CFI_DEF_CFA_REGISTER:
1527 return parseDirectiveCFIDefCfaRegister(IDLoc);
1529 return parseDirectiveCFIOffset(IDLoc);
1530 case DK_CFI_REL_OFFSET:
1531 return parseDirectiveCFIRelOffset(IDLoc);
1532 case DK_CFI_PERSONALITY:
1533 return parseDirectiveCFIPersonalityOrLsda(true);
1535 return parseDirectiveCFIPersonalityOrLsda(false);
1536 case DK_CFI_REMEMBER_STATE:
1537 return parseDirectiveCFIRememberState();
1538 case DK_CFI_RESTORE_STATE:
1539 return parseDirectiveCFIRestoreState();
1540 case DK_CFI_SAME_VALUE:
1541 return parseDirectiveCFISameValue(IDLoc);
1542 case DK_CFI_RESTORE:
1543 return parseDirectiveCFIRestore(IDLoc);
1545 return parseDirectiveCFIEscape();
1546 case DK_CFI_SIGNAL_FRAME:
1547 return parseDirectiveCFISignalFrame();
1548 case DK_CFI_UNDEFINED:
1549 return parseDirectiveCFIUndefined(IDLoc);
1550 case DK_CFI_REGISTER:
1551 return parseDirectiveCFIRegister(IDLoc);
1552 case DK_CFI_WINDOW_SAVE:
1553 return parseDirectiveCFIWindowSave();
1556 return parseDirectiveMacrosOnOff(IDVal);
1558 return parseDirectiveMacro(IDLoc);
1560 return parseDirectiveExitMacro(IDVal);
1563 return parseDirectiveEndMacro(IDVal);
1565 return parseDirectivePurgeMacro(IDLoc);
1567 return parseDirectiveEnd(IDLoc);
1569 return parseDirectiveError(IDLoc, false);
1571 return parseDirectiveError(IDLoc, true);
1573 return parseDirectiveWarning(IDLoc);
1576 return Error(IDLoc, "unknown directive");
1579 // __asm _emit or __asm __emit
1580 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1581 IDVal == "_EMIT" || IDVal == "__EMIT"))
1582 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1585 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1586 return parseDirectiveMSAlign(IDLoc, Info);
1588 checkForValidSection();
1590 // Canonicalize the opcode to lower case.
1591 std::string OpcodeStr = IDVal.lower();
1592 ParseInstructionInfo IInfo(Info.AsmRewrites);
1593 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1594 Info.ParsedOperands);
1595 Info.ParseError = HadError;
1597 // Dump the parsed representation, if requested.
1598 if (getShowParsedOperands()) {
1599 SmallString<256> Str;
1600 raw_svector_ostream OS(Str);
1601 OS << "parsed instruction: [";
1602 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1605 Info.ParsedOperands[i]->print(OS);
1609 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1612 // If we are generating dwarf for the current section then generate a .loc
1613 // directive for the instruction.
1614 if (!HadError && getContext().getGenDwarfForAssembly() &&
1615 getContext().getGenDwarfSectionSyms().count(
1616 getStreamer().getCurrentSection().first)) {
1618 if (ActiveMacros.empty())
1619 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1621 Line = SrcMgr.FindLineNumber(ActiveMacros.back()->InstantiationLoc,
1622 ActiveMacros.back()->ExitBuffer);
1624 // If we previously parsed a cpp hash file line comment then make sure the
1625 // current Dwarf File is for the CppHashFilename if not then emit the
1626 // Dwarf File table for it and adjust the line number for the .loc.
1627 if (CppHashFilename.size()) {
1628 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1629 0, StringRef(), CppHashFilename);
1630 getContext().setGenDwarfFileNumber(FileNumber);
1632 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1633 // cache with the different Loc from the call above we save the last
1634 // info we queried here with SrcMgr.FindLineNumber().
1635 unsigned CppHashLocLineNo;
1636 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1637 CppHashLocLineNo = LastQueryLine;
1639 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1640 LastQueryLine = CppHashLocLineNo;
1641 LastQueryIDLoc = CppHashLoc;
1642 LastQueryBuffer = CppHashBuf;
1644 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1647 getStreamer().EmitDwarfLocDirective(
1648 getContext().getGenDwarfFileNumber(), Line, 0,
1649 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1653 // If parsing succeeded, match the instruction.
1656 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1657 Info.ParsedOperands, Out,
1658 ErrorInfo, ParsingInlineAsm);
1661 // Don't skip the rest of the line, the instruction parser is responsible for
1666 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1667 /// since they may not be able to be tokenized to get to the end of line token.
1668 void AsmParser::eatToEndOfLine() {
1669 if (!Lexer.is(AsmToken::EndOfStatement))
1670 Lexer.LexUntilEndOfLine();
1675 /// parseCppHashLineFilenameComment as this:
1676 /// ::= # number "filename"
1677 /// or just as a full line comment if it doesn't have a number and a string.
1678 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1679 Lex(); // Eat the hash token.
1681 if (getLexer().isNot(AsmToken::Integer)) {
1682 // Consume the line since in cases it is not a well-formed line directive,
1683 // as if were simply a full line comment.
1688 int64_t LineNumber = getTok().getIntVal();
1691 if (getLexer().isNot(AsmToken::String)) {
1696 StringRef Filename = getTok().getString();
1697 // Get rid of the enclosing quotes.
1698 Filename = Filename.substr(1, Filename.size() - 2);
1700 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1702 CppHashFilename = Filename;
1703 CppHashLineNumber = LineNumber;
1704 CppHashBuf = CurBuffer;
1706 // Ignore any trailing characters, they're just comment.
1711 /// \brief will use the last parsed cpp hash line filename comment
1712 /// for the Filename and LineNo if any in the diagnostic.
1713 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1714 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1715 raw_ostream &OS = errs();
1717 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1718 const SMLoc &DiagLoc = Diag.getLoc();
1719 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1720 unsigned CppHashBuf =
1721 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1723 // Like SourceMgr::printMessage() we need to print the include stack if any
1724 // before printing the message.
1725 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1726 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1727 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
1728 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1729 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1732 // If we have not parsed a cpp hash line filename comment or the source
1733 // manager changed or buffer changed (like in a nested include) then just
1734 // print the normal diagnostic using its Filename and LineNo.
1735 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1736 DiagBuf != CppHashBuf) {
1737 if (Parser->SavedDiagHandler)
1738 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1740 Diag.print(nullptr, OS);
1744 // Use the CppHashFilename and calculate a line number based on the
1745 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1747 const std::string &Filename = Parser->CppHashFilename;
1749 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1750 int CppHashLocLineNo =
1751 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1753 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1755 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1756 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1757 Diag.getLineContents(), Diag.getRanges());
1759 if (Parser->SavedDiagHandler)
1760 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1762 NewDiag.print(nullptr, OS);
1765 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1766 // difference being that that function accepts '@' as part of identifiers and
1767 // we can't do that. AsmLexer.cpp should probably be changed to handle
1768 // '@' as a special case when needed.
1769 static bool isIdentifierChar(char c) {
1770 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1774 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1775 ArrayRef<MCAsmMacroParameter> Parameters,
1776 ArrayRef<MCAsmMacroArgument> A,
1777 bool EnableAtPseudoVariable, const SMLoc &L) {
1778 unsigned NParameters = Parameters.size();
1779 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1780 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1781 return Error(L, "Wrong number of arguments");
1783 // A macro without parameters is handled differently on Darwin:
1784 // gas accepts no arguments and does no substitutions
1785 while (!Body.empty()) {
1786 // Scan for the next substitution.
1787 std::size_t End = Body.size(), Pos = 0;
1788 for (; Pos != End; ++Pos) {
1789 // Check for a substitution or escape.
1790 if (IsDarwin && !NParameters) {
1791 // This macro has no parameters, look for $0, $1, etc.
1792 if (Body[Pos] != '$' || Pos + 1 == End)
1795 char Next = Body[Pos + 1];
1796 if (Next == '$' || Next == 'n' ||
1797 isdigit(static_cast<unsigned char>(Next)))
1800 // This macro has parameters, look for \foo, \bar, etc.
1801 if (Body[Pos] == '\\' && Pos + 1 != End)
1807 OS << Body.slice(0, Pos);
1809 // Check if we reached the end.
1813 if (IsDarwin && !NParameters) {
1814 switch (Body[Pos + 1]) {
1820 // $n => number of arguments
1825 // $[0-9] => argument
1827 // Missing arguments are ignored.
1828 unsigned Index = Body[Pos + 1] - '0';
1829 if (Index >= A.size())
1832 // Otherwise substitute with the token values, with spaces eliminated.
1833 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1834 ie = A[Index].end();
1836 OS << it->getString();
1842 unsigned I = Pos + 1;
1844 // Check for the \@ pseudo-variable.
1845 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
1848 while (isIdentifierChar(Body[I]) && I + 1 != End)
1851 const char *Begin = Body.data() + Pos + 1;
1852 StringRef Argument(Begin, I - (Pos + 1));
1855 if (Argument == "@") {
1856 OS << NumOfMacroInstantiations;
1859 for (; Index < NParameters; ++Index)
1860 if (Parameters[Index].Name == Argument)
1863 if (Index == NParameters) {
1864 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1867 OS << '\\' << Argument;
1871 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1872 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1873 ie = A[Index].end();
1875 // We expect no quotes around the string's contents when
1876 // parsing for varargs.
1877 if (it->getKind() != AsmToken::String || VarargParameter)
1878 OS << it->getString();
1880 OS << it->getStringContents();
1882 Pos += 1 + Argument.size();
1886 // Update the scan point.
1887 Body = Body.substr(Pos);
1893 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
1894 size_t CondStackDepth)
1895 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
1896 CondStackDepth(CondStackDepth) {}
1898 static bool isOperator(AsmToken::TokenKind kind) {
1902 case AsmToken::Plus:
1903 case AsmToken::Minus:
1904 case AsmToken::Tilde:
1905 case AsmToken::Slash:
1906 case AsmToken::Star:
1908 case AsmToken::Equal:
1909 case AsmToken::EqualEqual:
1910 case AsmToken::Pipe:
1911 case AsmToken::PipePipe:
1912 case AsmToken::Caret:
1914 case AsmToken::AmpAmp:
1915 case AsmToken::Exclaim:
1916 case AsmToken::ExclaimEqual:
1917 case AsmToken::Percent:
1918 case AsmToken::Less:
1919 case AsmToken::LessEqual:
1920 case AsmToken::LessLess:
1921 case AsmToken::LessGreater:
1922 case AsmToken::Greater:
1923 case AsmToken::GreaterEqual:
1924 case AsmToken::GreaterGreater:
1930 class AsmLexerSkipSpaceRAII {
1932 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1933 Lexer.setSkipSpace(SkipSpace);
1936 ~AsmLexerSkipSpaceRAII() {
1937 Lexer.setSkipSpace(true);
1945 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1948 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1949 StringRef Str = parseStringToEndOfStatement();
1950 MA.push_back(AsmToken(AsmToken::String, Str));
1955 unsigned ParenLevel = 0;
1956 unsigned AddTokens = 0;
1958 // Darwin doesn't use spaces to delmit arguments.
1959 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1962 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1963 return TokError("unexpected token in macro instantiation");
1965 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1968 if (Lexer.is(AsmToken::Space)) {
1969 Lex(); // Eat spaces
1971 // Spaces can delimit parameters, but could also be part an expression.
1972 // If the token after a space is an operator, add the token and the next
1973 // one into this argument
1975 if (isOperator(Lexer.getKind())) {
1976 // Check to see whether the token is used as an operator,
1977 // or part of an identifier
1978 const char *NextChar = getTok().getEndLoc().getPointer();
1979 if (*NextChar == ' ')
1983 if (!AddTokens && ParenLevel == 0) {
1989 // handleMacroEntry relies on not advancing the lexer here
1990 // to be able to fill in the remaining default parameter values
1991 if (Lexer.is(AsmToken::EndOfStatement))
1994 // Adjust the current parentheses level.
1995 if (Lexer.is(AsmToken::LParen))
1997 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2000 // Append the token to the current argument list.
2001 MA.push_back(getTok());
2007 if (ParenLevel != 0)
2008 return TokError("unbalanced parentheses in macro argument");
2012 // Parse the macro instantiation arguments.
2013 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2014 MCAsmMacroArguments &A) {
2015 const unsigned NParameters = M ? M->Parameters.size() : 0;
2016 bool NamedParametersFound = false;
2017 SmallVector<SMLoc, 4> FALocs;
2019 A.resize(NParameters);
2020 FALocs.resize(NParameters);
2022 // Parse two kinds of macro invocations:
2023 // - macros defined without any parameters accept an arbitrary number of them
2024 // - macros defined with parameters accept at most that many of them
2025 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2026 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2028 SMLoc IDLoc = Lexer.getLoc();
2029 MCAsmMacroParameter FA;
2031 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2032 if (parseIdentifier(FA.Name)) {
2033 Error(IDLoc, "invalid argument identifier for formal argument");
2034 eatToEndOfStatement();
2038 if (!Lexer.is(AsmToken::Equal)) {
2039 TokError("expected '=' after formal parameter identifier");
2040 eatToEndOfStatement();
2045 NamedParametersFound = true;
2048 if (NamedParametersFound && FA.Name.empty()) {
2049 Error(IDLoc, "cannot mix positional and keyword arguments");
2050 eatToEndOfStatement();
2054 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2055 if (parseMacroArgument(FA.Value, Vararg))
2058 unsigned PI = Parameter;
2059 if (!FA.Name.empty()) {
2061 for (FAI = 0; FAI < NParameters; ++FAI)
2062 if (M->Parameters[FAI].Name == FA.Name)
2065 if (FAI >= NParameters) {
2066 assert(M && "expected macro to be defined");
2068 "parameter named '" + FA.Name + "' does not exist for macro '" +
2075 if (!FA.Value.empty()) {
2080 if (FALocs.size() <= PI)
2081 FALocs.resize(PI + 1);
2083 FALocs[PI] = Lexer.getLoc();
2086 // At the end of the statement, fill in remaining arguments that have
2087 // default values. If there aren't any, then the next argument is
2088 // required but missing
2089 if (Lexer.is(AsmToken::EndOfStatement)) {
2090 bool Failure = false;
2091 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2092 if (A[FAI].empty()) {
2093 if (M->Parameters[FAI].Required) {
2094 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2095 "missing value for required parameter "
2096 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2100 if (!M->Parameters[FAI].Value.empty())
2101 A[FAI] = M->Parameters[FAI].Value;
2107 if (Lexer.is(AsmToken::Comma))
2111 return TokError("too many positional arguments");
2114 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2115 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2116 return (I == MacroMap.end()) ? nullptr : &I->getValue();
2119 void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2120 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2123 void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2125 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2126 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2127 // this, although we should protect against infinite loops.
2128 if (ActiveMacros.size() == 20)
2129 return TokError("macros cannot be nested more than 20 levels deep");
2131 MCAsmMacroArguments A;
2132 if (parseMacroArguments(M, A))
2135 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2136 // to hold the macro body with substitutions.
2137 SmallString<256> Buf;
2138 StringRef Body = M->Body;
2139 raw_svector_ostream OS(Buf);
2141 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2144 // We include the .endmacro in the buffer as our cue to exit the macro
2146 OS << ".endmacro\n";
2148 std::unique_ptr<MemoryBuffer> Instantiation =
2149 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2151 // Create the macro instantiation object and add to the current macro
2152 // instantiation stack.
2153 MacroInstantiation *MI = new MacroInstantiation(
2154 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2155 ActiveMacros.push_back(MI);
2157 ++NumOfMacroInstantiations;
2159 // Jump to the macro instantiation and prime the lexer.
2160 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2161 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2167 void AsmParser::handleMacroExit() {
2168 // Jump to the EndOfStatement we should return to, and consume it.
2169 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2172 // Pop the instantiation entry.
2173 delete ActiveMacros.back();
2174 ActiveMacros.pop_back();
2177 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2178 switch (Value->getKind()) {
2179 case MCExpr::Binary: {
2180 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2181 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2183 case MCExpr::Target:
2184 case MCExpr::Constant:
2186 case MCExpr::SymbolRef: {
2188 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2190 return isUsedIn(Sym, S.getVariableValue());
2194 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2197 llvm_unreachable("Unknown expr kind!");
2200 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2202 // FIXME: Use better location, we should use proper tokens.
2203 SMLoc EqualLoc = Lexer.getLoc();
2205 const MCExpr *Value;
2206 if (parseExpression(Value))
2209 // Note: we don't count b as used in "a = b". This is to allow
2213 if (Lexer.isNot(AsmToken::EndOfStatement))
2214 return TokError("unexpected token in assignment");
2216 // Eat the end of statement marker.
2219 // Validate that the LHS is allowed to be a variable (either it has not been
2220 // used as a symbol, or it is an absolute symbol).
2221 MCSymbol *Sym = getContext().lookupSymbol(Name);
2223 // Diagnose assignment to a label.
2225 // FIXME: Diagnostics. Note the location of the definition as a label.
2226 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2227 if (isUsedIn(Sym, Value))
2228 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2229 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2230 ; // Allow redefinitions of undefined symbols only used in directives.
2231 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2232 ; // Allow redefinitions of variables that haven't yet been used.
2233 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2234 return Error(EqualLoc, "redefinition of '" + Name + "'");
2235 else if (!Sym->isVariable())
2236 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2237 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2238 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2241 // Don't count these checks as uses.
2242 Sym->setUsed(false);
2243 } else if (Name == ".") {
2244 if (Out.EmitValueToOffset(Value, 0)) {
2245 Error(EqualLoc, "expected absolute expression");
2246 eatToEndOfStatement();
2250 Sym = getContext().getOrCreateSymbol(Name);
2252 Sym->setRedefinable(allow_redef);
2254 // Do the assignment.
2255 Out.EmitAssignment(Sym, Value);
2257 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2262 /// parseIdentifier:
2265 bool AsmParser::parseIdentifier(StringRef &Res) {
2266 // The assembler has relaxed rules for accepting identifiers, in particular we
2267 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2268 // separate tokens. At this level, we have already lexed so we cannot (currently)
2269 // handle this as a context dependent token, instead we detect adjacent tokens
2270 // and return the combined identifier.
2271 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2272 SMLoc PrefixLoc = getLexer().getLoc();
2274 // Consume the prefix character, and check for a following identifier.
2276 if (Lexer.isNot(AsmToken::Identifier))
2279 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2280 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2283 // Construct the joined identifier and consume the token.
2285 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2290 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2293 Res = getTok().getIdentifier();
2295 Lex(); // Consume the identifier token.
2300 /// parseDirectiveSet:
2301 /// ::= .equ identifier ',' expression
2302 /// ::= .equiv identifier ',' expression
2303 /// ::= .set identifier ',' expression
2304 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2307 if (parseIdentifier(Name))
2308 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2310 if (getLexer().isNot(AsmToken::Comma))
2311 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2314 return parseAssignment(Name, allow_redef, true);
2317 bool AsmParser::parseEscapedString(std::string &Data) {
2318 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2321 StringRef Str = getTok().getStringContents();
2322 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2323 if (Str[i] != '\\') {
2328 // Recognize escaped characters. Note that this escape semantics currently
2329 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2332 return TokError("unexpected backslash at end of string");
2334 // Recognize octal sequences.
2335 if ((unsigned)(Str[i] - '0') <= 7) {
2336 // Consume up to three octal characters.
2337 unsigned Value = Str[i] - '0';
2339 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2341 Value = Value * 8 + (Str[i] - '0');
2343 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2345 Value = Value * 8 + (Str[i] - '0');
2350 return TokError("invalid octal escape sequence (out of range)");
2352 Data += (unsigned char)Value;
2356 // Otherwise recognize individual escapes.
2359 // Just reject invalid escape sequences for now.
2360 return TokError("invalid escape sequence (unrecognized character)");
2362 case 'b': Data += '\b'; break;
2363 case 'f': Data += '\f'; break;
2364 case 'n': Data += '\n'; break;
2365 case 'r': Data += '\r'; break;
2366 case 't': Data += '\t'; break;
2367 case '"': Data += '"'; break;
2368 case '\\': Data += '\\'; break;
2375 /// parseDirectiveAscii:
2376 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2377 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2378 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2379 checkForValidSection();
2382 if (getLexer().isNot(AsmToken::String))
2383 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2386 if (parseEscapedString(Data))
2389 getStreamer().EmitBytes(Data);
2391 getStreamer().EmitBytes(StringRef("\0", 1));
2395 if (getLexer().is(AsmToken::EndOfStatement))
2398 if (getLexer().isNot(AsmToken::Comma))
2399 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2408 /// parseDirectiveValue
2409 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2410 bool AsmParser::parseDirectiveValue(unsigned Size) {
2411 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2412 checkForValidSection();
2415 const MCExpr *Value;
2416 SMLoc ExprLoc = getLexer().getLoc();
2417 if (parseExpression(Value))
2420 // Special case constant expressions to match code generator.
2421 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2422 assert(Size <= 8 && "Invalid size");
2423 uint64_t IntValue = MCE->getValue();
2424 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2425 return Error(ExprLoc, "literal value out of range for directive");
2426 getStreamer().EmitIntValue(IntValue, Size);
2428 getStreamer().EmitValue(Value, Size, ExprLoc);
2430 if (getLexer().is(AsmToken::EndOfStatement))
2433 // FIXME: Improve diagnostic.
2434 if (getLexer().isNot(AsmToken::Comma))
2435 return TokError("unexpected token in directive");
2444 /// ParseDirectiveOctaValue
2445 /// ::= .octa [ hexconstant (, hexconstant)* ]
2446 bool AsmParser::parseDirectiveOctaValue() {
2447 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2448 checkForValidSection();
2451 if (Lexer.getKind() == AsmToken::Error)
2453 if (Lexer.getKind() != AsmToken::Integer &&
2454 Lexer.getKind() != AsmToken::BigNum)
2455 return TokError("unknown token in expression");
2457 SMLoc ExprLoc = getLexer().getLoc();
2458 APInt IntValue = getTok().getAPIntVal();
2462 if (IntValue.isIntN(64)) {
2464 lo = IntValue.getZExtValue();
2465 } else if (IntValue.isIntN(128)) {
2466 // It might actually have more than 128 bits, but the top ones are zero.
2467 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2468 lo = IntValue.getLoBits(64).getZExtValue();
2470 return Error(ExprLoc, "literal value out of range for directive");
2472 if (MAI.isLittleEndian()) {
2473 getStreamer().EmitIntValue(lo, 8);
2474 getStreamer().EmitIntValue(hi, 8);
2476 getStreamer().EmitIntValue(hi, 8);
2477 getStreamer().EmitIntValue(lo, 8);
2480 if (getLexer().is(AsmToken::EndOfStatement))
2483 // FIXME: Improve diagnostic.
2484 if (getLexer().isNot(AsmToken::Comma))
2485 return TokError("unexpected token in directive");
2494 /// parseDirectiveRealValue
2495 /// ::= (.single | .double) [ expression (, expression)* ]
2496 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2497 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2498 checkForValidSection();
2501 // We don't truly support arithmetic on floating point expressions, so we
2502 // have to manually parse unary prefixes.
2504 if (getLexer().is(AsmToken::Minus)) {
2507 } else if (getLexer().is(AsmToken::Plus))
2510 if (getLexer().isNot(AsmToken::Integer) &&
2511 getLexer().isNot(AsmToken::Real) &&
2512 getLexer().isNot(AsmToken::Identifier))
2513 return TokError("unexpected token in directive");
2515 // Convert to an APFloat.
2516 APFloat Value(Semantics);
2517 StringRef IDVal = getTok().getString();
2518 if (getLexer().is(AsmToken::Identifier)) {
2519 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2520 Value = APFloat::getInf(Semantics);
2521 else if (!IDVal.compare_lower("nan"))
2522 Value = APFloat::getNaN(Semantics, false, ~0);
2524 return TokError("invalid floating point literal");
2525 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2526 APFloat::opInvalidOp)
2527 return TokError("invalid floating point literal");
2531 // Consume the numeric token.
2534 // Emit the value as an integer.
2535 APInt AsInt = Value.bitcastToAPInt();
2536 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2537 AsInt.getBitWidth() / 8);
2539 if (getLexer().is(AsmToken::EndOfStatement))
2542 if (getLexer().isNot(AsmToken::Comma))
2543 return TokError("unexpected token in directive");
2552 /// parseDirectiveZero
2553 /// ::= .zero expression
2554 bool AsmParser::parseDirectiveZero() {
2555 checkForValidSection();
2558 if (parseAbsoluteExpression(NumBytes))
2562 if (getLexer().is(AsmToken::Comma)) {
2564 if (parseAbsoluteExpression(Val))
2568 if (getLexer().isNot(AsmToken::EndOfStatement))
2569 return TokError("unexpected token in '.zero' directive");
2573 getStreamer().EmitFill(NumBytes, Val);
2578 /// parseDirectiveFill
2579 /// ::= .fill expression [ , expression [ , expression ] ]
2580 bool AsmParser::parseDirectiveFill() {
2581 checkForValidSection();
2583 SMLoc RepeatLoc = getLexer().getLoc();
2585 if (parseAbsoluteExpression(NumValues))
2588 if (NumValues < 0) {
2590 "'.fill' directive with negative repeat count has no effect");
2594 int64_t FillSize = 1;
2595 int64_t FillExpr = 0;
2597 SMLoc SizeLoc, ExprLoc;
2598 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2599 if (getLexer().isNot(AsmToken::Comma))
2600 return TokError("unexpected token in '.fill' directive");
2603 SizeLoc = getLexer().getLoc();
2604 if (parseAbsoluteExpression(FillSize))
2607 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2608 if (getLexer().isNot(AsmToken::Comma))
2609 return TokError("unexpected token in '.fill' directive");
2612 ExprLoc = getLexer().getLoc();
2613 if (parseAbsoluteExpression(FillExpr))
2616 if (getLexer().isNot(AsmToken::EndOfStatement))
2617 return TokError("unexpected token in '.fill' directive");
2624 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2628 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2632 if (!isUInt<32>(FillExpr) && FillSize > 4)
2633 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2635 if (NumValues > 0) {
2636 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2637 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2638 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2639 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2640 if (NonZeroFillSize < FillSize)
2641 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2648 /// parseDirectiveOrg
2649 /// ::= .org expression [ , expression ]
2650 bool AsmParser::parseDirectiveOrg() {
2651 checkForValidSection();
2653 const MCExpr *Offset;
2654 SMLoc Loc = getTok().getLoc();
2655 if (parseExpression(Offset))
2658 // Parse optional fill expression.
2659 int64_t FillExpr = 0;
2660 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2661 if (getLexer().isNot(AsmToken::Comma))
2662 return TokError("unexpected token in '.org' directive");
2665 if (parseAbsoluteExpression(FillExpr))
2668 if (getLexer().isNot(AsmToken::EndOfStatement))
2669 return TokError("unexpected token in '.org' directive");
2674 // Only limited forms of relocatable expressions are accepted here, it
2675 // has to be relative to the current section. The streamer will return
2676 // 'true' if the expression wasn't evaluatable.
2677 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2678 return Error(Loc, "expected assembly-time absolute expression");
2683 /// parseDirectiveAlign
2684 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2685 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2686 checkForValidSection();
2688 SMLoc AlignmentLoc = getLexer().getLoc();
2690 if (parseAbsoluteExpression(Alignment))
2694 bool HasFillExpr = false;
2695 int64_t FillExpr = 0;
2696 int64_t MaxBytesToFill = 0;
2697 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2698 if (getLexer().isNot(AsmToken::Comma))
2699 return TokError("unexpected token in directive");
2702 // The fill expression can be omitted while specifying a maximum number of
2703 // alignment bytes, e.g:
2705 if (getLexer().isNot(AsmToken::Comma)) {
2707 if (parseAbsoluteExpression(FillExpr))
2711 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2712 if (getLexer().isNot(AsmToken::Comma))
2713 return TokError("unexpected token in directive");
2716 MaxBytesLoc = getLexer().getLoc();
2717 if (parseAbsoluteExpression(MaxBytesToFill))
2720 if (getLexer().isNot(AsmToken::EndOfStatement))
2721 return TokError("unexpected token in directive");
2730 // Compute alignment in bytes.
2732 // FIXME: Diagnose overflow.
2733 if (Alignment >= 32) {
2734 Error(AlignmentLoc, "invalid alignment value");
2738 Alignment = 1ULL << Alignment;
2740 // Reject alignments that aren't a power of two, for gas compatibility.
2741 if (!isPowerOf2_64(Alignment))
2742 Error(AlignmentLoc, "alignment must be a power of 2");
2745 // Diagnose non-sensical max bytes to align.
2746 if (MaxBytesLoc.isValid()) {
2747 if (MaxBytesToFill < 1) {
2748 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2749 "many bytes, ignoring maximum bytes expression");
2753 if (MaxBytesToFill >= Alignment) {
2754 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2760 // Check whether we should use optimal code alignment for this .align
2762 const MCSection *Section = getStreamer().getCurrentSection().first;
2763 assert(Section && "must have section to emit alignment");
2764 bool UseCodeAlign = Section->UseCodeAlign();
2765 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2766 ValueSize == 1 && UseCodeAlign) {
2767 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2769 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2770 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2777 /// parseDirectiveFile
2778 /// ::= .file [number] filename
2779 /// ::= .file number directory filename
2780 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2781 // FIXME: I'm not sure what this is.
2782 int64_t FileNumber = -1;
2783 SMLoc FileNumberLoc = getLexer().getLoc();
2784 if (getLexer().is(AsmToken::Integer)) {
2785 FileNumber = getTok().getIntVal();
2789 return TokError("file number less than one");
2792 if (getLexer().isNot(AsmToken::String))
2793 return TokError("unexpected token in '.file' directive");
2795 // Usually the directory and filename together, otherwise just the directory.
2796 // Allow the strings to have escaped octal character sequence.
2797 std::string Path = getTok().getString();
2798 if (parseEscapedString(Path))
2802 StringRef Directory;
2804 std::string FilenameData;
2805 if (getLexer().is(AsmToken::String)) {
2806 if (FileNumber == -1)
2807 return TokError("explicit path specified, but no file number");
2808 if (parseEscapedString(FilenameData))
2810 Filename = FilenameData;
2817 if (getLexer().isNot(AsmToken::EndOfStatement))
2818 return TokError("unexpected token in '.file' directive");
2820 if (FileNumber == -1)
2821 getStreamer().EmitFileDirective(Filename);
2823 if (getContext().getGenDwarfForAssembly())
2825 "input can't have .file dwarf directives when -g is "
2826 "used to generate dwarf debug info for assembly code");
2828 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2830 Error(FileNumberLoc, "file number already allocated");
2836 /// parseDirectiveLine
2837 /// ::= .line [number]
2838 bool AsmParser::parseDirectiveLine() {
2839 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2840 if (getLexer().isNot(AsmToken::Integer))
2841 return TokError("unexpected token in '.line' directive");
2843 int64_t LineNumber = getTok().getIntVal();
2847 // FIXME: Do something with the .line.
2850 if (getLexer().isNot(AsmToken::EndOfStatement))
2851 return TokError("unexpected token in '.line' directive");
2856 /// parseDirectiveLoc
2857 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2858 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2859 /// The first number is a file number, must have been previously assigned with
2860 /// a .file directive, the second number is the line number and optionally the
2861 /// third number is a column position (zero if not specified). The remaining
2862 /// optional items are .loc sub-directives.
2863 bool AsmParser::parseDirectiveLoc() {
2864 if (getLexer().isNot(AsmToken::Integer))
2865 return TokError("unexpected token in '.loc' directive");
2866 int64_t FileNumber = getTok().getIntVal();
2868 return TokError("file number less than one in '.loc' directive");
2869 if (!getContext().isValidDwarfFileNumber(FileNumber))
2870 return TokError("unassigned file number in '.loc' directive");
2873 int64_t LineNumber = 0;
2874 if (getLexer().is(AsmToken::Integer)) {
2875 LineNumber = getTok().getIntVal();
2877 return TokError("line number less than zero in '.loc' directive");
2881 int64_t ColumnPos = 0;
2882 if (getLexer().is(AsmToken::Integer)) {
2883 ColumnPos = getTok().getIntVal();
2885 return TokError("column position less than zero in '.loc' directive");
2889 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2891 int64_t Discriminator = 0;
2892 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2894 if (getLexer().is(AsmToken::EndOfStatement))
2898 SMLoc Loc = getTok().getLoc();
2899 if (parseIdentifier(Name))
2900 return TokError("unexpected token in '.loc' directive");
2902 if (Name == "basic_block")
2903 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2904 else if (Name == "prologue_end")
2905 Flags |= DWARF2_FLAG_PROLOGUE_END;
2906 else if (Name == "epilogue_begin")
2907 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2908 else if (Name == "is_stmt") {
2909 Loc = getTok().getLoc();
2910 const MCExpr *Value;
2911 if (parseExpression(Value))
2913 // The expression must be the constant 0 or 1.
2914 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2915 int Value = MCE->getValue();
2917 Flags &= ~DWARF2_FLAG_IS_STMT;
2918 else if (Value == 1)
2919 Flags |= DWARF2_FLAG_IS_STMT;
2921 return Error(Loc, "is_stmt value not 0 or 1");
2923 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2925 } else if (Name == "isa") {
2926 Loc = getTok().getLoc();
2927 const MCExpr *Value;
2928 if (parseExpression(Value))
2930 // The expression must be a constant greater or equal to 0.
2931 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2932 int Value = MCE->getValue();
2934 return Error(Loc, "isa number less than zero");
2937 return Error(Loc, "isa number not a constant value");
2939 } else if (Name == "discriminator") {
2940 if (parseAbsoluteExpression(Discriminator))
2943 return Error(Loc, "unknown sub-directive in '.loc' directive");
2946 if (getLexer().is(AsmToken::EndOfStatement))
2951 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2952 Isa, Discriminator, StringRef());
2957 /// parseDirectiveStabs
2958 /// ::= .stabs string, number, number, number
2959 bool AsmParser::parseDirectiveStabs() {
2960 return TokError("unsupported directive '.stabs'");
2963 /// parseDirectiveCFISections
2964 /// ::= .cfi_sections section [, section]
2965 bool AsmParser::parseDirectiveCFISections() {
2970 if (parseIdentifier(Name))
2971 return TokError("Expected an identifier");
2973 if (Name == ".eh_frame")
2975 else if (Name == ".debug_frame")
2978 if (getLexer().is(AsmToken::Comma)) {
2981 if (parseIdentifier(Name))
2982 return TokError("Expected an identifier");
2984 if (Name == ".eh_frame")
2986 else if (Name == ".debug_frame")
2990 getStreamer().EmitCFISections(EH, Debug);
2994 /// parseDirectiveCFIStartProc
2995 /// ::= .cfi_startproc [simple]
2996 bool AsmParser::parseDirectiveCFIStartProc() {
2998 if (getLexer().isNot(AsmToken::EndOfStatement))
2999 if (parseIdentifier(Simple) || Simple != "simple")
3000 return TokError("unexpected token in .cfi_startproc directive");
3002 getStreamer().EmitCFIStartProc(!Simple.empty());
3006 /// parseDirectiveCFIEndProc
3007 /// ::= .cfi_endproc
3008 bool AsmParser::parseDirectiveCFIEndProc() {
3009 getStreamer().EmitCFIEndProc();
3013 /// \brief parse register name or number.
3014 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
3015 SMLoc DirectiveLoc) {
3018 if (getLexer().isNot(AsmToken::Integer)) {
3019 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3021 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
3023 return parseAbsoluteExpression(Register);
3028 /// parseDirectiveCFIDefCfa
3029 /// ::= .cfi_def_cfa register, offset
3030 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3031 int64_t Register = 0;
3032 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3035 if (getLexer().isNot(AsmToken::Comma))
3036 return TokError("unexpected token in directive");
3040 if (parseAbsoluteExpression(Offset))
3043 getStreamer().EmitCFIDefCfa(Register, Offset);
3047 /// parseDirectiveCFIDefCfaOffset
3048 /// ::= .cfi_def_cfa_offset offset
3049 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3051 if (parseAbsoluteExpression(Offset))
3054 getStreamer().EmitCFIDefCfaOffset(Offset);
3058 /// parseDirectiveCFIRegister
3059 /// ::= .cfi_register register, register
3060 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3061 int64_t Register1 = 0;
3062 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3065 if (getLexer().isNot(AsmToken::Comma))
3066 return TokError("unexpected token in directive");
3069 int64_t Register2 = 0;
3070 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3073 getStreamer().EmitCFIRegister(Register1, Register2);
3077 /// parseDirectiveCFIWindowSave
3078 /// ::= .cfi_window_save
3079 bool AsmParser::parseDirectiveCFIWindowSave() {
3080 getStreamer().EmitCFIWindowSave();
3084 /// parseDirectiveCFIAdjustCfaOffset
3085 /// ::= .cfi_adjust_cfa_offset adjustment
3086 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3087 int64_t Adjustment = 0;
3088 if (parseAbsoluteExpression(Adjustment))
3091 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3095 /// parseDirectiveCFIDefCfaRegister
3096 /// ::= .cfi_def_cfa_register register
3097 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3098 int64_t Register = 0;
3099 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3102 getStreamer().EmitCFIDefCfaRegister(Register);
3106 /// parseDirectiveCFIOffset
3107 /// ::= .cfi_offset register, offset
3108 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3109 int64_t Register = 0;
3112 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3115 if (getLexer().isNot(AsmToken::Comma))
3116 return TokError("unexpected token in directive");
3119 if (parseAbsoluteExpression(Offset))
3122 getStreamer().EmitCFIOffset(Register, Offset);
3126 /// parseDirectiveCFIRelOffset
3127 /// ::= .cfi_rel_offset register, offset
3128 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3129 int64_t Register = 0;
3131 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3134 if (getLexer().isNot(AsmToken::Comma))
3135 return TokError("unexpected token in directive");
3139 if (parseAbsoluteExpression(Offset))
3142 getStreamer().EmitCFIRelOffset(Register, Offset);
3146 static bool isValidEncoding(int64_t Encoding) {
3147 if (Encoding & ~0xff)
3150 if (Encoding == dwarf::DW_EH_PE_omit)
3153 const unsigned Format = Encoding & 0xf;
3154 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3155 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3156 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3157 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3160 const unsigned Application = Encoding & 0x70;
3161 if (Application != dwarf::DW_EH_PE_absptr &&
3162 Application != dwarf::DW_EH_PE_pcrel)
3168 /// parseDirectiveCFIPersonalityOrLsda
3169 /// IsPersonality true for cfi_personality, false for cfi_lsda
3170 /// ::= .cfi_personality encoding, [symbol_name]
3171 /// ::= .cfi_lsda encoding, [symbol_name]
3172 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3173 int64_t Encoding = 0;
3174 if (parseAbsoluteExpression(Encoding))
3176 if (Encoding == dwarf::DW_EH_PE_omit)
3179 if (!isValidEncoding(Encoding))
3180 return TokError("unsupported encoding.");
3182 if (getLexer().isNot(AsmToken::Comma))
3183 return TokError("unexpected token in directive");
3187 if (parseIdentifier(Name))
3188 return TokError("expected identifier in directive");
3190 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3193 getStreamer().EmitCFIPersonality(Sym, Encoding);
3195 getStreamer().EmitCFILsda(Sym, Encoding);
3199 /// parseDirectiveCFIRememberState
3200 /// ::= .cfi_remember_state
3201 bool AsmParser::parseDirectiveCFIRememberState() {
3202 getStreamer().EmitCFIRememberState();
3206 /// parseDirectiveCFIRestoreState
3207 /// ::= .cfi_remember_state
3208 bool AsmParser::parseDirectiveCFIRestoreState() {
3209 getStreamer().EmitCFIRestoreState();
3213 /// parseDirectiveCFISameValue
3214 /// ::= .cfi_same_value register
3215 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3216 int64_t Register = 0;
3218 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3221 getStreamer().EmitCFISameValue(Register);
3225 /// parseDirectiveCFIRestore
3226 /// ::= .cfi_restore register
3227 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3228 int64_t Register = 0;
3229 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3232 getStreamer().EmitCFIRestore(Register);
3236 /// parseDirectiveCFIEscape
3237 /// ::= .cfi_escape expression[,...]
3238 bool AsmParser::parseDirectiveCFIEscape() {
3241 if (parseAbsoluteExpression(CurrValue))
3244 Values.push_back((uint8_t)CurrValue);
3246 while (getLexer().is(AsmToken::Comma)) {
3249 if (parseAbsoluteExpression(CurrValue))
3252 Values.push_back((uint8_t)CurrValue);
3255 getStreamer().EmitCFIEscape(Values);
3259 /// parseDirectiveCFISignalFrame
3260 /// ::= .cfi_signal_frame
3261 bool AsmParser::parseDirectiveCFISignalFrame() {
3262 if (getLexer().isNot(AsmToken::EndOfStatement))
3263 return Error(getLexer().getLoc(),
3264 "unexpected token in '.cfi_signal_frame'");
3266 getStreamer().EmitCFISignalFrame();
3270 /// parseDirectiveCFIUndefined
3271 /// ::= .cfi_undefined register
3272 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3273 int64_t Register = 0;
3275 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3278 getStreamer().EmitCFIUndefined(Register);
3282 /// parseDirectiveMacrosOnOff
3285 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3286 if (getLexer().isNot(AsmToken::EndOfStatement))
3287 return Error(getLexer().getLoc(),
3288 "unexpected token in '" + Directive + "' directive");
3290 setMacrosEnabled(Directive == ".macros_on");
3294 /// parseDirectiveMacro
3295 /// ::= .macro name[,] [parameters]
3296 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3298 if (parseIdentifier(Name))
3299 return TokError("expected identifier in '.macro' directive");
3301 if (getLexer().is(AsmToken::Comma))
3304 MCAsmMacroParameters Parameters;
3305 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3307 if (!Parameters.empty() && Parameters.back().Vararg)
3308 return Error(Lexer.getLoc(),
3309 "Vararg parameter '" + Parameters.back().Name +
3310 "' should be last one in the list of parameters.");
3312 MCAsmMacroParameter Parameter;
3313 if (parseIdentifier(Parameter.Name))
3314 return TokError("expected identifier in '.macro' directive");
3316 if (Lexer.is(AsmToken::Colon)) {
3317 Lex(); // consume ':'
3320 StringRef Qualifier;
3322 QualLoc = Lexer.getLoc();
3323 if (parseIdentifier(Qualifier))
3324 return Error(QualLoc, "missing parameter qualifier for "
3325 "'" + Parameter.Name + "' in macro '" + Name + "'");
3327 if (Qualifier == "req")
3328 Parameter.Required = true;
3329 else if (Qualifier == "vararg")
3330 Parameter.Vararg = true;
3332 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3333 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3336 if (getLexer().is(AsmToken::Equal)) {
3341 ParamLoc = Lexer.getLoc();
3342 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3345 if (Parameter.Required)
3346 Warning(ParamLoc, "pointless default value for required parameter "
3347 "'" + Parameter.Name + "' in macro '" + Name + "'");
3350 Parameters.push_back(std::move(Parameter));
3352 if (getLexer().is(AsmToken::Comma))
3356 // Eat the end of statement.
3359 AsmToken EndToken, StartToken = getTok();
3360 unsigned MacroDepth = 0;
3362 // Lex the macro definition.
3364 // Check whether we have reached the end of the file.
3365 if (getLexer().is(AsmToken::Eof))
3366 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3368 // Otherwise, check whether we have reach the .endmacro.
3369 if (getLexer().is(AsmToken::Identifier)) {
3370 if (getTok().getIdentifier() == ".endm" ||
3371 getTok().getIdentifier() == ".endmacro") {
3372 if (MacroDepth == 0) { // Outermost macro.
3373 EndToken = getTok();
3375 if (getLexer().isNot(AsmToken::EndOfStatement))
3376 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3380 // Otherwise we just found the end of an inner macro.
3383 } else if (getTok().getIdentifier() == ".macro") {
3384 // We allow nested macros. Those aren't instantiated until the outermost
3385 // macro is expanded so just ignore them for now.
3390 // Otherwise, scan til the end of the statement.
3391 eatToEndOfStatement();
3394 if (lookupMacro(Name)) {
3395 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3398 const char *BodyStart = StartToken.getLoc().getPointer();
3399 const char *BodyEnd = EndToken.getLoc().getPointer();
3400 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3401 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3402 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
3406 /// checkForBadMacro
3408 /// With the support added for named parameters there may be code out there that
3409 /// is transitioning from positional parameters. In versions of gas that did
3410 /// not support named parameters they would be ignored on the macro definition.
3411 /// But to support both styles of parameters this is not possible so if a macro
3412 /// definition has named parameters but does not use them and has what appears
3413 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3414 /// warning that the positional parameter found in body which have no effect.
3415 /// Hoping the developer will either remove the named parameters from the macro
3416 /// definition so the positional parameters get used if that was what was
3417 /// intended or change the macro to use the named parameters. It is possible
3418 /// this warning will trigger when the none of the named parameters are used
3419 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3420 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3422 ArrayRef<MCAsmMacroParameter> Parameters) {
3423 // If this macro is not defined with named parameters the warning we are
3424 // checking for here doesn't apply.
3425 unsigned NParameters = Parameters.size();
3426 if (NParameters == 0)
3429 bool NamedParametersFound = false;
3430 bool PositionalParametersFound = false;
3432 // Look at the body of the macro for use of both the named parameters and what
3433 // are likely to be positional parameters. This is what expandMacro() is
3434 // doing when it finds the parameters in the body.
3435 while (!Body.empty()) {
3436 // Scan for the next possible parameter.
3437 std::size_t End = Body.size(), Pos = 0;
3438 for (; Pos != End; ++Pos) {
3439 // Check for a substitution or escape.
3440 // This macro is defined with parameters, look for \foo, \bar, etc.
3441 if (Body[Pos] == '\\' && Pos + 1 != End)
3444 // This macro should have parameters, but look for $0, $1, ..., $n too.
3445 if (Body[Pos] != '$' || Pos + 1 == End)
3447 char Next = Body[Pos + 1];
3448 if (Next == '$' || Next == 'n' ||
3449 isdigit(static_cast<unsigned char>(Next)))
3453 // Check if we reached the end.
3457 if (Body[Pos] == '$') {
3458 switch (Body[Pos + 1]) {
3463 // $n => number of arguments
3465 PositionalParametersFound = true;
3468 // $[0-9] => argument
3470 PositionalParametersFound = true;
3476 unsigned I = Pos + 1;
3477 while (isIdentifierChar(Body[I]) && I + 1 != End)
3480 const char *Begin = Body.data() + Pos + 1;
3481 StringRef Argument(Begin, I - (Pos + 1));
3483 for (; Index < NParameters; ++Index)
3484 if (Parameters[Index].Name == Argument)
3487 if (Index == NParameters) {
3488 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3494 NamedParametersFound = true;
3495 Pos += 1 + Argument.size();
3498 // Update the scan point.
3499 Body = Body.substr(Pos);
3502 if (!NamedParametersFound && PositionalParametersFound)
3503 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3504 "used in macro body, possible positional parameter "
3505 "found in body which will have no effect");
3508 /// parseDirectiveExitMacro
3510 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3511 if (getLexer().isNot(AsmToken::EndOfStatement))
3512 return TokError("unexpected token in '" + Directive + "' directive");
3514 if (!isInsideMacroInstantiation())
3515 return TokError("unexpected '" + Directive + "' in file, "
3516 "no current macro definition");
3518 // Exit all conditionals that are active in the current macro.
3519 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3520 TheCondState = TheCondStack.back();
3521 TheCondStack.pop_back();
3528 /// parseDirectiveEndMacro
3531 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3532 if (getLexer().isNot(AsmToken::EndOfStatement))
3533 return TokError("unexpected token in '" + Directive + "' directive");
3535 // If we are inside a macro instantiation, terminate the current
3537 if (isInsideMacroInstantiation()) {
3542 // Otherwise, this .endmacro is a stray entry in the file; well formed
3543 // .endmacro directives are handled during the macro definition parsing.
3544 return TokError("unexpected '" + Directive + "' in file, "
3545 "no current macro definition");
3548 /// parseDirectivePurgeMacro
3550 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3552 if (parseIdentifier(Name))
3553 return TokError("expected identifier in '.purgem' directive");
3555 if (getLexer().isNot(AsmToken::EndOfStatement))
3556 return TokError("unexpected token in '.purgem' directive");
3558 if (!lookupMacro(Name))
3559 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3561 undefineMacro(Name);
3565 /// parseDirectiveBundleAlignMode
3566 /// ::= {.bundle_align_mode} expression
3567 bool AsmParser::parseDirectiveBundleAlignMode() {
3568 checkForValidSection();
3570 // Expect a single argument: an expression that evaluates to a constant
3571 // in the inclusive range 0-30.
3572 SMLoc ExprLoc = getLexer().getLoc();
3573 int64_t AlignSizePow2;
3574 if (parseAbsoluteExpression(AlignSizePow2))
3576 else if (getLexer().isNot(AsmToken::EndOfStatement))
3577 return TokError("unexpected token after expression in"
3578 " '.bundle_align_mode' directive");
3579 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3580 return Error(ExprLoc,
3581 "invalid bundle alignment size (expected between 0 and 30)");
3585 // Because of AlignSizePow2's verified range we can safely truncate it to
3587 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3591 /// parseDirectiveBundleLock
3592 /// ::= {.bundle_lock} [align_to_end]
3593 bool AsmParser::parseDirectiveBundleLock() {
3594 checkForValidSection();
3595 bool AlignToEnd = false;
3597 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3599 SMLoc Loc = getTok().getLoc();
3600 const char *kInvalidOptionError =
3601 "invalid option for '.bundle_lock' directive";
3603 if (parseIdentifier(Option))
3604 return Error(Loc, kInvalidOptionError);
3606 if (Option != "align_to_end")
3607 return Error(Loc, kInvalidOptionError);
3608 else if (getLexer().isNot(AsmToken::EndOfStatement))
3610 "unexpected token after '.bundle_lock' directive option");
3616 getStreamer().EmitBundleLock(AlignToEnd);
3620 /// parseDirectiveBundleLock
3621 /// ::= {.bundle_lock}
3622 bool AsmParser::parseDirectiveBundleUnlock() {
3623 checkForValidSection();
3625 if (getLexer().isNot(AsmToken::EndOfStatement))
3626 return TokError("unexpected token in '.bundle_unlock' directive");
3629 getStreamer().EmitBundleUnlock();
3633 /// parseDirectiveSpace
3634 /// ::= (.skip | .space) expression [ , expression ]
3635 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3636 checkForValidSection();
3639 if (parseAbsoluteExpression(NumBytes))
3642 int64_t FillExpr = 0;
3643 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3644 if (getLexer().isNot(AsmToken::Comma))
3645 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3648 if (parseAbsoluteExpression(FillExpr))
3651 if (getLexer().isNot(AsmToken::EndOfStatement))
3652 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3658 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3661 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3662 getStreamer().EmitFill(NumBytes, FillExpr);
3667 /// parseDirectiveLEB128
3668 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
3669 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3670 checkForValidSection();
3671 const MCExpr *Value;
3674 if (parseExpression(Value))
3678 getStreamer().EmitSLEB128Value(Value);
3680 getStreamer().EmitULEB128Value(Value);
3682 if (getLexer().is(AsmToken::EndOfStatement))
3685 if (getLexer().isNot(AsmToken::Comma))
3686 return TokError("unexpected token in directive");
3693 /// parseDirectiveSymbolAttribute
3694 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3695 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3696 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3699 SMLoc Loc = getTok().getLoc();
3701 if (parseIdentifier(Name))
3702 return Error(Loc, "expected identifier in directive");
3704 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3706 // Assembler local symbols don't make any sense here. Complain loudly.
3707 if (Sym->isTemporary())
3708 return Error(Loc, "non-local symbol required in directive");
3710 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3711 return Error(Loc, "unable to emit symbol attribute");
3713 if (getLexer().is(AsmToken::EndOfStatement))
3716 if (getLexer().isNot(AsmToken::Comma))
3717 return TokError("unexpected token in directive");
3726 /// parseDirectiveComm
3727 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3728 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3729 checkForValidSection();
3731 SMLoc IDLoc = getLexer().getLoc();
3733 if (parseIdentifier(Name))
3734 return TokError("expected identifier in directive");
3736 // Handle the identifier as the key symbol.
3737 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3739 if (getLexer().isNot(AsmToken::Comma))
3740 return TokError("unexpected token in directive");
3744 SMLoc SizeLoc = getLexer().getLoc();
3745 if (parseAbsoluteExpression(Size))
3748 int64_t Pow2Alignment = 0;
3749 SMLoc Pow2AlignmentLoc;
3750 if (getLexer().is(AsmToken::Comma)) {
3752 Pow2AlignmentLoc = getLexer().getLoc();
3753 if (parseAbsoluteExpression(Pow2Alignment))
3756 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3757 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3758 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3760 // If this target takes alignments in bytes (not log) validate and convert.
3761 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3762 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3763 if (!isPowerOf2_64(Pow2Alignment))
3764 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3765 Pow2Alignment = Log2_64(Pow2Alignment);
3769 if (getLexer().isNot(AsmToken::EndOfStatement))
3770 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3774 // NOTE: a size of zero for a .comm should create a undefined symbol
3775 // but a size of .lcomm creates a bss symbol of size zero.
3777 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3778 "be less than zero");
3780 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3781 // may internally end up wanting an alignment in bytes.
3782 // FIXME: Diagnose overflow.
3783 if (Pow2Alignment < 0)
3784 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3785 "alignment, can't be less than zero");
3787 if (!Sym->isUndefined())
3788 return Error(IDLoc, "invalid symbol redefinition");
3790 // Create the Symbol as a common or local common with Size and Pow2Alignment
3792 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3796 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3800 /// parseDirectiveAbort
3801 /// ::= .abort [... message ...]
3802 bool AsmParser::parseDirectiveAbort() {
3803 // FIXME: Use loc from directive.
3804 SMLoc Loc = getLexer().getLoc();
3806 StringRef Str = parseStringToEndOfStatement();
3807 if (getLexer().isNot(AsmToken::EndOfStatement))
3808 return TokError("unexpected token in '.abort' directive");
3813 Error(Loc, ".abort detected. Assembly stopping.");
3815 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3816 // FIXME: Actually abort assembly here.
3821 /// parseDirectiveInclude
3822 /// ::= .include "filename"
3823 bool AsmParser::parseDirectiveInclude() {
3824 if (getLexer().isNot(AsmToken::String))
3825 return TokError("expected string in '.include' directive");
3827 // Allow the strings to have escaped octal character sequence.
3828 std::string Filename;
3829 if (parseEscapedString(Filename))
3831 SMLoc IncludeLoc = getLexer().getLoc();
3834 if (getLexer().isNot(AsmToken::EndOfStatement))
3835 return TokError("unexpected token in '.include' directive");
3837 // Attempt to switch the lexer to the included file before consuming the end
3838 // of statement to avoid losing it when we switch.
3839 if (enterIncludeFile(Filename)) {
3840 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3847 /// parseDirectiveIncbin
3848 /// ::= .incbin "filename"
3849 bool AsmParser::parseDirectiveIncbin() {
3850 if (getLexer().isNot(AsmToken::String))
3851 return TokError("expected string in '.incbin' directive");
3853 // Allow the strings to have escaped octal character sequence.
3854 std::string Filename;
3855 if (parseEscapedString(Filename))
3857 SMLoc IncbinLoc = getLexer().getLoc();
3860 if (getLexer().isNot(AsmToken::EndOfStatement))
3861 return TokError("unexpected token in '.incbin' directive");
3863 // Attempt to process the included file.
3864 if (processIncbinFile(Filename)) {
3865 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3872 /// parseDirectiveIf
3873 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
3874 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
3875 TheCondStack.push_back(TheCondState);
3876 TheCondState.TheCond = AsmCond::IfCond;
3877 if (TheCondState.Ignore) {
3878 eatToEndOfStatement();
3881 if (parseAbsoluteExpression(ExprValue))
3884 if (getLexer().isNot(AsmToken::EndOfStatement))
3885 return TokError("unexpected token in '.if' directive");
3891 llvm_unreachable("unsupported directive");
3896 ExprValue = ExprValue == 0;
3899 ExprValue = ExprValue >= 0;
3902 ExprValue = ExprValue > 0;
3905 ExprValue = ExprValue <= 0;
3908 ExprValue = ExprValue < 0;
3912 TheCondState.CondMet = ExprValue;
3913 TheCondState.Ignore = !TheCondState.CondMet;
3919 /// parseDirectiveIfb
3921 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3922 TheCondStack.push_back(TheCondState);
3923 TheCondState.TheCond = AsmCond::IfCond;
3925 if (TheCondState.Ignore) {
3926 eatToEndOfStatement();
3928 StringRef Str = parseStringToEndOfStatement();
3930 if (getLexer().isNot(AsmToken::EndOfStatement))
3931 return TokError("unexpected token in '.ifb' directive");
3935 TheCondState.CondMet = ExpectBlank == Str.empty();
3936 TheCondState.Ignore = !TheCondState.CondMet;
3942 /// parseDirectiveIfc
3943 /// ::= .ifc string1, string2
3944 /// ::= .ifnc string1, string2
3945 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3946 TheCondStack.push_back(TheCondState);
3947 TheCondState.TheCond = AsmCond::IfCond;
3949 if (TheCondState.Ignore) {
3950 eatToEndOfStatement();
3952 StringRef Str1 = parseStringToComma();
3954 if (getLexer().isNot(AsmToken::Comma))
3955 return TokError("unexpected token in '.ifc' directive");
3959 StringRef Str2 = parseStringToEndOfStatement();
3961 if (getLexer().isNot(AsmToken::EndOfStatement))
3962 return TokError("unexpected token in '.ifc' directive");
3966 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3967 TheCondState.Ignore = !TheCondState.CondMet;
3973 /// parseDirectiveIfeqs
3974 /// ::= .ifeqs string1, string2
3975 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
3976 if (Lexer.isNot(AsmToken::String)) {
3978 TokError("expected string parameter for '.ifeqs' directive");
3980 TokError("expected string parameter for '.ifnes' directive");
3981 eatToEndOfStatement();
3985 StringRef String1 = getTok().getStringContents();
3988 if (Lexer.isNot(AsmToken::Comma)) {
3990 TokError("expected comma after first string for '.ifeqs' directive");
3992 TokError("expected comma after first string for '.ifnes' directive");
3993 eatToEndOfStatement();
3999 if (Lexer.isNot(AsmToken::String)) {
4001 TokError("expected string parameter for '.ifeqs' directive");
4003 TokError("expected string parameter for '.ifnes' directive");
4004 eatToEndOfStatement();
4008 StringRef String2 = getTok().getStringContents();
4011 TheCondStack.push_back(TheCondState);
4012 TheCondState.TheCond = AsmCond::IfCond;
4013 TheCondState.CondMet = ExpectEqual == (String1 == String2);
4014 TheCondState.Ignore = !TheCondState.CondMet;
4019 /// parseDirectiveIfdef
4020 /// ::= .ifdef symbol
4021 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
4023 TheCondStack.push_back(TheCondState);
4024 TheCondState.TheCond = AsmCond::IfCond;
4026 if (TheCondState.Ignore) {
4027 eatToEndOfStatement();
4029 if (parseIdentifier(Name))
4030 return TokError("expected identifier after '.ifdef'");
4034 MCSymbol *Sym = getContext().lookupSymbol(Name);
4037 TheCondState.CondMet = (Sym && !Sym->isUndefined());
4039 TheCondState.CondMet = (!Sym || Sym->isUndefined());
4040 TheCondState.Ignore = !TheCondState.CondMet;
4046 /// parseDirectiveElseIf
4047 /// ::= .elseif expression
4048 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4049 if (TheCondState.TheCond != AsmCond::IfCond &&
4050 TheCondState.TheCond != AsmCond::ElseIfCond)
4051 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4053 TheCondState.TheCond = AsmCond::ElseIfCond;
4055 bool LastIgnoreState = false;
4056 if (!TheCondStack.empty())
4057 LastIgnoreState = TheCondStack.back().Ignore;
4058 if (LastIgnoreState || TheCondState.CondMet) {
4059 TheCondState.Ignore = true;
4060 eatToEndOfStatement();
4063 if (parseAbsoluteExpression(ExprValue))
4066 if (getLexer().isNot(AsmToken::EndOfStatement))
4067 return TokError("unexpected token in '.elseif' directive");
4070 TheCondState.CondMet = ExprValue;
4071 TheCondState.Ignore = !TheCondState.CondMet;
4077 /// parseDirectiveElse
4079 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4080 if (getLexer().isNot(AsmToken::EndOfStatement))
4081 return TokError("unexpected token in '.else' directive");
4085 if (TheCondState.TheCond != AsmCond::IfCond &&
4086 TheCondState.TheCond != AsmCond::ElseIfCond)
4087 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4089 TheCondState.TheCond = AsmCond::ElseCond;
4090 bool LastIgnoreState = false;
4091 if (!TheCondStack.empty())
4092 LastIgnoreState = TheCondStack.back().Ignore;
4093 if (LastIgnoreState || TheCondState.CondMet)
4094 TheCondState.Ignore = true;
4096 TheCondState.Ignore = false;
4101 /// parseDirectiveEnd
4103 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4104 if (getLexer().isNot(AsmToken::EndOfStatement))
4105 return TokError("unexpected token in '.end' directive");
4109 while (Lexer.isNot(AsmToken::Eof))
4115 /// parseDirectiveError
4117 /// ::= .error [string]
4118 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4119 if (!TheCondStack.empty()) {
4120 if (TheCondStack.back().Ignore) {
4121 eatToEndOfStatement();
4127 return Error(L, ".err encountered");
4129 StringRef Message = ".error directive invoked in source file";
4130 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4131 if (Lexer.isNot(AsmToken::String)) {
4132 TokError(".error argument must be a string");
4133 eatToEndOfStatement();
4137 Message = getTok().getStringContents();
4145 /// parseDirectiveWarning
4146 /// ::= .warning [string]
4147 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4148 if (!TheCondStack.empty()) {
4149 if (TheCondStack.back().Ignore) {
4150 eatToEndOfStatement();
4155 StringRef Message = ".warning directive invoked in source file";
4156 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4157 if (Lexer.isNot(AsmToken::String)) {
4158 TokError(".warning argument must be a string");
4159 eatToEndOfStatement();
4163 Message = getTok().getStringContents();
4167 Warning(L, Message);
4171 /// parseDirectiveEndIf
4173 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4174 if (getLexer().isNot(AsmToken::EndOfStatement))
4175 return TokError("unexpected token in '.endif' directive");
4179 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4180 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4182 if (!TheCondStack.empty()) {
4183 TheCondState = TheCondStack.back();
4184 TheCondStack.pop_back();
4190 void AsmParser::initializeDirectiveKindMap() {
4191 DirectiveKindMap[".set"] = DK_SET;
4192 DirectiveKindMap[".equ"] = DK_EQU;
4193 DirectiveKindMap[".equiv"] = DK_EQUIV;
4194 DirectiveKindMap[".ascii"] = DK_ASCII;
4195 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4196 DirectiveKindMap[".string"] = DK_STRING;
4197 DirectiveKindMap[".byte"] = DK_BYTE;
4198 DirectiveKindMap[".short"] = DK_SHORT;
4199 DirectiveKindMap[".value"] = DK_VALUE;
4200 DirectiveKindMap[".2byte"] = DK_2BYTE;
4201 DirectiveKindMap[".long"] = DK_LONG;
4202 DirectiveKindMap[".int"] = DK_INT;
4203 DirectiveKindMap[".4byte"] = DK_4BYTE;
4204 DirectiveKindMap[".quad"] = DK_QUAD;
4205 DirectiveKindMap[".8byte"] = DK_8BYTE;
4206 DirectiveKindMap[".octa"] = DK_OCTA;
4207 DirectiveKindMap[".single"] = DK_SINGLE;
4208 DirectiveKindMap[".float"] = DK_FLOAT;
4209 DirectiveKindMap[".double"] = DK_DOUBLE;
4210 DirectiveKindMap[".align"] = DK_ALIGN;
4211 DirectiveKindMap[".align32"] = DK_ALIGN32;
4212 DirectiveKindMap[".balign"] = DK_BALIGN;
4213 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4214 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4215 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4216 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4217 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4218 DirectiveKindMap[".org"] = DK_ORG;
4219 DirectiveKindMap[".fill"] = DK_FILL;
4220 DirectiveKindMap[".zero"] = DK_ZERO;
4221 DirectiveKindMap[".extern"] = DK_EXTERN;
4222 DirectiveKindMap[".globl"] = DK_GLOBL;
4223 DirectiveKindMap[".global"] = DK_GLOBAL;
4224 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4225 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4226 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4227 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4228 DirectiveKindMap[".reference"] = DK_REFERENCE;
4229 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4230 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4231 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4232 DirectiveKindMap[".comm"] = DK_COMM;
4233 DirectiveKindMap[".common"] = DK_COMMON;
4234 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4235 DirectiveKindMap[".abort"] = DK_ABORT;
4236 DirectiveKindMap[".include"] = DK_INCLUDE;
4237 DirectiveKindMap[".incbin"] = DK_INCBIN;
4238 DirectiveKindMap[".code16"] = DK_CODE16;
4239 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4240 DirectiveKindMap[".rept"] = DK_REPT;
4241 DirectiveKindMap[".rep"] = DK_REPT;
4242 DirectiveKindMap[".irp"] = DK_IRP;
4243 DirectiveKindMap[".irpc"] = DK_IRPC;
4244 DirectiveKindMap[".endr"] = DK_ENDR;
4245 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4246 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4247 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4248 DirectiveKindMap[".if"] = DK_IF;
4249 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4250 DirectiveKindMap[".ifge"] = DK_IFGE;
4251 DirectiveKindMap[".ifgt"] = DK_IFGT;
4252 DirectiveKindMap[".ifle"] = DK_IFLE;
4253 DirectiveKindMap[".iflt"] = DK_IFLT;
4254 DirectiveKindMap[".ifne"] = DK_IFNE;
4255 DirectiveKindMap[".ifb"] = DK_IFB;
4256 DirectiveKindMap[".ifnb"] = DK_IFNB;
4257 DirectiveKindMap[".ifc"] = DK_IFC;
4258 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4259 DirectiveKindMap[".ifnc"] = DK_IFNC;
4260 DirectiveKindMap[".ifnes"] = DK_IFNES;
4261 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4262 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4263 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4264 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4265 DirectiveKindMap[".else"] = DK_ELSE;
4266 DirectiveKindMap[".end"] = DK_END;
4267 DirectiveKindMap[".endif"] = DK_ENDIF;
4268 DirectiveKindMap[".skip"] = DK_SKIP;
4269 DirectiveKindMap[".space"] = DK_SPACE;
4270 DirectiveKindMap[".file"] = DK_FILE;
4271 DirectiveKindMap[".line"] = DK_LINE;
4272 DirectiveKindMap[".loc"] = DK_LOC;
4273 DirectiveKindMap[".stabs"] = DK_STABS;
4274 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4275 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4276 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4277 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4278 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4279 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4280 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4281 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4282 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4283 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4284 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4285 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4286 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4287 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4288 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4289 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4290 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4291 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4292 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4293 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4294 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4295 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4296 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4297 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4298 DirectiveKindMap[".macro"] = DK_MACRO;
4299 DirectiveKindMap[".exitm"] = DK_EXITM;
4300 DirectiveKindMap[".endm"] = DK_ENDM;
4301 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4302 DirectiveKindMap[".purgem"] = DK_PURGEM;
4303 DirectiveKindMap[".err"] = DK_ERR;
4304 DirectiveKindMap[".error"] = DK_ERROR;
4305 DirectiveKindMap[".warning"] = DK_WARNING;
4308 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4309 AsmToken EndToken, StartToken = getTok();
4311 unsigned NestLevel = 0;
4313 // Check whether we have reached the end of the file.
4314 if (getLexer().is(AsmToken::Eof)) {
4315 Error(DirectiveLoc, "no matching '.endr' in definition");
4319 if (Lexer.is(AsmToken::Identifier) &&
4320 (getTok().getIdentifier() == ".rept")) {
4324 // Otherwise, check whether we have reached the .endr.
4325 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4326 if (NestLevel == 0) {
4327 EndToken = getTok();
4329 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4330 TokError("unexpected token in '.endr' directive");
4338 // Otherwise, scan till the end of the statement.
4339 eatToEndOfStatement();
4342 const char *BodyStart = StartToken.getLoc().getPointer();
4343 const char *BodyEnd = EndToken.getLoc().getPointer();
4344 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4346 // We Are Anonymous.
4347 MacroLikeBodies.push_back(
4348 MCAsmMacro(StringRef(), Body, MCAsmMacroParameters()));
4349 return &MacroLikeBodies.back();
4352 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4353 raw_svector_ostream &OS) {
4356 std::unique_ptr<MemoryBuffer> Instantiation =
4357 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4359 // Create the macro instantiation object and add to the current macro
4360 // instantiation stack.
4361 MacroInstantiation *MI = new MacroInstantiation(
4362 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
4363 ActiveMacros.push_back(MI);
4365 // Jump to the macro instantiation and prime the lexer.
4366 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
4367 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
4371 /// parseDirectiveRept
4372 /// ::= .rep | .rept count
4373 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4374 const MCExpr *CountExpr;
4375 SMLoc CountLoc = getTok().getLoc();
4376 if (parseExpression(CountExpr))
4380 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4381 eatToEndOfStatement();
4382 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4386 return Error(CountLoc, "Count is negative");
4388 if (Lexer.isNot(AsmToken::EndOfStatement))
4389 return TokError("unexpected token in '" + Dir + "' directive");
4391 // Eat the end of statement.
4394 // Lex the rept definition.
4395 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4399 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4400 // to hold the macro body with substitutions.
4401 SmallString<256> Buf;
4402 raw_svector_ostream OS(Buf);
4404 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4405 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
4408 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4413 /// parseDirectiveIrp
4414 /// ::= .irp symbol,values
4415 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4416 MCAsmMacroParameter Parameter;
4418 if (parseIdentifier(Parameter.Name))
4419 return TokError("expected identifier in '.irp' directive");
4421 if (Lexer.isNot(AsmToken::Comma))
4422 return TokError("expected comma in '.irp' directive");
4426 MCAsmMacroArguments A;
4427 if (parseMacroArguments(nullptr, A))
4430 // Eat the end of statement.
4433 // Lex the irp definition.
4434 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4438 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4439 // to hold the macro body with substitutions.
4440 SmallString<256> Buf;
4441 raw_svector_ostream OS(Buf);
4443 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4444 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4445 // This is undocumented, but GAS seems to support it.
4446 if (expandMacro(OS, M->Body, Parameter, *i, true, getTok().getLoc()))
4450 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4455 /// parseDirectiveIrpc
4456 /// ::= .irpc symbol,values
4457 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4458 MCAsmMacroParameter Parameter;
4460 if (parseIdentifier(Parameter.Name))
4461 return TokError("expected identifier in '.irpc' directive");
4463 if (Lexer.isNot(AsmToken::Comma))
4464 return TokError("expected comma in '.irpc' directive");
4468 MCAsmMacroArguments A;
4469 if (parseMacroArguments(nullptr, A))
4472 if (A.size() != 1 || A.front().size() != 1)
4473 return TokError("unexpected token in '.irpc' directive");
4475 // Eat the end of statement.
4478 // Lex the irpc definition.
4479 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4483 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4484 // to hold the macro body with substitutions.
4485 SmallString<256> Buf;
4486 raw_svector_ostream OS(Buf);
4488 StringRef Values = A.front().front().getString();
4489 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4490 MCAsmMacroArgument Arg;
4491 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4493 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4494 // This is undocumented, but GAS seems to support it.
4495 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
4499 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4504 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4505 if (ActiveMacros.empty())
4506 return TokError("unmatched '.endr' directive");
4508 // The only .repl that should get here are the ones created by
4509 // instantiateMacroLikeBody.
4510 assert(getLexer().is(AsmToken::EndOfStatement));
4516 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4518 const MCExpr *Value;
4519 SMLoc ExprLoc = getLexer().getLoc();
4520 if (parseExpression(Value))
4522 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4524 return Error(ExprLoc, "unexpected expression in _emit");
4525 uint64_t IntValue = MCE->getValue();
4526 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4527 return Error(ExprLoc, "literal value out of range for directive");
4529 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4533 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4534 const MCExpr *Value;
4535 SMLoc ExprLoc = getLexer().getLoc();
4536 if (parseExpression(Value))
4538 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4540 return Error(ExprLoc, "unexpected expression in align");
4541 uint64_t IntValue = MCE->getValue();
4542 if (!isPowerOf2_64(IntValue))
4543 return Error(ExprLoc, "literal value not a power of two greater then zero");
4545 Info.AsmRewrites->push_back(
4546 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4550 // We are comparing pointers, but the pointers are relative to a single string.
4551 // Thus, this should always be deterministic.
4552 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4553 const AsmRewrite *AsmRewriteB) {
4554 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4556 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4559 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4560 // rewrite to the same location. Make sure the SizeDirective rewrite is
4561 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4562 // ensures the sort algorithm is stable.
4563 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4564 AsmRewritePrecedence[AsmRewriteB->Kind])
4567 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4568 AsmRewritePrecedence[AsmRewriteB->Kind])
4570 llvm_unreachable("Unstable rewrite sort.");
4573 bool AsmParser::parseMSInlineAsm(
4574 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4575 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4576 SmallVectorImpl<std::string> &Constraints,
4577 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4578 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4579 SmallVector<void *, 4> InputDecls;
4580 SmallVector<void *, 4> OutputDecls;
4581 SmallVector<bool, 4> InputDeclsAddressOf;
4582 SmallVector<bool, 4> OutputDeclsAddressOf;
4583 SmallVector<std::string, 4> InputConstraints;
4584 SmallVector<std::string, 4> OutputConstraints;
4585 SmallVector<unsigned, 4> ClobberRegs;
4587 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4592 // While we have input, parse each statement.
4593 unsigned InputIdx = 0;
4594 unsigned OutputIdx = 0;
4595 while (getLexer().isNot(AsmToken::Eof)) {
4596 ParseStatementInfo Info(&AsmStrRewrites);
4597 if (parseStatement(Info, &SI))
4600 if (Info.ParseError)
4603 if (Info.Opcode == ~0U)
4606 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4608 // Build the list of clobbers, outputs and inputs.
4609 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4610 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4613 if (Operand.isImm())
4616 // Register operand.
4617 if (Operand.isReg() && !Operand.needAddressOf() &&
4618 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
4619 unsigned NumDefs = Desc.getNumDefs();
4621 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4622 ClobberRegs.push_back(Operand.getReg());
4626 // Expr/Input or Output.
4627 StringRef SymName = Operand.getSymName();
4628 if (SymName.empty())
4631 void *OpDecl = Operand.getOpDecl();
4635 bool isOutput = (i == 1) && Desc.mayStore();
4636 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4639 OutputDecls.push_back(OpDecl);
4640 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4641 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
4642 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4644 InputDecls.push_back(OpDecl);
4645 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4646 InputConstraints.push_back(Operand.getConstraint().str());
4647 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4651 // Consider implicit defs to be clobbers. Think of cpuid and push.
4652 ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
4653 Desc.getNumImplicitDefs());
4654 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
4657 // Set the number of Outputs and Inputs.
4658 NumOutputs = OutputDecls.size();
4659 NumInputs = InputDecls.size();
4661 // Set the unique clobbers.
4662 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4663 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4665 Clobbers.assign(ClobberRegs.size(), std::string());
4666 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4667 raw_string_ostream OS(Clobbers[I]);
4668 IP->printRegName(OS, ClobberRegs[I]);
4671 // Merge the various outputs and inputs. Output are expected first.
4672 if (NumOutputs || NumInputs) {
4673 unsigned NumExprs = NumOutputs + NumInputs;
4674 OpDecls.resize(NumExprs);
4675 Constraints.resize(NumExprs);
4676 for (unsigned i = 0; i < NumOutputs; ++i) {
4677 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4678 Constraints[i] = OutputConstraints[i];
4680 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4681 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4682 Constraints[j] = InputConstraints[i];
4686 // Build the IR assembly string.
4687 std::string AsmStringIR;
4688 raw_string_ostream OS(AsmStringIR);
4689 StringRef ASMString =
4690 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4691 const char *AsmStart = ASMString.begin();
4692 const char *AsmEnd = ASMString.end();
4693 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4694 for (const AsmRewrite &AR : AsmStrRewrites) {
4695 AsmRewriteKind Kind = AR.Kind;
4696 if (Kind == AOK_Delete)
4699 const char *Loc = AR.Loc.getPointer();
4700 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4702 // Emit everything up to the immediate/expression.
4703 if (unsigned Len = Loc - AsmStart)
4704 OS << StringRef(AsmStart, Len);
4706 // Skip the original expression.
4707 if (Kind == AOK_Skip) {
4708 AsmStart = Loc + AR.Len;
4712 unsigned AdditionalSkip = 0;
4713 // Rewrite expressions in $N notation.
4718 OS << "$$" << AR.Val;
4724 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
4727 OS << '$' << InputIdx++;
4730 OS << '$' << OutputIdx++;
4732 case AOK_SizeDirective:
4735 case 8: OS << "byte ptr "; break;
4736 case 16: OS << "word ptr "; break;
4737 case 32: OS << "dword ptr "; break;
4738 case 64: OS << "qword ptr "; break;
4739 case 80: OS << "xword ptr "; break;
4740 case 128: OS << "xmmword ptr "; break;
4741 case 256: OS << "ymmword ptr "; break;
4748 unsigned Val = AR.Val;
4749 OS << ".align " << Val;
4751 // Skip the original immediate.
4752 assert(Val < 10 && "Expected alignment less then 2^10.");
4753 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4756 case AOK_DotOperator:
4757 // Insert the dot if the user omitted it.
4759 if (AsmStringIR.back() != '.')
4765 // Skip the original expression.
4766 AsmStart = Loc + AR.Len + AdditionalSkip;
4769 // Emit the remainder of the asm string.
4770 if (AsmStart != AsmEnd)
4771 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4773 AsmString = OS.str();
4777 /// \brief Create an MCAsmParser instance.
4778 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4779 MCStreamer &Out, const MCAsmInfo &MAI) {
4780 return new AsmParser(SM, C, Out, MAI);