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 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
330 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
331 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
333 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
335 // Generic (target and platform independent) directive parsing.
337 DK_NO_DIRECTIVE, // Placeholder
338 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
339 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
340 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
341 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
342 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
343 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
344 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
345 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
346 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
347 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
348 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
349 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
350 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
351 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
352 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
353 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
354 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
355 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
356 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
357 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
358 DK_MACROS_ON, DK_MACROS_OFF,
359 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
360 DK_SLEB128, DK_ULEB128,
361 DK_ERR, DK_ERROR, DK_WARNING,
365 /// \brief Maps directive name --> DirectiveKind enum, for
366 /// directives parsed by this class.
367 StringMap<DirectiveKind> DirectiveKindMap;
369 // ".ascii", ".asciz", ".string"
370 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
371 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
372 bool parseDirectiveOctaValue(); // ".octa"
373 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
374 bool parseDirectiveFill(); // ".fill"
375 bool parseDirectiveZero(); // ".zero"
376 // ".set", ".equ", ".equiv"
377 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
378 bool parseDirectiveOrg(); // ".org"
379 // ".align{,32}", ".p2align{,w,l}"
380 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
382 // ".file", ".line", ".loc", ".stabs"
383 bool parseDirectiveFile(SMLoc DirectiveLoc);
384 bool parseDirectiveLine();
385 bool parseDirectiveLoc();
386 bool parseDirectiveStabs();
389 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
390 bool parseDirectiveCFIWindowSave();
391 bool parseDirectiveCFISections();
392 bool parseDirectiveCFIStartProc();
393 bool parseDirectiveCFIEndProc();
394 bool parseDirectiveCFIDefCfaOffset();
395 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
396 bool parseDirectiveCFIAdjustCfaOffset();
397 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
398 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
399 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
400 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
401 bool parseDirectiveCFIRememberState();
402 bool parseDirectiveCFIRestoreState();
403 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
404 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
405 bool parseDirectiveCFIEscape();
406 bool parseDirectiveCFISignalFrame();
407 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
410 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
411 bool parseDirectiveExitMacro(StringRef Directive);
412 bool parseDirectiveEndMacro(StringRef Directive);
413 bool parseDirectiveMacro(SMLoc DirectiveLoc);
414 bool parseDirectiveMacrosOnOff(StringRef Directive);
416 // ".bundle_align_mode"
417 bool parseDirectiveBundleAlignMode();
419 bool parseDirectiveBundleLock();
421 bool parseDirectiveBundleUnlock();
424 bool parseDirectiveSpace(StringRef IDVal);
426 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
427 bool parseDirectiveLEB128(bool Signed);
429 /// \brief Parse a directive like ".globl" which
430 /// accepts a single symbol (which should be a label or an external).
431 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
433 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
435 bool parseDirectiveAbort(); // ".abort"
436 bool parseDirectiveInclude(); // ".include"
437 bool parseDirectiveIncbin(); // ".incbin"
439 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
440 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
441 // ".ifb" or ".ifnb", depending on ExpectBlank.
442 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
443 // ".ifc" or ".ifnc", depending on ExpectEqual.
444 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
445 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
446 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
447 // ".ifdef" or ".ifndef", depending on expect_defined
448 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
449 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
450 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
451 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
452 bool parseEscapedString(std::string &Data) override;
454 const MCExpr *applyModifierToExpr(const MCExpr *E,
455 MCSymbolRefExpr::VariantKind Variant);
457 // Macro-like directives
458 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
459 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
460 raw_svector_ostream &OS);
461 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
462 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
463 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
464 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
466 // "_emit" or "__emit"
467 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
471 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
474 bool parseDirectiveEnd(SMLoc DirectiveLoc);
476 // ".err" or ".error"
477 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
480 bool parseDirectiveWarning(SMLoc DirectiveLoc);
482 void initializeDirectiveKindMap();
488 extern MCAsmParserExtension *createDarwinAsmParser();
489 extern MCAsmParserExtension *createELFAsmParser();
490 extern MCAsmParserExtension *createCOFFAsmParser();
494 enum { DEFAULT_ADDRSPACE = 0 };
496 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
497 const MCAsmInfo &MAI)
498 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
499 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
500 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
501 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
502 // Save the old handler.
503 SavedDiagHandler = SrcMgr.getDiagHandler();
504 SavedDiagContext = SrcMgr.getDiagContext();
505 // Set our own handler which calls the saved handler.
506 SrcMgr.setDiagHandler(DiagHandler, this);
507 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
509 // Initialize the platform / file format parser.
510 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
511 case MCObjectFileInfo::IsCOFF:
512 PlatformParser.reset(createCOFFAsmParser());
514 case MCObjectFileInfo::IsMachO:
515 PlatformParser.reset(createDarwinAsmParser());
518 case MCObjectFileInfo::IsELF:
519 PlatformParser.reset(createELFAsmParser());
523 PlatformParser->Initialize(*this);
524 initializeDirectiveKindMap();
526 NumOfMacroInstantiations = 0;
529 AsmParser::~AsmParser() {
530 assert((HadError || ActiveMacros.empty()) &&
531 "Unexpected active macro instantiation!");
534 void AsmParser::printMacroInstantiations() {
535 // Print the active macro instantiation stack.
536 for (std::vector<MacroInstantiation *>::const_reverse_iterator
537 it = ActiveMacros.rbegin(),
538 ie = ActiveMacros.rend();
540 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
541 "while in macro instantiation");
544 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
545 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
546 printMacroInstantiations();
549 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
550 if (getTargetParser().getTargetOptions().MCFatalWarnings)
551 return Error(L, Msg, Ranges);
552 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
553 printMacroInstantiations();
557 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
559 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
560 printMacroInstantiations();
564 bool AsmParser::enterIncludeFile(const std::string &Filename) {
565 std::string IncludedFile;
567 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
572 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
576 /// Process the specified .incbin file by searching for it in the include paths
577 /// then just emitting the byte contents of the file to the streamer. This
578 /// returns true on failure.
579 bool AsmParser::processIncbinFile(const std::string &Filename) {
580 std::string IncludedFile;
582 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
586 // Pick up the bytes from the file and emit them.
587 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
591 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
592 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
593 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
597 const AsmToken &AsmParser::Lex() {
598 const AsmToken *tok = &Lexer.Lex();
600 if (tok->is(AsmToken::Eof)) {
601 // If this is the end of an included file, pop the parent file off the
603 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
604 if (ParentIncludeLoc != SMLoc()) {
605 jumpToLoc(ParentIncludeLoc);
610 if (tok->is(AsmToken::Error))
611 Error(Lexer.getErrLoc(), Lexer.getErr());
616 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
617 // Create the initial section, if requested.
618 if (!NoInitialTextSection)
619 Out.InitSections(false);
625 AsmCond StartingCondState = TheCondState;
627 // If we are generating dwarf for assembly source files save the initial text
628 // section and generate a .file directive.
629 if (getContext().getGenDwarfForAssembly()) {
630 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
631 getStreamer().EmitLabel(SectionStartSym);
632 auto InsertResult = getContext().addGenDwarfSection(
633 getStreamer().getCurrentSection().first);
634 assert(InsertResult.second && ".text section should not have debug info yet");
635 InsertResult.first->second.first = SectionStartSym;
636 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
637 0, StringRef(), getContext().getMainFileName()));
640 // While we have input, parse each statement.
641 while (Lexer.isNot(AsmToken::Eof)) {
642 ParseStatementInfo Info;
643 if (!parseStatement(Info, nullptr))
646 // We had an error, validate that one was emitted and recover by skipping to
648 assert(HadError && "Parse statement returned an error, but none emitted!");
649 eatToEndOfStatement();
652 if (TheCondState.TheCond != StartingCondState.TheCond ||
653 TheCondState.Ignore != StartingCondState.Ignore)
654 return TokError("unmatched .ifs or .elses");
656 // Check to see there are no empty DwarfFile slots.
657 const auto &LineTables = getContext().getMCDwarfLineTables();
658 if (!LineTables.empty()) {
660 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
661 if (File.Name.empty() && Index != 0)
662 TokError("unassigned file number: " + Twine(Index) +
663 " for .file directives");
668 // Check to see that all assembler local symbols were actually defined.
669 // Targets that don't do subsections via symbols may not want this, though,
670 // so conservatively exclude them. Only do this if we're finalizing, though,
671 // as otherwise we won't necessarilly have seen everything yet.
672 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
673 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
674 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
677 MCSymbol *Sym = i->getValue();
678 // Variable symbols may not be marked as defined, so check those
679 // explicitly. If we know it's a variable, we have a definition for
680 // the purposes of this check.
681 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
682 // FIXME: We would really like to refer back to where the symbol was
683 // first referenced for a source location. We need to add something
684 // to track that. Currently, we just point to the end of the file.
686 getLexer().getLoc(), SourceMgr::DK_Error,
687 "assembler local symbol '" + Sym->getName() + "' not defined");
691 // Finalize the output stream if there are no errors and if the client wants
693 if (!HadError && !NoFinalize)
699 void AsmParser::checkForValidSection() {
700 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
701 TokError("expected section directive before assembly directive");
702 Out.InitSections(false);
706 /// \brief Throw away the rest of the line for testing purposes.
707 void AsmParser::eatToEndOfStatement() {
708 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
712 if (Lexer.is(AsmToken::EndOfStatement))
716 StringRef AsmParser::parseStringToEndOfStatement() {
717 const char *Start = getTok().getLoc().getPointer();
719 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
722 const char *End = getTok().getLoc().getPointer();
723 return StringRef(Start, End - Start);
726 StringRef AsmParser::parseStringToComma() {
727 const char *Start = getTok().getLoc().getPointer();
729 while (Lexer.isNot(AsmToken::EndOfStatement) &&
730 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
733 const char *End = getTok().getLoc().getPointer();
734 return StringRef(Start, End - Start);
737 /// \brief Parse a paren expression and return it.
738 /// NOTE: This assumes the leading '(' has already been consumed.
740 /// parenexpr ::= expr)
742 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
743 if (parseExpression(Res))
745 if (Lexer.isNot(AsmToken::RParen))
746 return TokError("expected ')' in parentheses expression");
747 EndLoc = Lexer.getTok().getEndLoc();
752 /// \brief Parse a bracket expression and return it.
753 /// NOTE: This assumes the leading '[' has already been consumed.
755 /// bracketexpr ::= expr]
757 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
758 if (parseExpression(Res))
760 if (Lexer.isNot(AsmToken::RBrac))
761 return TokError("expected ']' in brackets expression");
762 EndLoc = Lexer.getTok().getEndLoc();
767 /// \brief Parse a primary expression and return it.
768 /// primaryexpr ::= (parenexpr
769 /// primaryexpr ::= symbol
770 /// primaryexpr ::= number
771 /// primaryexpr ::= '.'
772 /// primaryexpr ::= ~,+,- primaryexpr
773 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
774 SMLoc FirstTokenLoc = getLexer().getLoc();
775 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
776 switch (FirstTokenKind) {
778 return TokError("unknown token in expression");
779 // If we have an error assume that we've already handled it.
780 case AsmToken::Error:
782 case AsmToken::Exclaim:
783 Lex(); // Eat the operator.
784 if (parsePrimaryExpr(Res, EndLoc))
786 Res = MCUnaryExpr::CreateLNot(Res, getContext());
788 case AsmToken::Dollar:
790 case AsmToken::String:
791 case AsmToken::Identifier: {
792 StringRef Identifier;
793 if (parseIdentifier(Identifier)) {
794 if (FirstTokenKind == AsmToken::Dollar) {
795 if (Lexer.getMAI().getDollarIsPC()) {
796 // This is a '$' reference, which references the current PC. Emit a
797 // temporary label to the streamer and refer to it.
798 MCSymbol *Sym = Ctx.CreateTempSymbol();
800 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
802 EndLoc = FirstTokenLoc;
805 return Error(FirstTokenLoc, "invalid token in expression");
808 // Parse symbol variant
809 std::pair<StringRef, StringRef> Split;
810 if (!MAI.useParensForSymbolVariant()) {
811 if (FirstTokenKind == AsmToken::String) {
812 if (Lexer.is(AsmToken::At)) {
813 Lexer.Lex(); // eat @
814 SMLoc AtLoc = getLexer().getLoc();
816 if (parseIdentifier(VName))
817 return Error(AtLoc, "expected symbol variant after '@'");
819 Split = std::make_pair(Identifier, VName);
822 Split = Identifier.split('@');
824 } else if (Lexer.is(AsmToken::LParen)) {
825 Lexer.Lex(); // eat (
827 parseIdentifier(VName);
828 if (Lexer.isNot(AsmToken::RParen)) {
829 return Error(Lexer.getTok().getLoc(),
830 "unexpected token in variant, expected ')'");
832 Lexer.Lex(); // eat )
833 Split = std::make_pair(Identifier, VName);
836 EndLoc = SMLoc::getFromPointer(Identifier.end());
838 // This is a symbol reference.
839 StringRef SymbolName = Identifier;
840 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
842 // Lookup the symbol variant if used.
843 if (Split.second.size()) {
844 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
845 if (Variant != MCSymbolRefExpr::VK_Invalid) {
846 SymbolName = Split.first;
847 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
848 Variant = MCSymbolRefExpr::VK_None;
850 return Error(SMLoc::getFromPointer(Split.second.begin()),
851 "invalid variant '" + Split.second + "'");
855 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
857 // If this is an absolute variable reference, substitute it now to preserve
858 // semantics in the face of reassignment.
859 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
861 return Error(EndLoc, "unexpected modifier on variable reference");
863 Res = Sym->getVariableValue();
867 // Otherwise create a symbol ref.
868 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
871 case AsmToken::BigNum:
872 return TokError("literal value out of range for directive");
873 case AsmToken::Integer: {
874 SMLoc Loc = getTok().getLoc();
875 int64_t IntVal = getTok().getIntVal();
876 Res = MCConstantExpr::Create(IntVal, getContext());
877 EndLoc = Lexer.getTok().getEndLoc();
879 // Look for 'b' or 'f' following an Integer as a directional label
880 if (Lexer.getKind() == AsmToken::Identifier) {
881 StringRef IDVal = getTok().getString();
882 // Lookup the symbol variant if used.
883 std::pair<StringRef, StringRef> Split = IDVal.split('@');
884 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
885 if (Split.first.size() != IDVal.size()) {
886 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
887 if (Variant == MCSymbolRefExpr::VK_Invalid)
888 return TokError("invalid variant '" + Split.second + "'");
891 if (IDVal == "f" || IDVal == "b") {
893 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "b");
894 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
895 if (IDVal == "b" && Sym->isUndefined())
896 return Error(Loc, "invalid reference to undefined symbol");
897 EndLoc = Lexer.getTok().getEndLoc();
898 Lex(); // Eat identifier.
903 case AsmToken::Real: {
904 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
905 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
906 Res = MCConstantExpr::Create(IntVal, getContext());
907 EndLoc = Lexer.getTok().getEndLoc();
911 case AsmToken::Dot: {
912 // This is a '.' reference, which references the current PC. Emit a
913 // temporary label to the streamer and refer to it.
914 MCSymbol *Sym = Ctx.CreateTempSymbol();
916 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
917 EndLoc = Lexer.getTok().getEndLoc();
918 Lex(); // Eat identifier.
921 case AsmToken::LParen:
922 Lex(); // Eat the '('.
923 return parseParenExpr(Res, EndLoc);
924 case AsmToken::LBrac:
925 if (!PlatformParser->HasBracketExpressions())
926 return TokError("brackets expression not supported on this target");
927 Lex(); // Eat the '['.
928 return parseBracketExpr(Res, EndLoc);
929 case AsmToken::Minus:
930 Lex(); // Eat the operator.
931 if (parsePrimaryExpr(Res, EndLoc))
933 Res = MCUnaryExpr::CreateMinus(Res, getContext());
936 Lex(); // Eat the operator.
937 if (parsePrimaryExpr(Res, EndLoc))
939 Res = MCUnaryExpr::CreatePlus(Res, getContext());
941 case AsmToken::Tilde:
942 Lex(); // Eat the operator.
943 if (parsePrimaryExpr(Res, EndLoc))
945 Res = MCUnaryExpr::CreateNot(Res, getContext());
950 bool AsmParser::parseExpression(const MCExpr *&Res) {
952 return parseExpression(Res, EndLoc);
956 AsmParser::applyModifierToExpr(const MCExpr *E,
957 MCSymbolRefExpr::VariantKind Variant) {
958 // Ask the target implementation about this expression first.
959 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
962 // Recurse over the given expression, rebuilding it to apply the given variant
963 // if there is exactly one symbol.
964 switch (E->getKind()) {
966 case MCExpr::Constant:
969 case MCExpr::SymbolRef: {
970 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
972 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
973 TokError("invalid variant on expression '" + getTok().getIdentifier() +
974 "' (already modified)");
978 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
981 case MCExpr::Unary: {
982 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
983 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
986 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
989 case MCExpr::Binary: {
990 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
991 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
992 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1002 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
1006 llvm_unreachable("Invalid expression kind!");
1009 /// \brief Parse an expression and return it.
1011 /// expr ::= expr &&,|| expr -> lowest.
1012 /// expr ::= expr |,^,&,! expr
1013 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1014 /// expr ::= expr <<,>> expr
1015 /// expr ::= expr +,- expr
1016 /// expr ::= expr *,/,% expr -> highest.
1017 /// expr ::= primaryexpr
1019 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1020 // Parse the expression.
1022 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1025 // As a special case, we support 'a op b @ modifier' by rewriting the
1026 // expression to include the modifier. This is inefficient, but in general we
1027 // expect users to use 'a@modifier op b'.
1028 if (Lexer.getKind() == AsmToken::At) {
1031 if (Lexer.isNot(AsmToken::Identifier))
1032 return TokError("unexpected symbol modifier following '@'");
1034 MCSymbolRefExpr::VariantKind Variant =
1035 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1036 if (Variant == MCSymbolRefExpr::VK_Invalid)
1037 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1039 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1041 return TokError("invalid modifier '" + getTok().getIdentifier() +
1042 "' (no symbols present)");
1049 // Try to constant fold it up front, if possible.
1051 if (Res->EvaluateAsAbsolute(Value))
1052 Res = MCConstantExpr::Create(Value, getContext());
1057 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1059 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1062 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1065 SMLoc StartLoc = Lexer.getLoc();
1066 if (parseExpression(Expr))
1069 if (!Expr->EvaluateAsAbsolute(Res))
1070 return Error(StartLoc, "expected absolute expression");
1075 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1076 MCBinaryExpr::Opcode &Kind) {
1079 return 0; // not a binop.
1081 // Lowest Precedence: &&, ||
1082 case AsmToken::AmpAmp:
1083 Kind = MCBinaryExpr::LAnd;
1085 case AsmToken::PipePipe:
1086 Kind = MCBinaryExpr::LOr;
1089 // Low Precedence: |, &, ^
1091 // FIXME: gas seems to support '!' as an infix operator?
1092 case AsmToken::Pipe:
1093 Kind = MCBinaryExpr::Or;
1095 case AsmToken::Caret:
1096 Kind = MCBinaryExpr::Xor;
1099 Kind = MCBinaryExpr::And;
1102 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1103 case AsmToken::EqualEqual:
1104 Kind = MCBinaryExpr::EQ;
1106 case AsmToken::ExclaimEqual:
1107 case AsmToken::LessGreater:
1108 Kind = MCBinaryExpr::NE;
1110 case AsmToken::Less:
1111 Kind = MCBinaryExpr::LT;
1113 case AsmToken::LessEqual:
1114 Kind = MCBinaryExpr::LTE;
1116 case AsmToken::Greater:
1117 Kind = MCBinaryExpr::GT;
1119 case AsmToken::GreaterEqual:
1120 Kind = MCBinaryExpr::GTE;
1123 // Intermediate Precedence: <<, >>
1124 case AsmToken::LessLess:
1125 Kind = MCBinaryExpr::Shl;
1127 case AsmToken::GreaterGreater:
1128 Kind = MCBinaryExpr::Shr;
1131 // High Intermediate Precedence: +, -
1132 case AsmToken::Plus:
1133 Kind = MCBinaryExpr::Add;
1135 case AsmToken::Minus:
1136 Kind = MCBinaryExpr::Sub;
1139 // Highest Precedence: *, /, %
1140 case AsmToken::Star:
1141 Kind = MCBinaryExpr::Mul;
1143 case AsmToken::Slash:
1144 Kind = MCBinaryExpr::Div;
1146 case AsmToken::Percent:
1147 Kind = MCBinaryExpr::Mod;
1152 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1153 /// Res contains the LHS of the expression on input.
1154 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1157 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1158 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1160 // If the next token is lower precedence than we are allowed to eat, return
1161 // successfully with what we ate already.
1162 if (TokPrec < Precedence)
1167 // Eat the next primary expression.
1169 if (parsePrimaryExpr(RHS, EndLoc))
1172 // If BinOp binds less tightly with RHS than the operator after RHS, let
1173 // the pending operator take RHS as its LHS.
1174 MCBinaryExpr::Opcode Dummy;
1175 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1176 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1179 // Merge LHS and RHS according to operator.
1180 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1185 /// ::= EndOfStatement
1186 /// ::= Label* Directive ...Operands... EndOfStatement
1187 /// ::= Label* Identifier OperandList* EndOfStatement
1188 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1189 MCAsmParserSemaCallback *SI) {
1190 if (Lexer.is(AsmToken::EndOfStatement)) {
1196 // Statements always start with an identifier or are a full line comment.
1197 AsmToken ID = getTok();
1198 SMLoc IDLoc = ID.getLoc();
1200 int64_t LocalLabelVal = -1;
1201 // A full line comment is a '#' as the first token.
1202 if (Lexer.is(AsmToken::Hash))
1203 return parseCppHashLineFilenameComment(IDLoc);
1205 // Allow an integer followed by a ':' as a directional local label.
1206 if (Lexer.is(AsmToken::Integer)) {
1207 LocalLabelVal = getTok().getIntVal();
1208 if (LocalLabelVal < 0) {
1209 if (!TheCondState.Ignore)
1210 return TokError("unexpected token at start of statement");
1213 IDVal = getTok().getString();
1214 Lex(); // Consume the integer token to be used as an identifier token.
1215 if (Lexer.getKind() != AsmToken::Colon) {
1216 if (!TheCondState.Ignore)
1217 return TokError("unexpected token at start of statement");
1220 } else if (Lexer.is(AsmToken::Dot)) {
1221 // Treat '.' as a valid identifier in this context.
1224 } else if (parseIdentifier(IDVal)) {
1225 if (!TheCondState.Ignore)
1226 return TokError("unexpected token at start of statement");
1230 // Handle conditional assembly here before checking for skipping. We
1231 // have to do this so that .endif isn't skipped in a ".if 0" block for
1233 StringMap<DirectiveKind>::const_iterator DirKindIt =
1234 DirectiveKindMap.find(IDVal);
1235 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1237 : DirKindIt->getValue();
1248 return parseDirectiveIf(IDLoc, DirKind);
1250 return parseDirectiveIfb(IDLoc, true);
1252 return parseDirectiveIfb(IDLoc, false);
1254 return parseDirectiveIfc(IDLoc, true);
1256 return parseDirectiveIfeqs(IDLoc, true);
1258 return parseDirectiveIfc(IDLoc, false);
1260 return parseDirectiveIfeqs(IDLoc, false);
1262 return parseDirectiveIfdef(IDLoc, true);
1265 return parseDirectiveIfdef(IDLoc, false);
1267 return parseDirectiveElseIf(IDLoc);
1269 return parseDirectiveElse(IDLoc);
1271 return parseDirectiveEndIf(IDLoc);
1274 // Ignore the statement if in the middle of inactive conditional
1276 if (TheCondState.Ignore) {
1277 eatToEndOfStatement();
1281 // FIXME: Recurse on local labels?
1283 // See what kind of statement we have.
1284 switch (Lexer.getKind()) {
1285 case AsmToken::Colon: {
1286 checkForValidSection();
1288 // identifier ':' -> Label.
1291 // Diagnose attempt to use '.' as a label.
1293 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1295 // Diagnose attempt to use a variable as a label.
1297 // FIXME: Diagnostics. Note the location of the definition as a label.
1298 // FIXME: This doesn't diagnose assignment to a symbol which has been
1299 // implicitly marked as external.
1301 if (LocalLabelVal == -1) {
1302 if (ParsingInlineAsm && SI) {
1303 StringRef RewrittenLabel = SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1304 assert(RewrittenLabel.size() && "We should have an internal name here.");
1305 Info.AsmRewrites->push_back(AsmRewrite(AOK_Label, IDLoc,
1306 IDVal.size(), RewrittenLabel));
1307 IDVal = RewrittenLabel;
1309 Sym = getContext().GetOrCreateSymbol(IDVal);
1311 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1313 Sym->redefineIfPossible();
1315 if (!Sym->isUndefined() || Sym->isVariable())
1316 return Error(IDLoc, "invalid symbol redefinition");
1319 if (!ParsingInlineAsm)
1322 // If we are generating dwarf for assembly source files then gather the
1323 // info to make a dwarf label entry for this label if needed.
1324 if (getContext().getGenDwarfForAssembly())
1325 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1328 getTargetParser().onLabelParsed(Sym);
1330 // Consume any end of statement token, if present, to avoid spurious
1331 // AddBlankLine calls().
1332 if (Lexer.is(AsmToken::EndOfStatement)) {
1334 if (Lexer.is(AsmToken::Eof))
1341 case AsmToken::Equal:
1342 // identifier '=' ... -> assignment statement
1345 return parseAssignment(IDVal, true);
1347 default: // Normal instruction or directive.
1351 // If macros are enabled, check to see if this is a macro instantiation.
1352 if (areMacrosEnabled())
1353 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1354 return handleMacroEntry(M, IDLoc);
1357 // Otherwise, we have a normal instruction or directive.
1359 // Directives start with "."
1360 if (IDVal[0] == '.' && IDVal != ".") {
1361 // There are several entities interested in parsing directives:
1363 // 1. The target-specific assembly parser. Some directives are target
1364 // specific or may potentially behave differently on certain targets.
1365 // 2. Asm parser extensions. For example, platform-specific parsers
1366 // (like the ELF parser) register themselves as extensions.
1367 // 3. The generic directive parser implemented by this class. These are
1368 // all the directives that behave in a target and platform independent
1369 // manner, or at least have a default behavior that's shared between
1370 // all targets and platforms.
1372 // First query the target-specific parser. It will return 'true' if it
1373 // isn't interested in this directive.
1374 if (!getTargetParser().ParseDirective(ID))
1377 // Next, check the extension directive map to see if any extension has
1378 // registered itself to parse this directive.
1379 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1380 ExtensionDirectiveMap.lookup(IDVal);
1382 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1384 // Finally, if no one else is interested in this directive, it must be
1385 // generic and familiar to this class.
1391 return parseDirectiveSet(IDVal, true);
1393 return parseDirectiveSet(IDVal, false);
1395 return parseDirectiveAscii(IDVal, false);
1398 return parseDirectiveAscii(IDVal, true);
1400 return parseDirectiveValue(1);
1404 return parseDirectiveValue(2);
1408 return parseDirectiveValue(4);
1411 return parseDirectiveValue(8);
1413 return parseDirectiveOctaValue();
1416 return parseDirectiveRealValue(APFloat::IEEEsingle);
1418 return parseDirectiveRealValue(APFloat::IEEEdouble);
1420 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1421 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1424 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1425 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1428 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1430 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1432 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1434 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1436 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1438 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1440 return parseDirectiveOrg();
1442 return parseDirectiveFill();
1444 return parseDirectiveZero();
1446 eatToEndOfStatement(); // .extern is the default, ignore it.
1450 return parseDirectiveSymbolAttribute(MCSA_Global);
1451 case DK_LAZY_REFERENCE:
1452 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1453 case DK_NO_DEAD_STRIP:
1454 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1455 case DK_SYMBOL_RESOLVER:
1456 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1457 case DK_PRIVATE_EXTERN:
1458 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1460 return parseDirectiveSymbolAttribute(MCSA_Reference);
1461 case DK_WEAK_DEFINITION:
1462 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1463 case DK_WEAK_REFERENCE:
1464 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1465 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1466 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1469 return parseDirectiveComm(/*IsLocal=*/false);
1471 return parseDirectiveComm(/*IsLocal=*/true);
1473 return parseDirectiveAbort();
1475 return parseDirectiveInclude();
1477 return parseDirectiveIncbin();
1480 return TokError(Twine(IDVal) + " not supported yet");
1482 return parseDirectiveRept(IDLoc, IDVal);
1484 return parseDirectiveIrp(IDLoc);
1486 return parseDirectiveIrpc(IDLoc);
1488 return parseDirectiveEndr(IDLoc);
1489 case DK_BUNDLE_ALIGN_MODE:
1490 return parseDirectiveBundleAlignMode();
1491 case DK_BUNDLE_LOCK:
1492 return parseDirectiveBundleLock();
1493 case DK_BUNDLE_UNLOCK:
1494 return parseDirectiveBundleUnlock();
1496 return parseDirectiveLEB128(true);
1498 return parseDirectiveLEB128(false);
1501 return parseDirectiveSpace(IDVal);
1503 return parseDirectiveFile(IDLoc);
1505 return parseDirectiveLine();
1507 return parseDirectiveLoc();
1509 return parseDirectiveStabs();
1510 case DK_CFI_SECTIONS:
1511 return parseDirectiveCFISections();
1512 case DK_CFI_STARTPROC:
1513 return parseDirectiveCFIStartProc();
1514 case DK_CFI_ENDPROC:
1515 return parseDirectiveCFIEndProc();
1516 case DK_CFI_DEF_CFA:
1517 return parseDirectiveCFIDefCfa(IDLoc);
1518 case DK_CFI_DEF_CFA_OFFSET:
1519 return parseDirectiveCFIDefCfaOffset();
1520 case DK_CFI_ADJUST_CFA_OFFSET:
1521 return parseDirectiveCFIAdjustCfaOffset();
1522 case DK_CFI_DEF_CFA_REGISTER:
1523 return parseDirectiveCFIDefCfaRegister(IDLoc);
1525 return parseDirectiveCFIOffset(IDLoc);
1526 case DK_CFI_REL_OFFSET:
1527 return parseDirectiveCFIRelOffset(IDLoc);
1528 case DK_CFI_PERSONALITY:
1529 return parseDirectiveCFIPersonalityOrLsda(true);
1531 return parseDirectiveCFIPersonalityOrLsda(false);
1532 case DK_CFI_REMEMBER_STATE:
1533 return parseDirectiveCFIRememberState();
1534 case DK_CFI_RESTORE_STATE:
1535 return parseDirectiveCFIRestoreState();
1536 case DK_CFI_SAME_VALUE:
1537 return parseDirectiveCFISameValue(IDLoc);
1538 case DK_CFI_RESTORE:
1539 return parseDirectiveCFIRestore(IDLoc);
1541 return parseDirectiveCFIEscape();
1542 case DK_CFI_SIGNAL_FRAME:
1543 return parseDirectiveCFISignalFrame();
1544 case DK_CFI_UNDEFINED:
1545 return parseDirectiveCFIUndefined(IDLoc);
1546 case DK_CFI_REGISTER:
1547 return parseDirectiveCFIRegister(IDLoc);
1548 case DK_CFI_WINDOW_SAVE:
1549 return parseDirectiveCFIWindowSave();
1552 return parseDirectiveMacrosOnOff(IDVal);
1554 return parseDirectiveMacro(IDLoc);
1556 return parseDirectiveExitMacro(IDVal);
1559 return parseDirectiveEndMacro(IDVal);
1561 return parseDirectivePurgeMacro(IDLoc);
1563 return parseDirectiveEnd(IDLoc);
1565 return parseDirectiveError(IDLoc, false);
1567 return parseDirectiveError(IDLoc, true);
1569 return parseDirectiveWarning(IDLoc);
1572 return Error(IDLoc, "unknown directive");
1575 // __asm _emit or __asm __emit
1576 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1577 IDVal == "_EMIT" || IDVal == "__EMIT"))
1578 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1581 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1582 return parseDirectiveMSAlign(IDLoc, Info);
1584 checkForValidSection();
1586 // Canonicalize the opcode to lower case.
1587 std::string OpcodeStr = IDVal.lower();
1588 ParseInstructionInfo IInfo(Info.AsmRewrites);
1589 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1590 Info.ParsedOperands);
1591 Info.ParseError = HadError;
1593 // Dump the parsed representation, if requested.
1594 if (getShowParsedOperands()) {
1595 SmallString<256> Str;
1596 raw_svector_ostream OS(Str);
1597 OS << "parsed instruction: [";
1598 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1601 Info.ParsedOperands[i]->print(OS);
1605 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1608 // If we are generating dwarf for the current section then generate a .loc
1609 // directive for the instruction.
1610 if (!HadError && getContext().getGenDwarfForAssembly() &&
1611 getContext().getGenDwarfSectionSyms().count(
1612 getStreamer().getCurrentSection().first)) {
1614 if (ActiveMacros.empty())
1615 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1617 Line = SrcMgr.FindLineNumber(ActiveMacros.back()->InstantiationLoc,
1618 ActiveMacros.back()->ExitBuffer);
1620 // If we previously parsed a cpp hash file line comment then make sure the
1621 // current Dwarf File is for the CppHashFilename if not then emit the
1622 // Dwarf File table for it and adjust the line number for the .loc.
1623 if (CppHashFilename.size()) {
1624 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1625 0, StringRef(), CppHashFilename);
1626 getContext().setGenDwarfFileNumber(FileNumber);
1628 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1629 // cache with the different Loc from the call above we save the last
1630 // info we queried here with SrcMgr.FindLineNumber().
1631 unsigned CppHashLocLineNo;
1632 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1633 CppHashLocLineNo = LastQueryLine;
1635 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1636 LastQueryLine = CppHashLocLineNo;
1637 LastQueryIDLoc = CppHashLoc;
1638 LastQueryBuffer = CppHashBuf;
1640 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1643 getStreamer().EmitDwarfLocDirective(
1644 getContext().getGenDwarfFileNumber(), Line, 0,
1645 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1649 // If parsing succeeded, match the instruction.
1652 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1653 Info.ParsedOperands, Out,
1654 ErrorInfo, ParsingInlineAsm);
1657 // Don't skip the rest of the line, the instruction parser is responsible for
1662 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1663 /// since they may not be able to be tokenized to get to the end of line token.
1664 void AsmParser::eatToEndOfLine() {
1665 if (!Lexer.is(AsmToken::EndOfStatement))
1666 Lexer.LexUntilEndOfLine();
1671 /// parseCppHashLineFilenameComment as this:
1672 /// ::= # number "filename"
1673 /// or just as a full line comment if it doesn't have a number and a string.
1674 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1675 Lex(); // Eat the hash token.
1677 if (getLexer().isNot(AsmToken::Integer)) {
1678 // Consume the line since in cases it is not a well-formed line directive,
1679 // as if were simply a full line comment.
1684 int64_t LineNumber = getTok().getIntVal();
1687 if (getLexer().isNot(AsmToken::String)) {
1692 StringRef Filename = getTok().getString();
1693 // Get rid of the enclosing quotes.
1694 Filename = Filename.substr(1, Filename.size() - 2);
1696 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1698 CppHashFilename = Filename;
1699 CppHashLineNumber = LineNumber;
1700 CppHashBuf = CurBuffer;
1702 // Ignore any trailing characters, they're just comment.
1707 /// \brief will use the last parsed cpp hash line filename comment
1708 /// for the Filename and LineNo if any in the diagnostic.
1709 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1710 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1711 raw_ostream &OS = errs();
1713 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1714 const SMLoc &DiagLoc = Diag.getLoc();
1715 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1716 unsigned CppHashBuf =
1717 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1719 // Like SourceMgr::printMessage() we need to print the include stack if any
1720 // before printing the message.
1721 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1722 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1723 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
1724 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1725 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1728 // If we have not parsed a cpp hash line filename comment or the source
1729 // manager changed or buffer changed (like in a nested include) then just
1730 // print the normal diagnostic using its Filename and LineNo.
1731 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1732 DiagBuf != CppHashBuf) {
1733 if (Parser->SavedDiagHandler)
1734 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1736 Diag.print(nullptr, OS);
1740 // Use the CppHashFilename and calculate a line number based on the
1741 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1743 const std::string &Filename = Parser->CppHashFilename;
1745 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1746 int CppHashLocLineNo =
1747 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1749 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1751 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1752 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1753 Diag.getLineContents(), Diag.getRanges());
1755 if (Parser->SavedDiagHandler)
1756 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1758 NewDiag.print(nullptr, OS);
1761 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1762 // difference being that that function accepts '@' as part of identifiers and
1763 // we can't do that. AsmLexer.cpp should probably be changed to handle
1764 // '@' as a special case when needed.
1765 static bool isIdentifierChar(char c) {
1766 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1770 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1771 ArrayRef<MCAsmMacroParameter> Parameters,
1772 ArrayRef<MCAsmMacroArgument> A,
1773 bool EnableAtPseudoVariable, const SMLoc &L) {
1774 unsigned NParameters = Parameters.size();
1775 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1776 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1777 return Error(L, "Wrong number of arguments");
1779 // A macro without parameters is handled differently on Darwin:
1780 // gas accepts no arguments and does no substitutions
1781 while (!Body.empty()) {
1782 // Scan for the next substitution.
1783 std::size_t End = Body.size(), Pos = 0;
1784 for (; Pos != End; ++Pos) {
1785 // Check for a substitution or escape.
1786 if (IsDarwin && !NParameters) {
1787 // This macro has no parameters, look for $0, $1, etc.
1788 if (Body[Pos] != '$' || Pos + 1 == End)
1791 char Next = Body[Pos + 1];
1792 if (Next == '$' || Next == 'n' ||
1793 isdigit(static_cast<unsigned char>(Next)))
1796 // This macro has parameters, look for \foo, \bar, etc.
1797 if (Body[Pos] == '\\' && Pos + 1 != End)
1803 OS << Body.slice(0, Pos);
1805 // Check if we reached the end.
1809 if (IsDarwin && !NParameters) {
1810 switch (Body[Pos + 1]) {
1816 // $n => number of arguments
1821 // $[0-9] => argument
1823 // Missing arguments are ignored.
1824 unsigned Index = Body[Pos + 1] - '0';
1825 if (Index >= A.size())
1828 // Otherwise substitute with the token values, with spaces eliminated.
1829 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1830 ie = A[Index].end();
1832 OS << it->getString();
1838 unsigned I = Pos + 1;
1840 // Check for the \@ pseudo-variable.
1841 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
1844 while (isIdentifierChar(Body[I]) && I + 1 != End)
1847 const char *Begin = Body.data() + Pos + 1;
1848 StringRef Argument(Begin, I - (Pos + 1));
1851 if (Argument == "@") {
1852 OS << NumOfMacroInstantiations;
1855 for (; Index < NParameters; ++Index)
1856 if (Parameters[Index].Name == Argument)
1859 if (Index == NParameters) {
1860 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1863 OS << '\\' << Argument;
1867 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1868 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1869 ie = A[Index].end();
1871 // We expect no quotes around the string's contents when
1872 // parsing for varargs.
1873 if (it->getKind() != AsmToken::String || VarargParameter)
1874 OS << it->getString();
1876 OS << it->getStringContents();
1878 Pos += 1 + Argument.size();
1882 // Update the scan point.
1883 Body = Body.substr(Pos);
1889 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
1890 size_t CondStackDepth)
1891 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
1892 CondStackDepth(CondStackDepth) {}
1894 static bool isOperator(AsmToken::TokenKind kind) {
1898 case AsmToken::Plus:
1899 case AsmToken::Minus:
1900 case AsmToken::Tilde:
1901 case AsmToken::Slash:
1902 case AsmToken::Star:
1904 case AsmToken::Equal:
1905 case AsmToken::EqualEqual:
1906 case AsmToken::Pipe:
1907 case AsmToken::PipePipe:
1908 case AsmToken::Caret:
1910 case AsmToken::AmpAmp:
1911 case AsmToken::Exclaim:
1912 case AsmToken::ExclaimEqual:
1913 case AsmToken::Percent:
1914 case AsmToken::Less:
1915 case AsmToken::LessEqual:
1916 case AsmToken::LessLess:
1917 case AsmToken::LessGreater:
1918 case AsmToken::Greater:
1919 case AsmToken::GreaterEqual:
1920 case AsmToken::GreaterGreater:
1926 class AsmLexerSkipSpaceRAII {
1928 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1929 Lexer.setSkipSpace(SkipSpace);
1932 ~AsmLexerSkipSpaceRAII() {
1933 Lexer.setSkipSpace(true);
1941 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1944 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1945 StringRef Str = parseStringToEndOfStatement();
1946 MA.push_back(AsmToken(AsmToken::String, Str));
1951 unsigned ParenLevel = 0;
1952 unsigned AddTokens = 0;
1954 // Darwin doesn't use spaces to delmit arguments.
1955 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1958 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1959 return TokError("unexpected token in macro instantiation");
1961 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1964 if (Lexer.is(AsmToken::Space)) {
1965 Lex(); // Eat spaces
1967 // Spaces can delimit parameters, but could also be part an expression.
1968 // If the token after a space is an operator, add the token and the next
1969 // one into this argument
1971 if (isOperator(Lexer.getKind())) {
1972 // Check to see whether the token is used as an operator,
1973 // or part of an identifier
1974 const char *NextChar = getTok().getEndLoc().getPointer();
1975 if (*NextChar == ' ')
1979 if (!AddTokens && ParenLevel == 0) {
1985 // handleMacroEntry relies on not advancing the lexer here
1986 // to be able to fill in the remaining default parameter values
1987 if (Lexer.is(AsmToken::EndOfStatement))
1990 // Adjust the current parentheses level.
1991 if (Lexer.is(AsmToken::LParen))
1993 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1996 // Append the token to the current argument list.
1997 MA.push_back(getTok());
2003 if (ParenLevel != 0)
2004 return TokError("unbalanced parentheses in macro argument");
2008 // Parse the macro instantiation arguments.
2009 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2010 MCAsmMacroArguments &A) {
2011 const unsigned NParameters = M ? M->Parameters.size() : 0;
2012 bool NamedParametersFound = false;
2013 SmallVector<SMLoc, 4> FALocs;
2015 A.resize(NParameters);
2016 FALocs.resize(NParameters);
2018 // Parse two kinds of macro invocations:
2019 // - macros defined without any parameters accept an arbitrary number of them
2020 // - macros defined with parameters accept at most that many of them
2021 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2022 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2024 SMLoc IDLoc = Lexer.getLoc();
2025 MCAsmMacroParameter FA;
2027 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2028 if (parseIdentifier(FA.Name)) {
2029 Error(IDLoc, "invalid argument identifier for formal argument");
2030 eatToEndOfStatement();
2034 if (!Lexer.is(AsmToken::Equal)) {
2035 TokError("expected '=' after formal parameter identifier");
2036 eatToEndOfStatement();
2041 NamedParametersFound = true;
2044 if (NamedParametersFound && FA.Name.empty()) {
2045 Error(IDLoc, "cannot mix positional and keyword arguments");
2046 eatToEndOfStatement();
2050 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2051 if (parseMacroArgument(FA.Value, Vararg))
2054 unsigned PI = Parameter;
2055 if (!FA.Name.empty()) {
2057 for (FAI = 0; FAI < NParameters; ++FAI)
2058 if (M->Parameters[FAI].Name == FA.Name)
2061 if (FAI >= NParameters) {
2062 assert(M && "expected macro to be defined");
2064 "parameter named '" + FA.Name + "' does not exist for macro '" +
2071 if (!FA.Value.empty()) {
2076 if (FALocs.size() <= PI)
2077 FALocs.resize(PI + 1);
2079 FALocs[PI] = Lexer.getLoc();
2082 // At the end of the statement, fill in remaining arguments that have
2083 // default values. If there aren't any, then the next argument is
2084 // required but missing
2085 if (Lexer.is(AsmToken::EndOfStatement)) {
2086 bool Failure = false;
2087 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2088 if (A[FAI].empty()) {
2089 if (M->Parameters[FAI].Required) {
2090 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2091 "missing value for required parameter "
2092 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2096 if (!M->Parameters[FAI].Value.empty())
2097 A[FAI] = M->Parameters[FAI].Value;
2103 if (Lexer.is(AsmToken::Comma))
2107 return TokError("too many positional arguments");
2110 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2111 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2112 return (I == MacroMap.end()) ? nullptr : &I->getValue();
2115 void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2116 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2119 void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2121 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2122 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2123 // this, although we should protect against infinite loops.
2124 if (ActiveMacros.size() == 20)
2125 return TokError("macros cannot be nested more than 20 levels deep");
2127 MCAsmMacroArguments A;
2128 if (parseMacroArguments(M, A))
2131 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2132 // to hold the macro body with substitutions.
2133 SmallString<256> Buf;
2134 StringRef Body = M->Body;
2135 raw_svector_ostream OS(Buf);
2137 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2140 // We include the .endmacro in the buffer as our cue to exit the macro
2142 OS << ".endmacro\n";
2144 std::unique_ptr<MemoryBuffer> Instantiation =
2145 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2147 // Create the macro instantiation object and add to the current macro
2148 // instantiation stack.
2149 MacroInstantiation *MI = new MacroInstantiation(
2150 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2151 ActiveMacros.push_back(MI);
2153 ++NumOfMacroInstantiations;
2155 // Jump to the macro instantiation and prime the lexer.
2156 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2157 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2163 void AsmParser::handleMacroExit() {
2164 // Jump to the EndOfStatement we should return to, and consume it.
2165 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2168 // Pop the instantiation entry.
2169 delete ActiveMacros.back();
2170 ActiveMacros.pop_back();
2173 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2174 switch (Value->getKind()) {
2175 case MCExpr::Binary: {
2176 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2177 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2179 case MCExpr::Target:
2180 case MCExpr::Constant:
2182 case MCExpr::SymbolRef: {
2184 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2186 return isUsedIn(Sym, S.getVariableValue());
2190 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2193 llvm_unreachable("Unknown expr kind!");
2196 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2198 // FIXME: Use better location, we should use proper tokens.
2199 SMLoc EqualLoc = Lexer.getLoc();
2201 const MCExpr *Value;
2202 if (parseExpression(Value))
2205 // Note: we don't count b as used in "a = b". This is to allow
2209 if (Lexer.isNot(AsmToken::EndOfStatement))
2210 return TokError("unexpected token in assignment");
2212 // Eat the end of statement marker.
2215 // Validate that the LHS is allowed to be a variable (either it has not been
2216 // used as a symbol, or it is an absolute symbol).
2217 MCSymbol *Sym = getContext().LookupSymbol(Name);
2219 // Diagnose assignment to a label.
2221 // FIXME: Diagnostics. Note the location of the definition as a label.
2222 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2223 if (isUsedIn(Sym, Value))
2224 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2225 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2226 ; // Allow redefinitions of undefined symbols only used in directives.
2227 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2228 ; // Allow redefinitions of variables that haven't yet been used.
2229 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2230 return Error(EqualLoc, "redefinition of '" + Name + "'");
2231 else if (!Sym->isVariable())
2232 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2233 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2234 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2237 // Don't count these checks as uses.
2238 Sym->setUsed(false);
2239 } else if (Name == ".") {
2240 if (Out.EmitValueToOffset(Value, 0)) {
2241 Error(EqualLoc, "expected absolute expression");
2242 eatToEndOfStatement();
2246 Sym = getContext().GetOrCreateSymbol(Name);
2248 Sym->setRedefinable(allow_redef);
2250 // Do the assignment.
2251 Out.EmitAssignment(Sym, Value);
2253 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2258 /// parseIdentifier:
2261 bool AsmParser::parseIdentifier(StringRef &Res) {
2262 // The assembler has relaxed rules for accepting identifiers, in particular we
2263 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2264 // separate tokens. At this level, we have already lexed so we cannot (currently)
2265 // handle this as a context dependent token, instead we detect adjacent tokens
2266 // and return the combined identifier.
2267 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2268 SMLoc PrefixLoc = getLexer().getLoc();
2270 // Consume the prefix character, and check for a following identifier.
2272 if (Lexer.isNot(AsmToken::Identifier))
2275 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2276 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2279 // Construct the joined identifier and consume the token.
2281 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2286 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2289 Res = getTok().getIdentifier();
2291 Lex(); // Consume the identifier token.
2296 /// parseDirectiveSet:
2297 /// ::= .equ identifier ',' expression
2298 /// ::= .equiv identifier ',' expression
2299 /// ::= .set identifier ',' expression
2300 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2303 if (parseIdentifier(Name))
2304 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2306 if (getLexer().isNot(AsmToken::Comma))
2307 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2310 return parseAssignment(Name, allow_redef, true);
2313 bool AsmParser::parseEscapedString(std::string &Data) {
2314 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2317 StringRef Str = getTok().getStringContents();
2318 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2319 if (Str[i] != '\\') {
2324 // Recognize escaped characters. Note that this escape semantics currently
2325 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2328 return TokError("unexpected backslash at end of string");
2330 // Recognize octal sequences.
2331 if ((unsigned)(Str[i] - '0') <= 7) {
2332 // Consume up to three octal characters.
2333 unsigned Value = Str[i] - '0';
2335 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2337 Value = Value * 8 + (Str[i] - '0');
2339 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2341 Value = Value * 8 + (Str[i] - '0');
2346 return TokError("invalid octal escape sequence (out of range)");
2348 Data += (unsigned char)Value;
2352 // Otherwise recognize individual escapes.
2355 // Just reject invalid escape sequences for now.
2356 return TokError("invalid escape sequence (unrecognized character)");
2358 case 'b': Data += '\b'; break;
2359 case 'f': Data += '\f'; break;
2360 case 'n': Data += '\n'; break;
2361 case 'r': Data += '\r'; break;
2362 case 't': Data += '\t'; break;
2363 case '"': Data += '"'; break;
2364 case '\\': Data += '\\'; break;
2371 /// parseDirectiveAscii:
2372 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2373 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2374 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2375 checkForValidSection();
2378 if (getLexer().isNot(AsmToken::String))
2379 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2382 if (parseEscapedString(Data))
2385 getStreamer().EmitBytes(Data);
2387 getStreamer().EmitBytes(StringRef("\0", 1));
2391 if (getLexer().is(AsmToken::EndOfStatement))
2394 if (getLexer().isNot(AsmToken::Comma))
2395 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2404 /// parseDirectiveValue
2405 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2406 bool AsmParser::parseDirectiveValue(unsigned Size) {
2407 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2408 checkForValidSection();
2411 const MCExpr *Value;
2412 SMLoc ExprLoc = getLexer().getLoc();
2413 if (parseExpression(Value))
2416 // Special case constant expressions to match code generator.
2417 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2418 assert(Size <= 8 && "Invalid size");
2419 uint64_t IntValue = MCE->getValue();
2420 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2421 return Error(ExprLoc, "literal value out of range for directive");
2422 getStreamer().EmitIntValue(IntValue, Size);
2424 getStreamer().EmitValue(Value, Size, ExprLoc);
2426 if (getLexer().is(AsmToken::EndOfStatement))
2429 // FIXME: Improve diagnostic.
2430 if (getLexer().isNot(AsmToken::Comma))
2431 return TokError("unexpected token in directive");
2440 /// ParseDirectiveOctaValue
2441 /// ::= .octa [ hexconstant (, hexconstant)* ]
2442 bool AsmParser::parseDirectiveOctaValue() {
2443 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2444 checkForValidSection();
2447 if (Lexer.getKind() == AsmToken::Error)
2449 if (Lexer.getKind() != AsmToken::Integer &&
2450 Lexer.getKind() != AsmToken::BigNum)
2451 return TokError("unknown token in expression");
2453 SMLoc ExprLoc = getLexer().getLoc();
2454 APInt IntValue = getTok().getAPIntVal();
2458 if (IntValue.isIntN(64)) {
2460 lo = IntValue.getZExtValue();
2461 } else if (IntValue.isIntN(128)) {
2462 // It might actually have more than 128 bits, but the top ones are zero.
2463 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2464 lo = IntValue.getLoBits(64).getZExtValue();
2466 return Error(ExprLoc, "literal value out of range for directive");
2468 if (MAI.isLittleEndian()) {
2469 getStreamer().EmitIntValue(lo, 8);
2470 getStreamer().EmitIntValue(hi, 8);
2472 getStreamer().EmitIntValue(hi, 8);
2473 getStreamer().EmitIntValue(lo, 8);
2476 if (getLexer().is(AsmToken::EndOfStatement))
2479 // FIXME: Improve diagnostic.
2480 if (getLexer().isNot(AsmToken::Comma))
2481 return TokError("unexpected token in directive");
2490 /// parseDirectiveRealValue
2491 /// ::= (.single | .double) [ expression (, expression)* ]
2492 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2493 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2494 checkForValidSection();
2497 // We don't truly support arithmetic on floating point expressions, so we
2498 // have to manually parse unary prefixes.
2500 if (getLexer().is(AsmToken::Minus)) {
2503 } else if (getLexer().is(AsmToken::Plus))
2506 if (getLexer().isNot(AsmToken::Integer) &&
2507 getLexer().isNot(AsmToken::Real) &&
2508 getLexer().isNot(AsmToken::Identifier))
2509 return TokError("unexpected token in directive");
2511 // Convert to an APFloat.
2512 APFloat Value(Semantics);
2513 StringRef IDVal = getTok().getString();
2514 if (getLexer().is(AsmToken::Identifier)) {
2515 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2516 Value = APFloat::getInf(Semantics);
2517 else if (!IDVal.compare_lower("nan"))
2518 Value = APFloat::getNaN(Semantics, false, ~0);
2520 return TokError("invalid floating point literal");
2521 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2522 APFloat::opInvalidOp)
2523 return TokError("invalid floating point literal");
2527 // Consume the numeric token.
2530 // Emit the value as an integer.
2531 APInt AsInt = Value.bitcastToAPInt();
2532 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2533 AsInt.getBitWidth() / 8);
2535 if (getLexer().is(AsmToken::EndOfStatement))
2538 if (getLexer().isNot(AsmToken::Comma))
2539 return TokError("unexpected token in directive");
2548 /// parseDirectiveZero
2549 /// ::= .zero expression
2550 bool AsmParser::parseDirectiveZero() {
2551 checkForValidSection();
2554 if (parseAbsoluteExpression(NumBytes))
2558 if (getLexer().is(AsmToken::Comma)) {
2560 if (parseAbsoluteExpression(Val))
2564 if (getLexer().isNot(AsmToken::EndOfStatement))
2565 return TokError("unexpected token in '.zero' directive");
2569 getStreamer().EmitFill(NumBytes, Val);
2574 /// parseDirectiveFill
2575 /// ::= .fill expression [ , expression [ , expression ] ]
2576 bool AsmParser::parseDirectiveFill() {
2577 checkForValidSection();
2579 SMLoc RepeatLoc = getLexer().getLoc();
2581 if (parseAbsoluteExpression(NumValues))
2584 if (NumValues < 0) {
2586 "'.fill' directive with negative repeat count has no effect");
2590 int64_t FillSize = 1;
2591 int64_t FillExpr = 0;
2593 SMLoc SizeLoc, ExprLoc;
2594 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2595 if (getLexer().isNot(AsmToken::Comma))
2596 return TokError("unexpected token in '.fill' directive");
2599 SizeLoc = getLexer().getLoc();
2600 if (parseAbsoluteExpression(FillSize))
2603 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2604 if (getLexer().isNot(AsmToken::Comma))
2605 return TokError("unexpected token in '.fill' directive");
2608 ExprLoc = getLexer().getLoc();
2609 if (parseAbsoluteExpression(FillExpr))
2612 if (getLexer().isNot(AsmToken::EndOfStatement))
2613 return TokError("unexpected token in '.fill' directive");
2620 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2624 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2628 if (!isUInt<32>(FillExpr) && FillSize > 4)
2629 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2631 if (NumValues > 0) {
2632 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2633 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2634 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2635 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2636 if (NonZeroFillSize < FillSize)
2637 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2644 /// parseDirectiveOrg
2645 /// ::= .org expression [ , expression ]
2646 bool AsmParser::parseDirectiveOrg() {
2647 checkForValidSection();
2649 const MCExpr *Offset;
2650 SMLoc Loc = getTok().getLoc();
2651 if (parseExpression(Offset))
2654 // Parse optional fill expression.
2655 int64_t FillExpr = 0;
2656 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2657 if (getLexer().isNot(AsmToken::Comma))
2658 return TokError("unexpected token in '.org' directive");
2661 if (parseAbsoluteExpression(FillExpr))
2664 if (getLexer().isNot(AsmToken::EndOfStatement))
2665 return TokError("unexpected token in '.org' directive");
2670 // Only limited forms of relocatable expressions are accepted here, it
2671 // has to be relative to the current section. The streamer will return
2672 // 'true' if the expression wasn't evaluatable.
2673 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2674 return Error(Loc, "expected assembly-time absolute expression");
2679 /// parseDirectiveAlign
2680 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2681 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2682 checkForValidSection();
2684 SMLoc AlignmentLoc = getLexer().getLoc();
2686 if (parseAbsoluteExpression(Alignment))
2690 bool HasFillExpr = false;
2691 int64_t FillExpr = 0;
2692 int64_t MaxBytesToFill = 0;
2693 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2694 if (getLexer().isNot(AsmToken::Comma))
2695 return TokError("unexpected token in directive");
2698 // The fill expression can be omitted while specifying a maximum number of
2699 // alignment bytes, e.g:
2701 if (getLexer().isNot(AsmToken::Comma)) {
2703 if (parseAbsoluteExpression(FillExpr))
2707 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2708 if (getLexer().isNot(AsmToken::Comma))
2709 return TokError("unexpected token in directive");
2712 MaxBytesLoc = getLexer().getLoc();
2713 if (parseAbsoluteExpression(MaxBytesToFill))
2716 if (getLexer().isNot(AsmToken::EndOfStatement))
2717 return TokError("unexpected token in directive");
2726 // Compute alignment in bytes.
2728 // FIXME: Diagnose overflow.
2729 if (Alignment >= 32) {
2730 Error(AlignmentLoc, "invalid alignment value");
2734 Alignment = 1ULL << Alignment;
2736 // Reject alignments that aren't a power of two, for gas compatibility.
2737 if (!isPowerOf2_64(Alignment))
2738 Error(AlignmentLoc, "alignment must be a power of 2");
2741 // Diagnose non-sensical max bytes to align.
2742 if (MaxBytesLoc.isValid()) {
2743 if (MaxBytesToFill < 1) {
2744 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2745 "many bytes, ignoring maximum bytes expression");
2749 if (MaxBytesToFill >= Alignment) {
2750 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2756 // Check whether we should use optimal code alignment for this .align
2758 const MCSection *Section = getStreamer().getCurrentSection().first;
2759 assert(Section && "must have section to emit alignment");
2760 bool UseCodeAlign = Section->UseCodeAlign();
2761 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2762 ValueSize == 1 && UseCodeAlign) {
2763 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2765 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2766 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2773 /// parseDirectiveFile
2774 /// ::= .file [number] filename
2775 /// ::= .file number directory filename
2776 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2777 // FIXME: I'm not sure what this is.
2778 int64_t FileNumber = -1;
2779 SMLoc FileNumberLoc = getLexer().getLoc();
2780 if (getLexer().is(AsmToken::Integer)) {
2781 FileNumber = getTok().getIntVal();
2785 return TokError("file number less than one");
2788 if (getLexer().isNot(AsmToken::String))
2789 return TokError("unexpected token in '.file' directive");
2791 // Usually the directory and filename together, otherwise just the directory.
2792 // Allow the strings to have escaped octal character sequence.
2793 std::string Path = getTok().getString();
2794 if (parseEscapedString(Path))
2798 StringRef Directory;
2800 std::string FilenameData;
2801 if (getLexer().is(AsmToken::String)) {
2802 if (FileNumber == -1)
2803 return TokError("explicit path specified, but no file number");
2804 if (parseEscapedString(FilenameData))
2806 Filename = FilenameData;
2813 if (getLexer().isNot(AsmToken::EndOfStatement))
2814 return TokError("unexpected token in '.file' directive");
2816 if (FileNumber == -1)
2817 getStreamer().EmitFileDirective(Filename);
2819 if (getContext().getGenDwarfForAssembly())
2821 "input can't have .file dwarf directives when -g is "
2822 "used to generate dwarf debug info for assembly code");
2824 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2826 Error(FileNumberLoc, "file number already allocated");
2832 /// parseDirectiveLine
2833 /// ::= .line [number]
2834 bool AsmParser::parseDirectiveLine() {
2835 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2836 if (getLexer().isNot(AsmToken::Integer))
2837 return TokError("unexpected token in '.line' directive");
2839 int64_t LineNumber = getTok().getIntVal();
2843 // FIXME: Do something with the .line.
2846 if (getLexer().isNot(AsmToken::EndOfStatement))
2847 return TokError("unexpected token in '.line' directive");
2852 /// parseDirectiveLoc
2853 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2854 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2855 /// The first number is a file number, must have been previously assigned with
2856 /// a .file directive, the second number is the line number and optionally the
2857 /// third number is a column position (zero if not specified). The remaining
2858 /// optional items are .loc sub-directives.
2859 bool AsmParser::parseDirectiveLoc() {
2860 if (getLexer().isNot(AsmToken::Integer))
2861 return TokError("unexpected token in '.loc' directive");
2862 int64_t FileNumber = getTok().getIntVal();
2864 return TokError("file number less than one in '.loc' directive");
2865 if (!getContext().isValidDwarfFileNumber(FileNumber))
2866 return TokError("unassigned file number in '.loc' directive");
2869 int64_t LineNumber = 0;
2870 if (getLexer().is(AsmToken::Integer)) {
2871 LineNumber = getTok().getIntVal();
2873 return TokError("line number less than zero in '.loc' directive");
2877 int64_t ColumnPos = 0;
2878 if (getLexer().is(AsmToken::Integer)) {
2879 ColumnPos = getTok().getIntVal();
2881 return TokError("column position less than zero in '.loc' directive");
2885 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2887 int64_t Discriminator = 0;
2888 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2890 if (getLexer().is(AsmToken::EndOfStatement))
2894 SMLoc Loc = getTok().getLoc();
2895 if (parseIdentifier(Name))
2896 return TokError("unexpected token in '.loc' directive");
2898 if (Name == "basic_block")
2899 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2900 else if (Name == "prologue_end")
2901 Flags |= DWARF2_FLAG_PROLOGUE_END;
2902 else if (Name == "epilogue_begin")
2903 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2904 else if (Name == "is_stmt") {
2905 Loc = getTok().getLoc();
2906 const MCExpr *Value;
2907 if (parseExpression(Value))
2909 // The expression must be the constant 0 or 1.
2910 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2911 int Value = MCE->getValue();
2913 Flags &= ~DWARF2_FLAG_IS_STMT;
2914 else if (Value == 1)
2915 Flags |= DWARF2_FLAG_IS_STMT;
2917 return Error(Loc, "is_stmt value not 0 or 1");
2919 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2921 } else if (Name == "isa") {
2922 Loc = getTok().getLoc();
2923 const MCExpr *Value;
2924 if (parseExpression(Value))
2926 // The expression must be a constant greater or equal to 0.
2927 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2928 int Value = MCE->getValue();
2930 return Error(Loc, "isa number less than zero");
2933 return Error(Loc, "isa number not a constant value");
2935 } else if (Name == "discriminator") {
2936 if (parseAbsoluteExpression(Discriminator))
2939 return Error(Loc, "unknown sub-directive in '.loc' directive");
2942 if (getLexer().is(AsmToken::EndOfStatement))
2947 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2948 Isa, Discriminator, StringRef());
2953 /// parseDirectiveStabs
2954 /// ::= .stabs string, number, number, number
2955 bool AsmParser::parseDirectiveStabs() {
2956 return TokError("unsupported directive '.stabs'");
2959 /// parseDirectiveCFISections
2960 /// ::= .cfi_sections section [, section]
2961 bool AsmParser::parseDirectiveCFISections() {
2966 if (parseIdentifier(Name))
2967 return TokError("Expected an identifier");
2969 if (Name == ".eh_frame")
2971 else if (Name == ".debug_frame")
2974 if (getLexer().is(AsmToken::Comma)) {
2977 if (parseIdentifier(Name))
2978 return TokError("Expected an identifier");
2980 if (Name == ".eh_frame")
2982 else if (Name == ".debug_frame")
2986 getStreamer().EmitCFISections(EH, Debug);
2990 /// parseDirectiveCFIStartProc
2991 /// ::= .cfi_startproc [simple]
2992 bool AsmParser::parseDirectiveCFIStartProc() {
2994 if (getLexer().isNot(AsmToken::EndOfStatement))
2995 if (parseIdentifier(Simple) || Simple != "simple")
2996 return TokError("unexpected token in .cfi_startproc directive");
2998 getStreamer().EmitCFIStartProc(!Simple.empty());
3002 /// parseDirectiveCFIEndProc
3003 /// ::= .cfi_endproc
3004 bool AsmParser::parseDirectiveCFIEndProc() {
3005 getStreamer().EmitCFIEndProc();
3009 /// \brief parse register name or number.
3010 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
3011 SMLoc DirectiveLoc) {
3014 if (getLexer().isNot(AsmToken::Integer)) {
3015 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3017 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
3019 return parseAbsoluteExpression(Register);
3024 /// parseDirectiveCFIDefCfa
3025 /// ::= .cfi_def_cfa register, offset
3026 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3027 int64_t Register = 0;
3028 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3031 if (getLexer().isNot(AsmToken::Comma))
3032 return TokError("unexpected token in directive");
3036 if (parseAbsoluteExpression(Offset))
3039 getStreamer().EmitCFIDefCfa(Register, Offset);
3043 /// parseDirectiveCFIDefCfaOffset
3044 /// ::= .cfi_def_cfa_offset offset
3045 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3047 if (parseAbsoluteExpression(Offset))
3050 getStreamer().EmitCFIDefCfaOffset(Offset);
3054 /// parseDirectiveCFIRegister
3055 /// ::= .cfi_register register, register
3056 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3057 int64_t Register1 = 0;
3058 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3061 if (getLexer().isNot(AsmToken::Comma))
3062 return TokError("unexpected token in directive");
3065 int64_t Register2 = 0;
3066 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3069 getStreamer().EmitCFIRegister(Register1, Register2);
3073 /// parseDirectiveCFIWindowSave
3074 /// ::= .cfi_window_save
3075 bool AsmParser::parseDirectiveCFIWindowSave() {
3076 getStreamer().EmitCFIWindowSave();
3080 /// parseDirectiveCFIAdjustCfaOffset
3081 /// ::= .cfi_adjust_cfa_offset adjustment
3082 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3083 int64_t Adjustment = 0;
3084 if (parseAbsoluteExpression(Adjustment))
3087 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3091 /// parseDirectiveCFIDefCfaRegister
3092 /// ::= .cfi_def_cfa_register register
3093 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3094 int64_t Register = 0;
3095 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3098 getStreamer().EmitCFIDefCfaRegister(Register);
3102 /// parseDirectiveCFIOffset
3103 /// ::= .cfi_offset register, offset
3104 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3105 int64_t Register = 0;
3108 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3111 if (getLexer().isNot(AsmToken::Comma))
3112 return TokError("unexpected token in directive");
3115 if (parseAbsoluteExpression(Offset))
3118 getStreamer().EmitCFIOffset(Register, Offset);
3122 /// parseDirectiveCFIRelOffset
3123 /// ::= .cfi_rel_offset register, offset
3124 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3125 int64_t Register = 0;
3127 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3130 if (getLexer().isNot(AsmToken::Comma))
3131 return TokError("unexpected token in directive");
3135 if (parseAbsoluteExpression(Offset))
3138 getStreamer().EmitCFIRelOffset(Register, Offset);
3142 static bool isValidEncoding(int64_t Encoding) {
3143 if (Encoding & ~0xff)
3146 if (Encoding == dwarf::DW_EH_PE_omit)
3149 const unsigned Format = Encoding & 0xf;
3150 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3151 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3152 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3153 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3156 const unsigned Application = Encoding & 0x70;
3157 if (Application != dwarf::DW_EH_PE_absptr &&
3158 Application != dwarf::DW_EH_PE_pcrel)
3164 /// parseDirectiveCFIPersonalityOrLsda
3165 /// IsPersonality true for cfi_personality, false for cfi_lsda
3166 /// ::= .cfi_personality encoding, [symbol_name]
3167 /// ::= .cfi_lsda encoding, [symbol_name]
3168 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3169 int64_t Encoding = 0;
3170 if (parseAbsoluteExpression(Encoding))
3172 if (Encoding == dwarf::DW_EH_PE_omit)
3175 if (!isValidEncoding(Encoding))
3176 return TokError("unsupported encoding.");
3178 if (getLexer().isNot(AsmToken::Comma))
3179 return TokError("unexpected token in directive");
3183 if (parseIdentifier(Name))
3184 return TokError("expected identifier in directive");
3186 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3189 getStreamer().EmitCFIPersonality(Sym, Encoding);
3191 getStreamer().EmitCFILsda(Sym, Encoding);
3195 /// parseDirectiveCFIRememberState
3196 /// ::= .cfi_remember_state
3197 bool AsmParser::parseDirectiveCFIRememberState() {
3198 getStreamer().EmitCFIRememberState();
3202 /// parseDirectiveCFIRestoreState
3203 /// ::= .cfi_remember_state
3204 bool AsmParser::parseDirectiveCFIRestoreState() {
3205 getStreamer().EmitCFIRestoreState();
3209 /// parseDirectiveCFISameValue
3210 /// ::= .cfi_same_value register
3211 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3212 int64_t Register = 0;
3214 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3217 getStreamer().EmitCFISameValue(Register);
3221 /// parseDirectiveCFIRestore
3222 /// ::= .cfi_restore register
3223 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3224 int64_t Register = 0;
3225 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3228 getStreamer().EmitCFIRestore(Register);
3232 /// parseDirectiveCFIEscape
3233 /// ::= .cfi_escape expression[,...]
3234 bool AsmParser::parseDirectiveCFIEscape() {
3237 if (parseAbsoluteExpression(CurrValue))
3240 Values.push_back((uint8_t)CurrValue);
3242 while (getLexer().is(AsmToken::Comma)) {
3245 if (parseAbsoluteExpression(CurrValue))
3248 Values.push_back((uint8_t)CurrValue);
3251 getStreamer().EmitCFIEscape(Values);
3255 /// parseDirectiveCFISignalFrame
3256 /// ::= .cfi_signal_frame
3257 bool AsmParser::parseDirectiveCFISignalFrame() {
3258 if (getLexer().isNot(AsmToken::EndOfStatement))
3259 return Error(getLexer().getLoc(),
3260 "unexpected token in '.cfi_signal_frame'");
3262 getStreamer().EmitCFISignalFrame();
3266 /// parseDirectiveCFIUndefined
3267 /// ::= .cfi_undefined register
3268 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3269 int64_t Register = 0;
3271 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3274 getStreamer().EmitCFIUndefined(Register);
3278 /// parseDirectiveMacrosOnOff
3281 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3282 if (getLexer().isNot(AsmToken::EndOfStatement))
3283 return Error(getLexer().getLoc(),
3284 "unexpected token in '" + Directive + "' directive");
3286 setMacrosEnabled(Directive == ".macros_on");
3290 /// parseDirectiveMacro
3291 /// ::= .macro name[,] [parameters]
3292 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3294 if (parseIdentifier(Name))
3295 return TokError("expected identifier in '.macro' directive");
3297 if (getLexer().is(AsmToken::Comma))
3300 MCAsmMacroParameters Parameters;
3301 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3303 if (!Parameters.empty() && Parameters.back().Vararg)
3304 return Error(Lexer.getLoc(),
3305 "Vararg parameter '" + Parameters.back().Name +
3306 "' should be last one in the list of parameters.");
3308 MCAsmMacroParameter Parameter;
3309 if (parseIdentifier(Parameter.Name))
3310 return TokError("expected identifier in '.macro' directive");
3312 if (Lexer.is(AsmToken::Colon)) {
3313 Lex(); // consume ':'
3316 StringRef Qualifier;
3318 QualLoc = Lexer.getLoc();
3319 if (parseIdentifier(Qualifier))
3320 return Error(QualLoc, "missing parameter qualifier for "
3321 "'" + Parameter.Name + "' in macro '" + Name + "'");
3323 if (Qualifier == "req")
3324 Parameter.Required = true;
3325 else if (Qualifier == "vararg")
3326 Parameter.Vararg = true;
3328 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3329 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3332 if (getLexer().is(AsmToken::Equal)) {
3337 ParamLoc = Lexer.getLoc();
3338 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3341 if (Parameter.Required)
3342 Warning(ParamLoc, "pointless default value for required parameter "
3343 "'" + Parameter.Name + "' in macro '" + Name + "'");
3346 Parameters.push_back(std::move(Parameter));
3348 if (getLexer().is(AsmToken::Comma))
3352 // Eat the end of statement.
3355 AsmToken EndToken, StartToken = getTok();
3356 unsigned MacroDepth = 0;
3358 // Lex the macro definition.
3360 // Check whether we have reached the end of the file.
3361 if (getLexer().is(AsmToken::Eof))
3362 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3364 // Otherwise, check whether we have reach the .endmacro.
3365 if (getLexer().is(AsmToken::Identifier)) {
3366 if (getTok().getIdentifier() == ".endm" ||
3367 getTok().getIdentifier() == ".endmacro") {
3368 if (MacroDepth == 0) { // Outermost macro.
3369 EndToken = getTok();
3371 if (getLexer().isNot(AsmToken::EndOfStatement))
3372 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3376 // Otherwise we just found the end of an inner macro.
3379 } else if (getTok().getIdentifier() == ".macro") {
3380 // We allow nested macros. Those aren't instantiated until the outermost
3381 // macro is expanded so just ignore them for now.
3386 // Otherwise, scan til the end of the statement.
3387 eatToEndOfStatement();
3390 if (lookupMacro(Name)) {
3391 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3394 const char *BodyStart = StartToken.getLoc().getPointer();
3395 const char *BodyEnd = EndToken.getLoc().getPointer();
3396 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3397 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3398 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
3402 /// checkForBadMacro
3404 /// With the support added for named parameters there may be code out there that
3405 /// is transitioning from positional parameters. In versions of gas that did
3406 /// not support named parameters they would be ignored on the macro definition.
3407 /// But to support both styles of parameters this is not possible so if a macro
3408 /// definition has named parameters but does not use them and has what appears
3409 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3410 /// warning that the positional parameter found in body which have no effect.
3411 /// Hoping the developer will either remove the named parameters from the macro
3412 /// definition so the positional parameters get used if that was what was
3413 /// intended or change the macro to use the named parameters. It is possible
3414 /// this warning will trigger when the none of the named parameters are used
3415 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3416 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3418 ArrayRef<MCAsmMacroParameter> Parameters) {
3419 // If this macro is not defined with named parameters the warning we are
3420 // checking for here doesn't apply.
3421 unsigned NParameters = Parameters.size();
3422 if (NParameters == 0)
3425 bool NamedParametersFound = false;
3426 bool PositionalParametersFound = false;
3428 // Look at the body of the macro for use of both the named parameters and what
3429 // are likely to be positional parameters. This is what expandMacro() is
3430 // doing when it finds the parameters in the body.
3431 while (!Body.empty()) {
3432 // Scan for the next possible parameter.
3433 std::size_t End = Body.size(), Pos = 0;
3434 for (; Pos != End; ++Pos) {
3435 // Check for a substitution or escape.
3436 // This macro is defined with parameters, look for \foo, \bar, etc.
3437 if (Body[Pos] == '\\' && Pos + 1 != End)
3440 // This macro should have parameters, but look for $0, $1, ..., $n too.
3441 if (Body[Pos] != '$' || Pos + 1 == End)
3443 char Next = Body[Pos + 1];
3444 if (Next == '$' || Next == 'n' ||
3445 isdigit(static_cast<unsigned char>(Next)))
3449 // Check if we reached the end.
3453 if (Body[Pos] == '$') {
3454 switch (Body[Pos + 1]) {
3459 // $n => number of arguments
3461 PositionalParametersFound = true;
3464 // $[0-9] => argument
3466 PositionalParametersFound = true;
3472 unsigned I = Pos + 1;
3473 while (isIdentifierChar(Body[I]) && I + 1 != End)
3476 const char *Begin = Body.data() + Pos + 1;
3477 StringRef Argument(Begin, I - (Pos + 1));
3479 for (; Index < NParameters; ++Index)
3480 if (Parameters[Index].Name == Argument)
3483 if (Index == NParameters) {
3484 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3490 NamedParametersFound = true;
3491 Pos += 1 + Argument.size();
3494 // Update the scan point.
3495 Body = Body.substr(Pos);
3498 if (!NamedParametersFound && PositionalParametersFound)
3499 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3500 "used in macro body, possible positional parameter "
3501 "found in body which will have no effect");
3504 /// parseDirectiveExitMacro
3506 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3507 if (getLexer().isNot(AsmToken::EndOfStatement))
3508 return TokError("unexpected token in '" + Directive + "' directive");
3510 if (!isInsideMacroInstantiation())
3511 return TokError("unexpected '" + Directive + "' in file, "
3512 "no current macro definition");
3514 // Exit all conditionals that are active in the current macro.
3515 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3516 TheCondState = TheCondStack.back();
3517 TheCondStack.pop_back();
3524 /// parseDirectiveEndMacro
3527 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3528 if (getLexer().isNot(AsmToken::EndOfStatement))
3529 return TokError("unexpected token in '" + Directive + "' directive");
3531 // If we are inside a macro instantiation, terminate the current
3533 if (isInsideMacroInstantiation()) {
3538 // Otherwise, this .endmacro is a stray entry in the file; well formed
3539 // .endmacro directives are handled during the macro definition parsing.
3540 return TokError("unexpected '" + Directive + "' in file, "
3541 "no current macro definition");
3544 /// parseDirectivePurgeMacro
3546 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3548 if (parseIdentifier(Name))
3549 return TokError("expected identifier in '.purgem' directive");
3551 if (getLexer().isNot(AsmToken::EndOfStatement))
3552 return TokError("unexpected token in '.purgem' directive");
3554 if (!lookupMacro(Name))
3555 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3557 undefineMacro(Name);
3561 /// parseDirectiveBundleAlignMode
3562 /// ::= {.bundle_align_mode} expression
3563 bool AsmParser::parseDirectiveBundleAlignMode() {
3564 checkForValidSection();
3566 // Expect a single argument: an expression that evaluates to a constant
3567 // in the inclusive range 0-30.
3568 SMLoc ExprLoc = getLexer().getLoc();
3569 int64_t AlignSizePow2;
3570 if (parseAbsoluteExpression(AlignSizePow2))
3572 else if (getLexer().isNot(AsmToken::EndOfStatement))
3573 return TokError("unexpected token after expression in"
3574 " '.bundle_align_mode' directive");
3575 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3576 return Error(ExprLoc,
3577 "invalid bundle alignment size (expected between 0 and 30)");
3581 // Because of AlignSizePow2's verified range we can safely truncate it to
3583 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3587 /// parseDirectiveBundleLock
3588 /// ::= {.bundle_lock} [align_to_end]
3589 bool AsmParser::parseDirectiveBundleLock() {
3590 checkForValidSection();
3591 bool AlignToEnd = false;
3593 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3595 SMLoc Loc = getTok().getLoc();
3596 const char *kInvalidOptionError =
3597 "invalid option for '.bundle_lock' directive";
3599 if (parseIdentifier(Option))
3600 return Error(Loc, kInvalidOptionError);
3602 if (Option != "align_to_end")
3603 return Error(Loc, kInvalidOptionError);
3604 else if (getLexer().isNot(AsmToken::EndOfStatement))
3606 "unexpected token after '.bundle_lock' directive option");
3612 getStreamer().EmitBundleLock(AlignToEnd);
3616 /// parseDirectiveBundleLock
3617 /// ::= {.bundle_lock}
3618 bool AsmParser::parseDirectiveBundleUnlock() {
3619 checkForValidSection();
3621 if (getLexer().isNot(AsmToken::EndOfStatement))
3622 return TokError("unexpected token in '.bundle_unlock' directive");
3625 getStreamer().EmitBundleUnlock();
3629 /// parseDirectiveSpace
3630 /// ::= (.skip | .space) expression [ , expression ]
3631 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3632 checkForValidSection();
3635 if (parseAbsoluteExpression(NumBytes))
3638 int64_t FillExpr = 0;
3639 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3640 if (getLexer().isNot(AsmToken::Comma))
3641 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3644 if (parseAbsoluteExpression(FillExpr))
3647 if (getLexer().isNot(AsmToken::EndOfStatement))
3648 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3654 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3657 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3658 getStreamer().EmitFill(NumBytes, FillExpr);
3663 /// parseDirectiveLEB128
3664 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
3665 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3666 checkForValidSection();
3667 const MCExpr *Value;
3670 if (parseExpression(Value))
3674 getStreamer().EmitSLEB128Value(Value);
3676 getStreamer().EmitULEB128Value(Value);
3678 if (getLexer().is(AsmToken::EndOfStatement))
3681 if (getLexer().isNot(AsmToken::Comma))
3682 return TokError("unexpected token in directive");
3689 /// parseDirectiveSymbolAttribute
3690 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3691 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3692 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3695 SMLoc Loc = getTok().getLoc();
3697 if (parseIdentifier(Name))
3698 return Error(Loc, "expected identifier in directive");
3700 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3702 // Assembler local symbols don't make any sense here. Complain loudly.
3703 if (Sym->isTemporary())
3704 return Error(Loc, "non-local symbol required in directive");
3706 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3707 return Error(Loc, "unable to emit symbol attribute");
3709 if (getLexer().is(AsmToken::EndOfStatement))
3712 if (getLexer().isNot(AsmToken::Comma))
3713 return TokError("unexpected token in directive");
3722 /// parseDirectiveComm
3723 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3724 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3725 checkForValidSection();
3727 SMLoc IDLoc = getLexer().getLoc();
3729 if (parseIdentifier(Name))
3730 return TokError("expected identifier in directive");
3732 // Handle the identifier as the key symbol.
3733 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3735 if (getLexer().isNot(AsmToken::Comma))
3736 return TokError("unexpected token in directive");
3740 SMLoc SizeLoc = getLexer().getLoc();
3741 if (parseAbsoluteExpression(Size))
3744 int64_t Pow2Alignment = 0;
3745 SMLoc Pow2AlignmentLoc;
3746 if (getLexer().is(AsmToken::Comma)) {
3748 Pow2AlignmentLoc = getLexer().getLoc();
3749 if (parseAbsoluteExpression(Pow2Alignment))
3752 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3753 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3754 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3756 // If this target takes alignments in bytes (not log) validate and convert.
3757 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3758 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3759 if (!isPowerOf2_64(Pow2Alignment))
3760 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3761 Pow2Alignment = Log2_64(Pow2Alignment);
3765 if (getLexer().isNot(AsmToken::EndOfStatement))
3766 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3770 // NOTE: a size of zero for a .comm should create a undefined symbol
3771 // but a size of .lcomm creates a bss symbol of size zero.
3773 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3774 "be less than zero");
3776 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3777 // may internally end up wanting an alignment in bytes.
3778 // FIXME: Diagnose overflow.
3779 if (Pow2Alignment < 0)
3780 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3781 "alignment, can't be less than zero");
3783 if (!Sym->isUndefined())
3784 return Error(IDLoc, "invalid symbol redefinition");
3786 // Create the Symbol as a common or local common with Size and Pow2Alignment
3788 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3792 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3796 /// parseDirectiveAbort
3797 /// ::= .abort [... message ...]
3798 bool AsmParser::parseDirectiveAbort() {
3799 // FIXME: Use loc from directive.
3800 SMLoc Loc = getLexer().getLoc();
3802 StringRef Str = parseStringToEndOfStatement();
3803 if (getLexer().isNot(AsmToken::EndOfStatement))
3804 return TokError("unexpected token in '.abort' directive");
3809 Error(Loc, ".abort detected. Assembly stopping.");
3811 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3812 // FIXME: Actually abort assembly here.
3817 /// parseDirectiveInclude
3818 /// ::= .include "filename"
3819 bool AsmParser::parseDirectiveInclude() {
3820 if (getLexer().isNot(AsmToken::String))
3821 return TokError("expected string in '.include' directive");
3823 // Allow the strings to have escaped octal character sequence.
3824 std::string Filename;
3825 if (parseEscapedString(Filename))
3827 SMLoc IncludeLoc = getLexer().getLoc();
3830 if (getLexer().isNot(AsmToken::EndOfStatement))
3831 return TokError("unexpected token in '.include' directive");
3833 // Attempt to switch the lexer to the included file before consuming the end
3834 // of statement to avoid losing it when we switch.
3835 if (enterIncludeFile(Filename)) {
3836 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3843 /// parseDirectiveIncbin
3844 /// ::= .incbin "filename"
3845 bool AsmParser::parseDirectiveIncbin() {
3846 if (getLexer().isNot(AsmToken::String))
3847 return TokError("expected string in '.incbin' directive");
3849 // Allow the strings to have escaped octal character sequence.
3850 std::string Filename;
3851 if (parseEscapedString(Filename))
3853 SMLoc IncbinLoc = getLexer().getLoc();
3856 if (getLexer().isNot(AsmToken::EndOfStatement))
3857 return TokError("unexpected token in '.incbin' directive");
3859 // Attempt to process the included file.
3860 if (processIncbinFile(Filename)) {
3861 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3868 /// parseDirectiveIf
3869 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
3870 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
3871 TheCondStack.push_back(TheCondState);
3872 TheCondState.TheCond = AsmCond::IfCond;
3873 if (TheCondState.Ignore) {
3874 eatToEndOfStatement();
3877 if (parseAbsoluteExpression(ExprValue))
3880 if (getLexer().isNot(AsmToken::EndOfStatement))
3881 return TokError("unexpected token in '.if' directive");
3887 llvm_unreachable("unsupported directive");
3892 ExprValue = ExprValue == 0;
3895 ExprValue = ExprValue >= 0;
3898 ExprValue = ExprValue > 0;
3901 ExprValue = ExprValue <= 0;
3904 ExprValue = ExprValue < 0;
3908 TheCondState.CondMet = ExprValue;
3909 TheCondState.Ignore = !TheCondState.CondMet;
3915 /// parseDirectiveIfb
3917 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3918 TheCondStack.push_back(TheCondState);
3919 TheCondState.TheCond = AsmCond::IfCond;
3921 if (TheCondState.Ignore) {
3922 eatToEndOfStatement();
3924 StringRef Str = parseStringToEndOfStatement();
3926 if (getLexer().isNot(AsmToken::EndOfStatement))
3927 return TokError("unexpected token in '.ifb' directive");
3931 TheCondState.CondMet = ExpectBlank == Str.empty();
3932 TheCondState.Ignore = !TheCondState.CondMet;
3938 /// parseDirectiveIfc
3939 /// ::= .ifc string1, string2
3940 /// ::= .ifnc string1, string2
3941 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3942 TheCondStack.push_back(TheCondState);
3943 TheCondState.TheCond = AsmCond::IfCond;
3945 if (TheCondState.Ignore) {
3946 eatToEndOfStatement();
3948 StringRef Str1 = parseStringToComma();
3950 if (getLexer().isNot(AsmToken::Comma))
3951 return TokError("unexpected token in '.ifc' directive");
3955 StringRef Str2 = parseStringToEndOfStatement();
3957 if (getLexer().isNot(AsmToken::EndOfStatement))
3958 return TokError("unexpected token in '.ifc' directive");
3962 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3963 TheCondState.Ignore = !TheCondState.CondMet;
3969 /// parseDirectiveIfeqs
3970 /// ::= .ifeqs string1, string2
3971 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
3972 if (Lexer.isNot(AsmToken::String)) {
3974 TokError("expected string parameter for '.ifeqs' directive");
3976 TokError("expected string parameter for '.ifnes' directive");
3977 eatToEndOfStatement();
3981 StringRef String1 = getTok().getStringContents();
3984 if (Lexer.isNot(AsmToken::Comma)) {
3986 TokError("expected comma after first string for '.ifeqs' directive");
3988 TokError("expected comma after first string for '.ifnes' directive");
3989 eatToEndOfStatement();
3995 if (Lexer.isNot(AsmToken::String)) {
3997 TokError("expected string parameter for '.ifeqs' directive");
3999 TokError("expected string parameter for '.ifnes' directive");
4000 eatToEndOfStatement();
4004 StringRef String2 = getTok().getStringContents();
4007 TheCondStack.push_back(TheCondState);
4008 TheCondState.TheCond = AsmCond::IfCond;
4009 TheCondState.CondMet = ExpectEqual == (String1 == String2);
4010 TheCondState.Ignore = !TheCondState.CondMet;
4015 /// parseDirectiveIfdef
4016 /// ::= .ifdef symbol
4017 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
4019 TheCondStack.push_back(TheCondState);
4020 TheCondState.TheCond = AsmCond::IfCond;
4022 if (TheCondState.Ignore) {
4023 eatToEndOfStatement();
4025 if (parseIdentifier(Name))
4026 return TokError("expected identifier after '.ifdef'");
4030 MCSymbol *Sym = getContext().LookupSymbol(Name);
4033 TheCondState.CondMet = (Sym && !Sym->isUndefined());
4035 TheCondState.CondMet = (!Sym || Sym->isUndefined());
4036 TheCondState.Ignore = !TheCondState.CondMet;
4042 /// parseDirectiveElseIf
4043 /// ::= .elseif expression
4044 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4045 if (TheCondState.TheCond != AsmCond::IfCond &&
4046 TheCondState.TheCond != AsmCond::ElseIfCond)
4047 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4049 TheCondState.TheCond = AsmCond::ElseIfCond;
4051 bool LastIgnoreState = false;
4052 if (!TheCondStack.empty())
4053 LastIgnoreState = TheCondStack.back().Ignore;
4054 if (LastIgnoreState || TheCondState.CondMet) {
4055 TheCondState.Ignore = true;
4056 eatToEndOfStatement();
4059 if (parseAbsoluteExpression(ExprValue))
4062 if (getLexer().isNot(AsmToken::EndOfStatement))
4063 return TokError("unexpected token in '.elseif' directive");
4066 TheCondState.CondMet = ExprValue;
4067 TheCondState.Ignore = !TheCondState.CondMet;
4073 /// parseDirectiveElse
4075 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4076 if (getLexer().isNot(AsmToken::EndOfStatement))
4077 return TokError("unexpected token in '.else' directive");
4081 if (TheCondState.TheCond != AsmCond::IfCond &&
4082 TheCondState.TheCond != AsmCond::ElseIfCond)
4083 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4085 TheCondState.TheCond = AsmCond::ElseCond;
4086 bool LastIgnoreState = false;
4087 if (!TheCondStack.empty())
4088 LastIgnoreState = TheCondStack.back().Ignore;
4089 if (LastIgnoreState || TheCondState.CondMet)
4090 TheCondState.Ignore = true;
4092 TheCondState.Ignore = false;
4097 /// parseDirectiveEnd
4099 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4100 if (getLexer().isNot(AsmToken::EndOfStatement))
4101 return TokError("unexpected token in '.end' directive");
4105 while (Lexer.isNot(AsmToken::Eof))
4111 /// parseDirectiveError
4113 /// ::= .error [string]
4114 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4115 if (!TheCondStack.empty()) {
4116 if (TheCondStack.back().Ignore) {
4117 eatToEndOfStatement();
4123 return Error(L, ".err encountered");
4125 StringRef Message = ".error directive invoked in source file";
4126 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4127 if (Lexer.isNot(AsmToken::String)) {
4128 TokError(".error argument must be a string");
4129 eatToEndOfStatement();
4133 Message = getTok().getStringContents();
4141 /// parseDirectiveWarning
4142 /// ::= .warning [string]
4143 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4144 if (!TheCondStack.empty()) {
4145 if (TheCondStack.back().Ignore) {
4146 eatToEndOfStatement();
4151 StringRef Message = ".warning directive invoked in source file";
4152 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4153 if (Lexer.isNot(AsmToken::String)) {
4154 TokError(".warning argument must be a string");
4155 eatToEndOfStatement();
4159 Message = getTok().getStringContents();
4163 Warning(L, Message);
4167 /// parseDirectiveEndIf
4169 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4170 if (getLexer().isNot(AsmToken::EndOfStatement))
4171 return TokError("unexpected token in '.endif' directive");
4175 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4176 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4178 if (!TheCondStack.empty()) {
4179 TheCondState = TheCondStack.back();
4180 TheCondStack.pop_back();
4186 void AsmParser::initializeDirectiveKindMap() {
4187 DirectiveKindMap[".set"] = DK_SET;
4188 DirectiveKindMap[".equ"] = DK_EQU;
4189 DirectiveKindMap[".equiv"] = DK_EQUIV;
4190 DirectiveKindMap[".ascii"] = DK_ASCII;
4191 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4192 DirectiveKindMap[".string"] = DK_STRING;
4193 DirectiveKindMap[".byte"] = DK_BYTE;
4194 DirectiveKindMap[".short"] = DK_SHORT;
4195 DirectiveKindMap[".value"] = DK_VALUE;
4196 DirectiveKindMap[".2byte"] = DK_2BYTE;
4197 DirectiveKindMap[".long"] = DK_LONG;
4198 DirectiveKindMap[".int"] = DK_INT;
4199 DirectiveKindMap[".4byte"] = DK_4BYTE;
4200 DirectiveKindMap[".quad"] = DK_QUAD;
4201 DirectiveKindMap[".8byte"] = DK_8BYTE;
4202 DirectiveKindMap[".octa"] = DK_OCTA;
4203 DirectiveKindMap[".single"] = DK_SINGLE;
4204 DirectiveKindMap[".float"] = DK_FLOAT;
4205 DirectiveKindMap[".double"] = DK_DOUBLE;
4206 DirectiveKindMap[".align"] = DK_ALIGN;
4207 DirectiveKindMap[".align32"] = DK_ALIGN32;
4208 DirectiveKindMap[".balign"] = DK_BALIGN;
4209 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4210 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4211 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4212 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4213 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4214 DirectiveKindMap[".org"] = DK_ORG;
4215 DirectiveKindMap[".fill"] = DK_FILL;
4216 DirectiveKindMap[".zero"] = DK_ZERO;
4217 DirectiveKindMap[".extern"] = DK_EXTERN;
4218 DirectiveKindMap[".globl"] = DK_GLOBL;
4219 DirectiveKindMap[".global"] = DK_GLOBAL;
4220 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4221 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4222 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4223 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4224 DirectiveKindMap[".reference"] = DK_REFERENCE;
4225 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4226 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4227 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4228 DirectiveKindMap[".comm"] = DK_COMM;
4229 DirectiveKindMap[".common"] = DK_COMMON;
4230 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4231 DirectiveKindMap[".abort"] = DK_ABORT;
4232 DirectiveKindMap[".include"] = DK_INCLUDE;
4233 DirectiveKindMap[".incbin"] = DK_INCBIN;
4234 DirectiveKindMap[".code16"] = DK_CODE16;
4235 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4236 DirectiveKindMap[".rept"] = DK_REPT;
4237 DirectiveKindMap[".rep"] = DK_REPT;
4238 DirectiveKindMap[".irp"] = DK_IRP;
4239 DirectiveKindMap[".irpc"] = DK_IRPC;
4240 DirectiveKindMap[".endr"] = DK_ENDR;
4241 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4242 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4243 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4244 DirectiveKindMap[".if"] = DK_IF;
4245 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4246 DirectiveKindMap[".ifge"] = DK_IFGE;
4247 DirectiveKindMap[".ifgt"] = DK_IFGT;
4248 DirectiveKindMap[".ifle"] = DK_IFLE;
4249 DirectiveKindMap[".iflt"] = DK_IFLT;
4250 DirectiveKindMap[".ifne"] = DK_IFNE;
4251 DirectiveKindMap[".ifb"] = DK_IFB;
4252 DirectiveKindMap[".ifnb"] = DK_IFNB;
4253 DirectiveKindMap[".ifc"] = DK_IFC;
4254 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4255 DirectiveKindMap[".ifnc"] = DK_IFNC;
4256 DirectiveKindMap[".ifnes"] = DK_IFNES;
4257 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4258 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4259 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4260 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4261 DirectiveKindMap[".else"] = DK_ELSE;
4262 DirectiveKindMap[".end"] = DK_END;
4263 DirectiveKindMap[".endif"] = DK_ENDIF;
4264 DirectiveKindMap[".skip"] = DK_SKIP;
4265 DirectiveKindMap[".space"] = DK_SPACE;
4266 DirectiveKindMap[".file"] = DK_FILE;
4267 DirectiveKindMap[".line"] = DK_LINE;
4268 DirectiveKindMap[".loc"] = DK_LOC;
4269 DirectiveKindMap[".stabs"] = DK_STABS;
4270 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4271 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4272 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4273 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4274 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4275 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4276 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4277 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4278 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4279 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4280 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4281 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4282 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4283 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4284 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4285 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4286 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4287 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4288 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4289 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4290 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4291 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4292 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4293 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4294 DirectiveKindMap[".macro"] = DK_MACRO;
4295 DirectiveKindMap[".exitm"] = DK_EXITM;
4296 DirectiveKindMap[".endm"] = DK_ENDM;
4297 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4298 DirectiveKindMap[".purgem"] = DK_PURGEM;
4299 DirectiveKindMap[".err"] = DK_ERR;
4300 DirectiveKindMap[".error"] = DK_ERROR;
4301 DirectiveKindMap[".warning"] = DK_WARNING;
4304 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4305 AsmToken EndToken, StartToken = getTok();
4307 unsigned NestLevel = 0;
4309 // Check whether we have reached the end of the file.
4310 if (getLexer().is(AsmToken::Eof)) {
4311 Error(DirectiveLoc, "no matching '.endr' in definition");
4315 if (Lexer.is(AsmToken::Identifier) &&
4316 (getTok().getIdentifier() == ".rept")) {
4320 // Otherwise, check whether we have reached the .endr.
4321 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4322 if (NestLevel == 0) {
4323 EndToken = getTok();
4325 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4326 TokError("unexpected token in '.endr' directive");
4334 // Otherwise, scan till the end of the statement.
4335 eatToEndOfStatement();
4338 const char *BodyStart = StartToken.getLoc().getPointer();
4339 const char *BodyEnd = EndToken.getLoc().getPointer();
4340 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4342 // We Are Anonymous.
4343 MacroLikeBodies.push_back(
4344 MCAsmMacro(StringRef(), Body, MCAsmMacroParameters()));
4345 return &MacroLikeBodies.back();
4348 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4349 raw_svector_ostream &OS) {
4352 std::unique_ptr<MemoryBuffer> Instantiation =
4353 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4355 // Create the macro instantiation object and add to the current macro
4356 // instantiation stack.
4357 MacroInstantiation *MI = new MacroInstantiation(
4358 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
4359 ActiveMacros.push_back(MI);
4361 // Jump to the macro instantiation and prime the lexer.
4362 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
4363 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
4367 /// parseDirectiveRept
4368 /// ::= .rep | .rept count
4369 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4370 const MCExpr *CountExpr;
4371 SMLoc CountLoc = getTok().getLoc();
4372 if (parseExpression(CountExpr))
4376 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4377 eatToEndOfStatement();
4378 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4382 return Error(CountLoc, "Count is negative");
4384 if (Lexer.isNot(AsmToken::EndOfStatement))
4385 return TokError("unexpected token in '" + Dir + "' directive");
4387 // Eat the end of statement.
4390 // Lex the rept definition.
4391 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4395 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4396 // to hold the macro body with substitutions.
4397 SmallString<256> Buf;
4398 raw_svector_ostream OS(Buf);
4400 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4401 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
4404 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4409 /// parseDirectiveIrp
4410 /// ::= .irp symbol,values
4411 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4412 MCAsmMacroParameter Parameter;
4414 if (parseIdentifier(Parameter.Name))
4415 return TokError("expected identifier in '.irp' directive");
4417 if (Lexer.isNot(AsmToken::Comma))
4418 return TokError("expected comma in '.irp' directive");
4422 MCAsmMacroArguments A;
4423 if (parseMacroArguments(nullptr, A))
4426 // Eat the end of statement.
4429 // Lex the irp definition.
4430 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4434 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4435 // to hold the macro body with substitutions.
4436 SmallString<256> Buf;
4437 raw_svector_ostream OS(Buf);
4439 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4440 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4441 // This is undocumented, but GAS seems to support it.
4442 if (expandMacro(OS, M->Body, Parameter, *i, true, getTok().getLoc()))
4446 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4451 /// parseDirectiveIrpc
4452 /// ::= .irpc symbol,values
4453 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4454 MCAsmMacroParameter Parameter;
4456 if (parseIdentifier(Parameter.Name))
4457 return TokError("expected identifier in '.irpc' directive");
4459 if (Lexer.isNot(AsmToken::Comma))
4460 return TokError("expected comma in '.irpc' directive");
4464 MCAsmMacroArguments A;
4465 if (parseMacroArguments(nullptr, A))
4468 if (A.size() != 1 || A.front().size() != 1)
4469 return TokError("unexpected token in '.irpc' directive");
4471 // Eat the end of statement.
4474 // Lex the irpc definition.
4475 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4479 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4480 // to hold the macro body with substitutions.
4481 SmallString<256> Buf;
4482 raw_svector_ostream OS(Buf);
4484 StringRef Values = A.front().front().getString();
4485 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4486 MCAsmMacroArgument Arg;
4487 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4489 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4490 // This is undocumented, but GAS seems to support it.
4491 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
4495 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4500 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4501 if (ActiveMacros.empty())
4502 return TokError("unmatched '.endr' directive");
4504 // The only .repl that should get here are the ones created by
4505 // instantiateMacroLikeBody.
4506 assert(getLexer().is(AsmToken::EndOfStatement));
4512 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4514 const MCExpr *Value;
4515 SMLoc ExprLoc = getLexer().getLoc();
4516 if (parseExpression(Value))
4518 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4520 return Error(ExprLoc, "unexpected expression in _emit");
4521 uint64_t IntValue = MCE->getValue();
4522 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4523 return Error(ExprLoc, "literal value out of range for directive");
4525 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4529 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4530 const MCExpr *Value;
4531 SMLoc ExprLoc = getLexer().getLoc();
4532 if (parseExpression(Value))
4534 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4536 return Error(ExprLoc, "unexpected expression in align");
4537 uint64_t IntValue = MCE->getValue();
4538 if (!isPowerOf2_64(IntValue))
4539 return Error(ExprLoc, "literal value not a power of two greater then zero");
4541 Info.AsmRewrites->push_back(
4542 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4546 // We are comparing pointers, but the pointers are relative to a single string.
4547 // Thus, this should always be deterministic.
4548 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4549 const AsmRewrite *AsmRewriteB) {
4550 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4552 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4555 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4556 // rewrite to the same location. Make sure the SizeDirective rewrite is
4557 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4558 // ensures the sort algorithm is stable.
4559 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4560 AsmRewritePrecedence[AsmRewriteB->Kind])
4563 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4564 AsmRewritePrecedence[AsmRewriteB->Kind])
4566 llvm_unreachable("Unstable rewrite sort.");
4569 bool AsmParser::parseMSInlineAsm(
4570 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4571 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4572 SmallVectorImpl<std::string> &Constraints,
4573 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4574 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4575 SmallVector<void *, 4> InputDecls;
4576 SmallVector<void *, 4> OutputDecls;
4577 SmallVector<bool, 4> InputDeclsAddressOf;
4578 SmallVector<bool, 4> OutputDeclsAddressOf;
4579 SmallVector<std::string, 4> InputConstraints;
4580 SmallVector<std::string, 4> OutputConstraints;
4581 SmallVector<unsigned, 4> ClobberRegs;
4583 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4588 // While we have input, parse each statement.
4589 unsigned InputIdx = 0;
4590 unsigned OutputIdx = 0;
4591 while (getLexer().isNot(AsmToken::Eof)) {
4592 ParseStatementInfo Info(&AsmStrRewrites);
4593 if (parseStatement(Info, &SI))
4596 if (Info.ParseError)
4599 if (Info.Opcode == ~0U)
4602 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4604 // Build the list of clobbers, outputs and inputs.
4605 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4606 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4609 if (Operand.isImm())
4612 // Register operand.
4613 if (Operand.isReg() && !Operand.needAddressOf() &&
4614 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
4615 unsigned NumDefs = Desc.getNumDefs();
4617 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4618 ClobberRegs.push_back(Operand.getReg());
4622 // Expr/Input or Output.
4623 StringRef SymName = Operand.getSymName();
4624 if (SymName.empty())
4627 void *OpDecl = Operand.getOpDecl();
4631 bool isOutput = (i == 1) && Desc.mayStore();
4632 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4635 OutputDecls.push_back(OpDecl);
4636 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4637 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
4638 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4640 InputDecls.push_back(OpDecl);
4641 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4642 InputConstraints.push_back(Operand.getConstraint().str());
4643 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4647 // Consider implicit defs to be clobbers. Think of cpuid and push.
4648 ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
4649 Desc.getNumImplicitDefs());
4650 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
4653 // Set the number of Outputs and Inputs.
4654 NumOutputs = OutputDecls.size();
4655 NumInputs = InputDecls.size();
4657 // Set the unique clobbers.
4658 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4659 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4661 Clobbers.assign(ClobberRegs.size(), std::string());
4662 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4663 raw_string_ostream OS(Clobbers[I]);
4664 IP->printRegName(OS, ClobberRegs[I]);
4667 // Merge the various outputs and inputs. Output are expected first.
4668 if (NumOutputs || NumInputs) {
4669 unsigned NumExprs = NumOutputs + NumInputs;
4670 OpDecls.resize(NumExprs);
4671 Constraints.resize(NumExprs);
4672 for (unsigned i = 0; i < NumOutputs; ++i) {
4673 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4674 Constraints[i] = OutputConstraints[i];
4676 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4677 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4678 Constraints[j] = InputConstraints[i];
4682 // Build the IR assembly string.
4683 std::string AsmStringIR;
4684 raw_string_ostream OS(AsmStringIR);
4685 StringRef ASMString =
4686 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4687 const char *AsmStart = ASMString.begin();
4688 const char *AsmEnd = ASMString.end();
4689 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4690 for (const AsmRewrite &AR : AsmStrRewrites) {
4691 AsmRewriteKind Kind = AR.Kind;
4692 if (Kind == AOK_Delete)
4695 const char *Loc = AR.Loc.getPointer();
4696 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4698 // Emit everything up to the immediate/expression.
4699 if (unsigned Len = Loc - AsmStart)
4700 OS << StringRef(AsmStart, Len);
4702 // Skip the original expression.
4703 if (Kind == AOK_Skip) {
4704 AsmStart = Loc + AR.Len;
4708 unsigned AdditionalSkip = 0;
4709 // Rewrite expressions in $N notation.
4714 OS << "$$" << AR.Val;
4720 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
4723 OS << '$' << InputIdx++;
4726 OS << '$' << OutputIdx++;
4728 case AOK_SizeDirective:
4731 case 8: OS << "byte ptr "; break;
4732 case 16: OS << "word ptr "; break;
4733 case 32: OS << "dword ptr "; break;
4734 case 64: OS << "qword ptr "; break;
4735 case 80: OS << "xword ptr "; break;
4736 case 128: OS << "xmmword ptr "; break;
4737 case 256: OS << "ymmword ptr "; break;
4744 unsigned Val = AR.Val;
4745 OS << ".align " << Val;
4747 // Skip the original immediate.
4748 assert(Val < 10 && "Expected alignment less then 2^10.");
4749 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4752 case AOK_DotOperator:
4753 // Insert the dot if the user omitted it.
4755 if (AsmStringIR.back() != '.')
4761 // Skip the original expression.
4762 AsmStart = Loc + AR.Len + AdditionalSkip;
4765 // Emit the remainder of the asm string.
4766 if (AsmStart != AsmEnd)
4767 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4769 AsmString = OS.str();
4773 /// \brief Create an MCAsmParser instance.
4774 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4775 MCStreamer &Out, const MCAsmInfo &MAI) {
4776 return new AsmParser(SM, C, Out, MAI);