1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCParser/AsmCond.h"
27 #include "llvm/MC/MCParser/AsmLexer.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
30 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCSectionMachO.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/MC/MCTargetAsmParser.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/SourceMgr.h"
41 #include "llvm/Support/raw_ostream.h"
49 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
52 /// \brief Helper types for tracking macro definitions.
53 typedef std::vector<AsmToken> MCAsmMacroArgument;
54 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
56 struct MCAsmMacroParameter {
58 MCAsmMacroArgument Value;
62 MCAsmMacroParameter() : Required(false), Vararg(false) {}
65 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
70 MCAsmMacroParameters Parameters;
73 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
74 : Name(N), Body(B), Parameters(std::move(P)) {}
77 /// \brief Helper class for storing information about an active macro
79 struct MacroInstantiation {
80 /// The location of the instantiation.
81 SMLoc InstantiationLoc;
83 /// The buffer where parsing should resume upon instantiation completion.
86 /// The location where parsing should resume upon instantiation completion.
89 /// The depth of TheCondStack at the start of the instantiation.
90 size_t CondStackDepth;
93 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
96 struct ParseStatementInfo {
97 /// \brief The parsed operands from the last parsed statement.
98 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
100 /// \brief The opcode from the last parsed instruction.
103 /// \brief Was there an error parsing the inline assembly?
106 SmallVectorImpl<AsmRewrite> *AsmRewrites;
108 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
109 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
110 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
113 /// \brief The concrete assembly parser instance.
114 class AsmParser : public MCAsmParser {
115 AsmParser(const AsmParser &) = delete;
116 void operator=(const AsmParser &) = delete;
121 const MCAsmInfo &MAI;
123 SourceMgr::DiagHandlerTy SavedDiagHandler;
124 void *SavedDiagContext;
125 std::unique_ptr<MCAsmParserExtension> PlatformParser;
127 /// This is the current buffer index we're lexing from as managed by the
128 /// SourceMgr object.
131 AsmCond TheCondState;
132 std::vector<AsmCond> TheCondStack;
134 /// \brief maps directive names to handler methods in parser
135 /// extensions. Extensions register themselves in this map by calling
136 /// addDirectiveHandler.
137 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
139 /// \brief Map of currently defined macros.
140 StringMap<MCAsmMacro> MacroMap;
142 /// \brief Stack of active macro instantiations.
143 std::vector<MacroInstantiation*> ActiveMacros;
145 /// \brief List of bodies of anonymous macros.
146 std::deque<MCAsmMacro> MacroLikeBodies;
148 /// Boolean tracking whether macro substitution is enabled.
149 unsigned MacrosEnabledFlag : 1;
151 /// \brief Keeps track of how many .macro's have been instantiated.
152 unsigned NumOfMacroInstantiations;
154 /// Flag tracking whether any errors have been encountered.
155 unsigned HadError : 1;
157 /// The values from the last parsed cpp hash file line comment if any.
158 StringRef CppHashFilename;
159 int64_t CppHashLineNumber;
162 /// When generating dwarf for assembly source files we need to calculate the
163 /// logical line number based on the last parsed cpp hash file line comment
164 /// and current line. Since this is slow and messes up the SourceMgr's
165 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
166 SMLoc LastQueryIDLoc;
167 unsigned LastQueryBuffer;
168 unsigned LastQueryLine;
170 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
171 unsigned AssemblerDialect;
173 /// \brief is Darwin compatibility enabled?
176 /// \brief Are we parsing ms-style inline assembly?
177 bool ParsingInlineAsm;
180 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
181 const MCAsmInfo &MAI);
182 ~AsmParser() override;
184 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
186 void addDirectiveHandler(StringRef Directive,
187 ExtensionDirectiveHandler Handler) override {
188 ExtensionDirectiveMap[Directive] = Handler;
191 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
192 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
196 /// @name MCAsmParser Interface
199 SourceMgr &getSourceManager() override { return SrcMgr; }
200 MCAsmLexer &getLexer() override { return Lexer; }
201 MCContext &getContext() override { return Ctx; }
202 MCStreamer &getStreamer() override { return Out; }
203 unsigned getAssemblerDialect() override {
204 if (AssemblerDialect == ~0U)
205 return MAI.getAssemblerDialect();
207 return AssemblerDialect;
209 void setAssemblerDialect(unsigned i) override {
210 AssemblerDialect = i;
213 void Note(SMLoc L, const Twine &Msg,
214 ArrayRef<SMRange> Ranges = None) override;
215 bool Warning(SMLoc L, const Twine &Msg,
216 ArrayRef<SMRange> Ranges = None) override;
217 bool Error(SMLoc L, const Twine &Msg,
218 ArrayRef<SMRange> Ranges = None) override;
220 const AsmToken &Lex() override;
222 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
223 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
225 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
226 unsigned &NumOutputs, unsigned &NumInputs,
227 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
228 SmallVectorImpl<std::string> &Constraints,
229 SmallVectorImpl<std::string> &Clobbers,
230 const MCInstrInfo *MII, const MCInstPrinter *IP,
231 MCAsmParserSemaCallback &SI) override;
233 bool parseExpression(const MCExpr *&Res);
234 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
235 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
236 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
237 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
238 SMLoc &EndLoc) override;
239 bool parseAbsoluteExpression(int64_t &Res) override;
241 /// \brief Parse an identifier or string (as a quoted identifier)
242 /// and set \p Res to the identifier contents.
243 bool parseIdentifier(StringRef &Res) override;
244 void eatToEndOfStatement() override;
246 void checkForValidSection() override;
251 bool parseStatement(ParseStatementInfo &Info,
252 MCAsmParserSemaCallback *SI);
253 void eatToEndOfLine();
254 bool parseCppHashLineFilenameComment(const SMLoc &L);
256 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
257 ArrayRef<MCAsmMacroParameter> Parameters);
258 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
259 ArrayRef<MCAsmMacroParameter> Parameters,
260 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
263 /// \brief Are macros enabled in the parser?
264 bool areMacrosEnabled() {return MacrosEnabledFlag;}
266 /// \brief Control a flag in the parser that enables or disables macros.
267 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
269 /// \brief Lookup a previously defined macro.
270 /// \param Name Macro name.
271 /// \returns Pointer to macro. NULL if no such macro was defined.
272 const MCAsmMacro* lookupMacro(StringRef Name);
274 /// \brief Define a new macro with the given name and information.
275 void defineMacro(StringRef Name, MCAsmMacro Macro);
277 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
278 void undefineMacro(StringRef Name);
280 /// \brief Are we inside a macro instantiation?
281 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
283 /// \brief Handle entry to macro instantiation.
285 /// \param M The macro.
286 /// \param NameLoc Instantiation location.
287 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
289 /// \brief Handle exit from macro instantiation.
290 void handleMacroExit();
292 /// \brief Extract AsmTokens for a macro argument.
293 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
295 /// \brief Parse all macro arguments for a given macro.
296 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
298 void printMacroInstantiations();
299 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
300 ArrayRef<SMRange> Ranges = None) const {
301 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
303 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
305 /// \brief Enter the specified file. This returns true on failure.
306 bool enterIncludeFile(const std::string &Filename);
308 /// \brief Process the specified file for the .incbin directive.
309 /// This returns true on failure.
310 bool processIncbinFile(const std::string &Filename);
312 /// \brief Reset the current lexer position to that given by \p Loc. The
313 /// current token is not set; clients should ensure Lex() is called
316 /// \param InBuffer If not 0, should be the known buffer id that contains the
318 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
320 /// \brief Parse up to the end of statement and a return the contents from the
321 /// current token until the end of the statement; the current token on exit
322 /// will be either the EndOfStatement or EOF.
323 StringRef parseStringToEndOfStatement() override;
325 /// \brief Parse until the end of a statement or a comma is encountered,
326 /// return the contents from the current token up to the end or comma.
327 StringRef parseStringToComma();
329 bool parseAssignment(StringRef Name, bool allow_redef,
330 bool NoDeadStrip = false);
332 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
333 MCBinaryExpr::Opcode &Kind);
335 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
336 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
337 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
339 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
341 // Generic (target and platform independent) directive parsing.
343 DK_NO_DIRECTIVE, // Placeholder
344 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
345 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
346 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
347 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
348 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
349 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
350 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
351 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
352 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
353 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
354 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
355 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
356 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
357 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
358 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
359 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
360 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
361 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
362 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
363 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
364 DK_MACROS_ON, DK_MACROS_OFF,
365 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
366 DK_SLEB128, DK_ULEB128,
367 DK_ERR, DK_ERROR, DK_WARNING,
371 /// \brief Maps directive name --> DirectiveKind enum, for
372 /// directives parsed by this class.
373 StringMap<DirectiveKind> DirectiveKindMap;
375 // ".ascii", ".asciz", ".string"
376 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
377 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
378 bool parseDirectiveOctaValue(); // ".octa"
379 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
380 bool parseDirectiveFill(); // ".fill"
381 bool parseDirectiveZero(); // ".zero"
382 // ".set", ".equ", ".equiv"
383 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
384 bool parseDirectiveOrg(); // ".org"
385 // ".align{,32}", ".p2align{,w,l}"
386 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
388 // ".file", ".line", ".loc", ".stabs"
389 bool parseDirectiveFile(SMLoc DirectiveLoc);
390 bool parseDirectiveLine();
391 bool parseDirectiveLoc();
392 bool parseDirectiveStabs();
395 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
396 bool parseDirectiveCFIWindowSave();
397 bool parseDirectiveCFISections();
398 bool parseDirectiveCFIStartProc();
399 bool parseDirectiveCFIEndProc();
400 bool parseDirectiveCFIDefCfaOffset();
401 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIAdjustCfaOffset();
403 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
404 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
405 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
406 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
407 bool parseDirectiveCFIRememberState();
408 bool parseDirectiveCFIRestoreState();
409 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
410 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
411 bool parseDirectiveCFIEscape();
412 bool parseDirectiveCFISignalFrame();
413 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
416 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
417 bool parseDirectiveExitMacro(StringRef Directive);
418 bool parseDirectiveEndMacro(StringRef Directive);
419 bool parseDirectiveMacro(SMLoc DirectiveLoc);
420 bool parseDirectiveMacrosOnOff(StringRef Directive);
422 // ".bundle_align_mode"
423 bool parseDirectiveBundleAlignMode();
425 bool parseDirectiveBundleLock();
427 bool parseDirectiveBundleUnlock();
430 bool parseDirectiveSpace(StringRef IDVal);
432 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
433 bool parseDirectiveLEB128(bool Signed);
435 /// \brief Parse a directive like ".globl" which
436 /// accepts a single symbol (which should be a label or an external).
437 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
439 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
441 bool parseDirectiveAbort(); // ".abort"
442 bool parseDirectiveInclude(); // ".include"
443 bool parseDirectiveIncbin(); // ".incbin"
445 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
446 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
447 // ".ifb" or ".ifnb", depending on ExpectBlank.
448 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
449 // ".ifc" or ".ifnc", depending on ExpectEqual.
450 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
451 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
452 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
453 // ".ifdef" or ".ifndef", depending on expect_defined
454 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
455 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
456 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
457 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
458 bool parseEscapedString(std::string &Data) override;
460 const MCExpr *applyModifierToExpr(const MCExpr *E,
461 MCSymbolRefExpr::VariantKind Variant);
463 // Macro-like directives
464 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
465 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
466 raw_svector_ostream &OS);
467 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
468 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
469 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
470 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
472 // "_emit" or "__emit"
473 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
477 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
480 bool parseDirectiveEnd(SMLoc DirectiveLoc);
482 // ".err" or ".error"
483 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
486 bool parseDirectiveWarning(SMLoc DirectiveLoc);
488 void initializeDirectiveKindMap();
494 extern MCAsmParserExtension *createDarwinAsmParser();
495 extern MCAsmParserExtension *createELFAsmParser();
496 extern MCAsmParserExtension *createCOFFAsmParser();
500 enum { DEFAULT_ADDRSPACE = 0 };
502 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
503 const MCAsmInfo &MAI)
504 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
505 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
506 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
507 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
508 // Save the old handler.
509 SavedDiagHandler = SrcMgr.getDiagHandler();
510 SavedDiagContext = SrcMgr.getDiagContext();
511 // Set our own handler which calls the saved handler.
512 SrcMgr.setDiagHandler(DiagHandler, this);
513 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
515 // Initialize the platform / file format parser.
516 switch (Ctx.getObjectFileInfo()->getTargetTriple().getObjectFormat()) {
518 PlatformParser.reset(createCOFFAsmParser());
521 PlatformParser.reset(createDarwinAsmParser());
525 PlatformParser.reset(createELFAsmParser());
527 case Triple::UnknownObjectFormat:
531 PlatformParser->Initialize(*this);
532 initializeDirectiveKindMap();
534 NumOfMacroInstantiations = 0;
537 AsmParser::~AsmParser() {
538 assert((HadError || ActiveMacros.empty()) &&
539 "Unexpected active macro instantiation!");
542 void AsmParser::printMacroInstantiations() {
543 // Print the active macro instantiation stack.
544 for (std::vector<MacroInstantiation *>::const_reverse_iterator
545 it = ActiveMacros.rbegin(),
546 ie = ActiveMacros.rend();
548 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
549 "while in macro instantiation");
552 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
553 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
554 printMacroInstantiations();
557 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
558 if(getTargetParser().getTargetOptions().MCNoWarn)
560 if (getTargetParser().getTargetOptions().MCFatalWarnings)
561 return Error(L, Msg, Ranges);
562 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
563 printMacroInstantiations();
567 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
569 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
570 printMacroInstantiations();
574 bool AsmParser::enterIncludeFile(const std::string &Filename) {
575 std::string IncludedFile;
577 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
582 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
586 /// Process the specified .incbin file by searching for it in the include paths
587 /// then just emitting the byte contents of the file to the streamer. This
588 /// returns true on failure.
589 bool AsmParser::processIncbinFile(const std::string &Filename) {
590 std::string IncludedFile;
592 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
596 // Pick up the bytes from the file and emit them.
597 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
601 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
602 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
603 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
607 const AsmToken &AsmParser::Lex() {
608 const AsmToken *tok = &Lexer.Lex();
610 if (tok->is(AsmToken::Eof)) {
611 // If this is the end of an included file, pop the parent file off the
613 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
614 if (ParentIncludeLoc != SMLoc()) {
615 jumpToLoc(ParentIncludeLoc);
620 if (tok->is(AsmToken::Error))
621 Error(Lexer.getErrLoc(), Lexer.getErr());
626 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
627 // Create the initial section, if requested.
628 if (!NoInitialTextSection)
629 Out.InitSections(false);
635 AsmCond StartingCondState = TheCondState;
637 // If we are generating dwarf for assembly source files save the initial text
638 // section and generate a .file directive.
639 if (getContext().getGenDwarfForAssembly()) {
640 MCSection *Sec = getStreamer().getCurrentSection().first;
641 if (!Sec->getBeginSymbol()) {
642 MCSymbol *SectionStartSym = getContext().createTempSymbol();
643 getStreamer().EmitLabel(SectionStartSym);
644 Sec->setBeginSymbol(SectionStartSym);
646 bool InsertResult = getContext().addGenDwarfSection(Sec);
647 assert(InsertResult && ".text section should not have debug info yet");
649 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
650 0, StringRef(), getContext().getMainFileName()));
653 // While we have input, parse each statement.
654 while (Lexer.isNot(AsmToken::Eof)) {
655 ParseStatementInfo Info;
656 if (!parseStatement(Info, nullptr))
659 // We had an error, validate that one was emitted and recover by skipping to
661 assert(HadError && "Parse statement returned an error, but none emitted!");
662 eatToEndOfStatement();
665 if (TheCondState.TheCond != StartingCondState.TheCond ||
666 TheCondState.Ignore != StartingCondState.Ignore)
667 return TokError("unmatched .ifs or .elses");
669 // Check to see there are no empty DwarfFile slots.
670 const auto &LineTables = getContext().getMCDwarfLineTables();
671 if (!LineTables.empty()) {
673 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
674 if (File.Name.empty() && Index != 0)
675 TokError("unassigned file number: " + Twine(Index) +
676 " for .file directives");
681 // Check to see that all assembler local symbols were actually defined.
682 // Targets that don't do subsections via symbols may not want this, though,
683 // so conservatively exclude them. Only do this if we're finalizing, though,
684 // as otherwise we won't necessarilly have seen everything yet.
685 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
686 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
687 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
690 MCSymbol *Sym = i->getValue();
691 // Variable symbols may not be marked as defined, so check those
692 // explicitly. If we know it's a variable, we have a definition for
693 // the purposes of this check.
694 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
695 // FIXME: We would really like to refer back to where the symbol was
696 // first referenced for a source location. We need to add something
697 // to track that. Currently, we just point to the end of the file.
699 getLexer().getLoc(), SourceMgr::DK_Error,
700 "assembler local symbol '" + Sym->getName() + "' not defined");
704 // Finalize the output stream if there are no errors and if the client wants
706 if (!HadError && !NoFinalize)
712 void AsmParser::checkForValidSection() {
713 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
714 TokError("expected section directive before assembly directive");
715 Out.InitSections(false);
719 /// \brief Throw away the rest of the line for testing purposes.
720 void AsmParser::eatToEndOfStatement() {
721 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
725 if (Lexer.is(AsmToken::EndOfStatement))
729 StringRef AsmParser::parseStringToEndOfStatement() {
730 const char *Start = getTok().getLoc().getPointer();
732 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
735 const char *End = getTok().getLoc().getPointer();
736 return StringRef(Start, End - Start);
739 StringRef AsmParser::parseStringToComma() {
740 const char *Start = getTok().getLoc().getPointer();
742 while (Lexer.isNot(AsmToken::EndOfStatement) &&
743 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
746 const char *End = getTok().getLoc().getPointer();
747 return StringRef(Start, End - Start);
750 /// \brief Parse a paren expression and return it.
751 /// NOTE: This assumes the leading '(' has already been consumed.
753 /// parenexpr ::= expr)
755 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
756 if (parseExpression(Res))
758 if (Lexer.isNot(AsmToken::RParen))
759 return TokError("expected ')' in parentheses expression");
760 EndLoc = Lexer.getTok().getEndLoc();
765 /// \brief Parse a bracket expression and return it.
766 /// NOTE: This assumes the leading '[' has already been consumed.
768 /// bracketexpr ::= expr]
770 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
771 if (parseExpression(Res))
773 if (Lexer.isNot(AsmToken::RBrac))
774 return TokError("expected ']' in brackets expression");
775 EndLoc = Lexer.getTok().getEndLoc();
780 /// \brief Parse a primary expression and return it.
781 /// primaryexpr ::= (parenexpr
782 /// primaryexpr ::= symbol
783 /// primaryexpr ::= number
784 /// primaryexpr ::= '.'
785 /// primaryexpr ::= ~,+,- primaryexpr
786 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
787 SMLoc FirstTokenLoc = getLexer().getLoc();
788 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
789 switch (FirstTokenKind) {
791 return TokError("unknown token in expression");
792 // If we have an error assume that we've already handled it.
793 case AsmToken::Error:
795 case AsmToken::Exclaim:
796 Lex(); // Eat the operator.
797 if (parsePrimaryExpr(Res, EndLoc))
799 Res = MCUnaryExpr::createLNot(Res, getContext());
801 case AsmToken::Dollar:
803 case AsmToken::String:
804 case AsmToken::Identifier: {
805 StringRef Identifier;
806 if (parseIdentifier(Identifier)) {
807 if (FirstTokenKind == AsmToken::Dollar) {
808 if (Lexer.getMAI().getDollarIsPC()) {
809 // This is a '$' reference, which references the current PC. Emit a
810 // temporary label to the streamer and refer to it.
811 MCSymbol *Sym = Ctx.createTempSymbol();
813 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
815 EndLoc = FirstTokenLoc;
818 return Error(FirstTokenLoc, "invalid token in expression");
821 // Parse symbol variant
822 std::pair<StringRef, StringRef> Split;
823 if (!MAI.useParensForSymbolVariant()) {
824 if (FirstTokenKind == AsmToken::String) {
825 if (Lexer.is(AsmToken::At)) {
826 Lexer.Lex(); // eat @
827 SMLoc AtLoc = getLexer().getLoc();
829 if (parseIdentifier(VName))
830 return Error(AtLoc, "expected symbol variant after '@'");
832 Split = std::make_pair(Identifier, VName);
835 Split = Identifier.split('@');
837 } else if (Lexer.is(AsmToken::LParen)) {
838 Lexer.Lex(); // eat (
840 parseIdentifier(VName);
841 if (Lexer.isNot(AsmToken::RParen)) {
842 return Error(Lexer.getTok().getLoc(),
843 "unexpected token in variant, expected ')'");
845 Lexer.Lex(); // eat )
846 Split = std::make_pair(Identifier, VName);
849 EndLoc = SMLoc::getFromPointer(Identifier.end());
851 // This is a symbol reference.
852 StringRef SymbolName = Identifier;
853 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
855 // Lookup the symbol variant if used.
856 if (Split.second.size()) {
857 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
858 if (Variant != MCSymbolRefExpr::VK_Invalid) {
859 SymbolName = Split.first;
860 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
861 Variant = MCSymbolRefExpr::VK_None;
863 return Error(SMLoc::getFromPointer(Split.second.begin()),
864 "invalid variant '" + Split.second + "'");
868 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
870 // If this is an absolute variable reference, substitute it now to preserve
871 // semantics in the face of reassignment.
872 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
874 return Error(EndLoc, "unexpected modifier on variable reference");
876 Res = Sym->getVariableValue();
880 // Otherwise create a symbol ref.
881 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
884 case AsmToken::BigNum:
885 return TokError("literal value out of range for directive");
886 case AsmToken::Integer: {
887 SMLoc Loc = getTok().getLoc();
888 int64_t IntVal = getTok().getIntVal();
889 Res = MCConstantExpr::create(IntVal, getContext());
890 EndLoc = Lexer.getTok().getEndLoc();
892 // Look for 'b' or 'f' following an Integer as a directional label
893 if (Lexer.getKind() == AsmToken::Identifier) {
894 StringRef IDVal = getTok().getString();
895 // Lookup the symbol variant if used.
896 std::pair<StringRef, StringRef> Split = IDVal.split('@');
897 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
898 if (Split.first.size() != IDVal.size()) {
899 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
900 if (Variant == MCSymbolRefExpr::VK_Invalid)
901 return TokError("invalid variant '" + Split.second + "'");
904 if (IDVal == "f" || IDVal == "b") {
906 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
907 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
908 if (IDVal == "b" && Sym->isUndefined())
909 return Error(Loc, "invalid reference to undefined symbol");
910 EndLoc = Lexer.getTok().getEndLoc();
911 Lex(); // Eat identifier.
916 case AsmToken::Real: {
917 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
918 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
919 Res = MCConstantExpr::create(IntVal, getContext());
920 EndLoc = Lexer.getTok().getEndLoc();
924 case AsmToken::Dot: {
925 // This is a '.' reference, which references the current PC. Emit a
926 // temporary label to the streamer and refer to it.
927 MCSymbol *Sym = Ctx.createTempSymbol();
929 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
930 EndLoc = Lexer.getTok().getEndLoc();
931 Lex(); // Eat identifier.
934 case AsmToken::LParen:
935 Lex(); // Eat the '('.
936 return parseParenExpr(Res, EndLoc);
937 case AsmToken::LBrac:
938 if (!PlatformParser->HasBracketExpressions())
939 return TokError("brackets expression not supported on this target");
940 Lex(); // Eat the '['.
941 return parseBracketExpr(Res, EndLoc);
942 case AsmToken::Minus:
943 Lex(); // Eat the operator.
944 if (parsePrimaryExpr(Res, EndLoc))
946 Res = MCUnaryExpr::createMinus(Res, getContext());
949 Lex(); // Eat the operator.
950 if (parsePrimaryExpr(Res, EndLoc))
952 Res = MCUnaryExpr::createPlus(Res, getContext());
954 case AsmToken::Tilde:
955 Lex(); // Eat the operator.
956 if (parsePrimaryExpr(Res, EndLoc))
958 Res = MCUnaryExpr::createNot(Res, getContext());
963 bool AsmParser::parseExpression(const MCExpr *&Res) {
965 return parseExpression(Res, EndLoc);
969 AsmParser::applyModifierToExpr(const MCExpr *E,
970 MCSymbolRefExpr::VariantKind Variant) {
971 // Ask the target implementation about this expression first.
972 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
975 // Recurse over the given expression, rebuilding it to apply the given variant
976 // if there is exactly one symbol.
977 switch (E->getKind()) {
979 case MCExpr::Constant:
982 case MCExpr::SymbolRef: {
983 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
985 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
986 TokError("invalid variant on expression '" + getTok().getIdentifier() +
987 "' (already modified)");
991 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
994 case MCExpr::Unary: {
995 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
996 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
999 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
1002 case MCExpr::Binary: {
1003 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1004 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1005 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1015 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1019 llvm_unreachable("Invalid expression kind!");
1022 /// \brief Parse an expression and return it.
1024 /// expr ::= expr &&,|| expr -> lowest.
1025 /// expr ::= expr |,^,&,! expr
1026 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1027 /// expr ::= expr <<,>> expr
1028 /// expr ::= expr +,- expr
1029 /// expr ::= expr *,/,% expr -> highest.
1030 /// expr ::= primaryexpr
1032 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1033 // Parse the expression.
1035 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1038 // As a special case, we support 'a op b @ modifier' by rewriting the
1039 // expression to include the modifier. This is inefficient, but in general we
1040 // expect users to use 'a@modifier op b'.
1041 if (Lexer.getKind() == AsmToken::At) {
1044 if (Lexer.isNot(AsmToken::Identifier))
1045 return TokError("unexpected symbol modifier following '@'");
1047 MCSymbolRefExpr::VariantKind Variant =
1048 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1049 if (Variant == MCSymbolRefExpr::VK_Invalid)
1050 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1052 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1054 return TokError("invalid modifier '" + getTok().getIdentifier() +
1055 "' (no symbols present)");
1062 // Try to constant fold it up front, if possible.
1064 if (Res->evaluateAsAbsolute(Value))
1065 Res = MCConstantExpr::create(Value, getContext());
1070 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1072 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1075 bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1077 if (parseParenExpr(Res, EndLoc))
1080 for (; ParenDepth > 0; --ParenDepth) {
1081 if (parseBinOpRHS(1, Res, EndLoc))
1084 // We don't Lex() the last RParen.
1085 // This is the same behavior as parseParenExpression().
1086 if (ParenDepth - 1 > 0) {
1087 if (Lexer.isNot(AsmToken::RParen))
1088 return TokError("expected ')' in parentheses expression");
1089 EndLoc = Lexer.getTok().getEndLoc();
1096 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1099 SMLoc StartLoc = Lexer.getLoc();
1100 if (parseExpression(Expr))
1103 if (!Expr->evaluateAsAbsolute(Res))
1104 return Error(StartLoc, "expected absolute expression");
1109 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1110 MCBinaryExpr::Opcode &Kind) {
1113 return 0; // not a binop.
1115 // Lowest Precedence: &&, ||
1116 case AsmToken::AmpAmp:
1117 Kind = MCBinaryExpr::LAnd;
1119 case AsmToken::PipePipe:
1120 Kind = MCBinaryExpr::LOr;
1123 // Low Precedence: |, &, ^
1125 // FIXME: gas seems to support '!' as an infix operator?
1126 case AsmToken::Pipe:
1127 Kind = MCBinaryExpr::Or;
1129 case AsmToken::Caret:
1130 Kind = MCBinaryExpr::Xor;
1133 Kind = MCBinaryExpr::And;
1136 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1137 case AsmToken::EqualEqual:
1138 Kind = MCBinaryExpr::EQ;
1140 case AsmToken::ExclaimEqual:
1141 case AsmToken::LessGreater:
1142 Kind = MCBinaryExpr::NE;
1144 case AsmToken::Less:
1145 Kind = MCBinaryExpr::LT;
1147 case AsmToken::LessEqual:
1148 Kind = MCBinaryExpr::LTE;
1150 case AsmToken::Greater:
1151 Kind = MCBinaryExpr::GT;
1153 case AsmToken::GreaterEqual:
1154 Kind = MCBinaryExpr::GTE;
1157 // Intermediate Precedence: <<, >>
1158 case AsmToken::LessLess:
1159 Kind = MCBinaryExpr::Shl;
1161 case AsmToken::GreaterGreater:
1162 Kind = MAI.shouldUseLogicalShr() ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1165 // High Intermediate Precedence: +, -
1166 case AsmToken::Plus:
1167 Kind = MCBinaryExpr::Add;
1169 case AsmToken::Minus:
1170 Kind = MCBinaryExpr::Sub;
1173 // Highest Precedence: *, /, %
1174 case AsmToken::Star:
1175 Kind = MCBinaryExpr::Mul;
1177 case AsmToken::Slash:
1178 Kind = MCBinaryExpr::Div;
1180 case AsmToken::Percent:
1181 Kind = MCBinaryExpr::Mod;
1186 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1187 /// Res contains the LHS of the expression on input.
1188 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1191 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1192 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1194 // If the next token is lower precedence than we are allowed to eat, return
1195 // successfully with what we ate already.
1196 if (TokPrec < Precedence)
1201 // Eat the next primary expression.
1203 if (parsePrimaryExpr(RHS, EndLoc))
1206 // If BinOp binds less tightly with RHS than the operator after RHS, let
1207 // the pending operator take RHS as its LHS.
1208 MCBinaryExpr::Opcode Dummy;
1209 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1210 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1213 // Merge LHS and RHS according to operator.
1214 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
1219 /// ::= EndOfStatement
1220 /// ::= Label* Directive ...Operands... EndOfStatement
1221 /// ::= Label* Identifier OperandList* EndOfStatement
1222 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1223 MCAsmParserSemaCallback *SI) {
1224 if (Lexer.is(AsmToken::EndOfStatement)) {
1230 // Statements always start with an identifier or are a full line comment.
1231 AsmToken ID = getTok();
1232 SMLoc IDLoc = ID.getLoc();
1234 int64_t LocalLabelVal = -1;
1235 // A full line comment is a '#' as the first token.
1236 if (Lexer.is(AsmToken::Hash))
1237 return parseCppHashLineFilenameComment(IDLoc);
1239 // Allow an integer followed by a ':' as a directional local label.
1240 if (Lexer.is(AsmToken::Integer)) {
1241 LocalLabelVal = getTok().getIntVal();
1242 if (LocalLabelVal < 0) {
1243 if (!TheCondState.Ignore)
1244 return TokError("unexpected token at start of statement");
1247 IDVal = getTok().getString();
1248 Lex(); // Consume the integer token to be used as an identifier token.
1249 if (Lexer.getKind() != AsmToken::Colon) {
1250 if (!TheCondState.Ignore)
1251 return TokError("unexpected token at start of statement");
1254 } else if (Lexer.is(AsmToken::Dot)) {
1255 // Treat '.' as a valid identifier in this context.
1258 } else if (parseIdentifier(IDVal)) {
1259 if (!TheCondState.Ignore)
1260 return TokError("unexpected token at start of statement");
1264 // Handle conditional assembly here before checking for skipping. We
1265 // have to do this so that .endif isn't skipped in a ".if 0" block for
1267 StringMap<DirectiveKind>::const_iterator DirKindIt =
1268 DirectiveKindMap.find(IDVal);
1269 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1271 : DirKindIt->getValue();
1282 return parseDirectiveIf(IDLoc, DirKind);
1284 return parseDirectiveIfb(IDLoc, true);
1286 return parseDirectiveIfb(IDLoc, false);
1288 return parseDirectiveIfc(IDLoc, true);
1290 return parseDirectiveIfeqs(IDLoc, true);
1292 return parseDirectiveIfc(IDLoc, false);
1294 return parseDirectiveIfeqs(IDLoc, false);
1296 return parseDirectiveIfdef(IDLoc, true);
1299 return parseDirectiveIfdef(IDLoc, false);
1301 return parseDirectiveElseIf(IDLoc);
1303 return parseDirectiveElse(IDLoc);
1305 return parseDirectiveEndIf(IDLoc);
1308 // Ignore the statement if in the middle of inactive conditional
1310 if (TheCondState.Ignore) {
1311 eatToEndOfStatement();
1315 // FIXME: Recurse on local labels?
1317 // See what kind of statement we have.
1318 switch (Lexer.getKind()) {
1319 case AsmToken::Colon: {
1320 checkForValidSection();
1322 // identifier ':' -> Label.
1325 // Diagnose attempt to use '.' as a label.
1327 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1329 // Diagnose attempt to use a variable as a label.
1331 // FIXME: Diagnostics. Note the location of the definition as a label.
1332 // FIXME: This doesn't diagnose assignment to a symbol which has been
1333 // implicitly marked as external.
1335 if (LocalLabelVal == -1) {
1336 if (ParsingInlineAsm && SI) {
1337 StringRef RewrittenLabel =
1338 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1339 assert(RewrittenLabel.size() &&
1340 "We should have an internal name here.");
1341 Info.AsmRewrites->push_back(AsmRewrite(AOK_Label, IDLoc,
1342 IDVal.size(), RewrittenLabel));
1343 IDVal = RewrittenLabel;
1345 Sym = getContext().getOrCreateSymbol(IDVal);
1347 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1349 Sym->redefineIfPossible();
1351 if (!Sym->isUndefined() || Sym->isVariable())
1352 return Error(IDLoc, "invalid symbol redefinition");
1355 if (!ParsingInlineAsm)
1358 // If we are generating dwarf for assembly source files then gather the
1359 // info to make a dwarf label entry for this label if needed.
1360 if (getContext().getGenDwarfForAssembly())
1361 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1364 getTargetParser().onLabelParsed(Sym);
1366 // Consume any end of statement token, if present, to avoid spurious
1367 // AddBlankLine calls().
1368 if (Lexer.is(AsmToken::EndOfStatement)) {
1370 if (Lexer.is(AsmToken::Eof))
1377 case AsmToken::Equal:
1378 // identifier '=' ... -> assignment statement
1381 return parseAssignment(IDVal, true);
1383 default: // Normal instruction or directive.
1387 // If macros are enabled, check to see if this is a macro instantiation.
1388 if (areMacrosEnabled())
1389 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1390 return handleMacroEntry(M, IDLoc);
1393 // Otherwise, we have a normal instruction or directive.
1395 // Directives start with "."
1396 if (IDVal[0] == '.' && IDVal != ".") {
1397 // There are several entities interested in parsing directives:
1399 // 1. The target-specific assembly parser. Some directives are target
1400 // specific or may potentially behave differently on certain targets.
1401 // 2. Asm parser extensions. For example, platform-specific parsers
1402 // (like the ELF parser) register themselves as extensions.
1403 // 3. The generic directive parser implemented by this class. These are
1404 // all the directives that behave in a target and platform independent
1405 // manner, or at least have a default behavior that's shared between
1406 // all targets and platforms.
1408 // First query the target-specific parser. It will return 'true' if it
1409 // isn't interested in this directive.
1410 if (!getTargetParser().ParseDirective(ID))
1413 // Next, check the extension directive map to see if any extension has
1414 // registered itself to parse this directive.
1415 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1416 ExtensionDirectiveMap.lookup(IDVal);
1418 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1420 // Finally, if no one else is interested in this directive, it must be
1421 // generic and familiar to this class.
1427 return parseDirectiveSet(IDVal, true);
1429 return parseDirectiveSet(IDVal, false);
1431 return parseDirectiveAscii(IDVal, false);
1434 return parseDirectiveAscii(IDVal, true);
1436 return parseDirectiveValue(1);
1440 return parseDirectiveValue(2);
1444 return parseDirectiveValue(4);
1447 return parseDirectiveValue(8);
1449 return parseDirectiveOctaValue();
1452 return parseDirectiveRealValue(APFloat::IEEEsingle);
1454 return parseDirectiveRealValue(APFloat::IEEEdouble);
1456 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1457 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1460 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1461 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1464 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1466 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1468 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1470 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1472 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1474 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1476 return parseDirectiveOrg();
1478 return parseDirectiveFill();
1480 return parseDirectiveZero();
1482 eatToEndOfStatement(); // .extern is the default, ignore it.
1486 return parseDirectiveSymbolAttribute(MCSA_Global);
1487 case DK_LAZY_REFERENCE:
1488 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1489 case DK_NO_DEAD_STRIP:
1490 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1491 case DK_SYMBOL_RESOLVER:
1492 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1493 case DK_PRIVATE_EXTERN:
1494 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1496 return parseDirectiveSymbolAttribute(MCSA_Reference);
1497 case DK_WEAK_DEFINITION:
1498 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1499 case DK_WEAK_REFERENCE:
1500 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1501 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1502 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1505 return parseDirectiveComm(/*IsLocal=*/false);
1507 return parseDirectiveComm(/*IsLocal=*/true);
1509 return parseDirectiveAbort();
1511 return parseDirectiveInclude();
1513 return parseDirectiveIncbin();
1516 return TokError(Twine(IDVal) + " not supported yet");
1518 return parseDirectiveRept(IDLoc, IDVal);
1520 return parseDirectiveIrp(IDLoc);
1522 return parseDirectiveIrpc(IDLoc);
1524 return parseDirectiveEndr(IDLoc);
1525 case DK_BUNDLE_ALIGN_MODE:
1526 return parseDirectiveBundleAlignMode();
1527 case DK_BUNDLE_LOCK:
1528 return parseDirectiveBundleLock();
1529 case DK_BUNDLE_UNLOCK:
1530 return parseDirectiveBundleUnlock();
1532 return parseDirectiveLEB128(true);
1534 return parseDirectiveLEB128(false);
1537 return parseDirectiveSpace(IDVal);
1539 return parseDirectiveFile(IDLoc);
1541 return parseDirectiveLine();
1543 return parseDirectiveLoc();
1545 return parseDirectiveStabs();
1546 case DK_CFI_SECTIONS:
1547 return parseDirectiveCFISections();
1548 case DK_CFI_STARTPROC:
1549 return parseDirectiveCFIStartProc();
1550 case DK_CFI_ENDPROC:
1551 return parseDirectiveCFIEndProc();
1552 case DK_CFI_DEF_CFA:
1553 return parseDirectiveCFIDefCfa(IDLoc);
1554 case DK_CFI_DEF_CFA_OFFSET:
1555 return parseDirectiveCFIDefCfaOffset();
1556 case DK_CFI_ADJUST_CFA_OFFSET:
1557 return parseDirectiveCFIAdjustCfaOffset();
1558 case DK_CFI_DEF_CFA_REGISTER:
1559 return parseDirectiveCFIDefCfaRegister(IDLoc);
1561 return parseDirectiveCFIOffset(IDLoc);
1562 case DK_CFI_REL_OFFSET:
1563 return parseDirectiveCFIRelOffset(IDLoc);
1564 case DK_CFI_PERSONALITY:
1565 return parseDirectiveCFIPersonalityOrLsda(true);
1567 return parseDirectiveCFIPersonalityOrLsda(false);
1568 case DK_CFI_REMEMBER_STATE:
1569 return parseDirectiveCFIRememberState();
1570 case DK_CFI_RESTORE_STATE:
1571 return parseDirectiveCFIRestoreState();
1572 case DK_CFI_SAME_VALUE:
1573 return parseDirectiveCFISameValue(IDLoc);
1574 case DK_CFI_RESTORE:
1575 return parseDirectiveCFIRestore(IDLoc);
1577 return parseDirectiveCFIEscape();
1578 case DK_CFI_SIGNAL_FRAME:
1579 return parseDirectiveCFISignalFrame();
1580 case DK_CFI_UNDEFINED:
1581 return parseDirectiveCFIUndefined(IDLoc);
1582 case DK_CFI_REGISTER:
1583 return parseDirectiveCFIRegister(IDLoc);
1584 case DK_CFI_WINDOW_SAVE:
1585 return parseDirectiveCFIWindowSave();
1588 return parseDirectiveMacrosOnOff(IDVal);
1590 return parseDirectiveMacro(IDLoc);
1592 return parseDirectiveExitMacro(IDVal);
1595 return parseDirectiveEndMacro(IDVal);
1597 return parseDirectivePurgeMacro(IDLoc);
1599 return parseDirectiveEnd(IDLoc);
1601 return parseDirectiveError(IDLoc, false);
1603 return parseDirectiveError(IDLoc, true);
1605 return parseDirectiveWarning(IDLoc);
1608 return Error(IDLoc, "unknown directive");
1611 // __asm _emit or __asm __emit
1612 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1613 IDVal == "_EMIT" || IDVal == "__EMIT"))
1614 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1617 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1618 return parseDirectiveMSAlign(IDLoc, Info);
1620 checkForValidSection();
1622 // Canonicalize the opcode to lower case.
1623 std::string OpcodeStr = IDVal.lower();
1624 ParseInstructionInfo IInfo(Info.AsmRewrites);
1625 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1626 Info.ParsedOperands);
1627 Info.ParseError = HadError;
1629 // Dump the parsed representation, if requested.
1630 if (getShowParsedOperands()) {
1631 SmallString<256> Str;
1632 raw_svector_ostream OS(Str);
1633 OS << "parsed instruction: [";
1634 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1637 Info.ParsedOperands[i]->print(OS);
1641 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1644 // If we are generating dwarf for the current section then generate a .loc
1645 // directive for the instruction.
1646 if (!HadError && getContext().getGenDwarfForAssembly() &&
1647 getContext().getGenDwarfSectionSyms().count(
1648 getStreamer().getCurrentSection().first)) {
1650 if (ActiveMacros.empty())
1651 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1653 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
1654 ActiveMacros.front()->ExitBuffer);
1656 // If we previously parsed a cpp hash file line comment then make sure the
1657 // current Dwarf File is for the CppHashFilename if not then emit the
1658 // Dwarf File table for it and adjust the line number for the .loc.
1659 if (CppHashFilename.size()) {
1660 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1661 0, StringRef(), CppHashFilename);
1662 getContext().setGenDwarfFileNumber(FileNumber);
1664 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1665 // cache with the different Loc from the call above we save the last
1666 // info we queried here with SrcMgr.FindLineNumber().
1667 unsigned CppHashLocLineNo;
1668 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1669 CppHashLocLineNo = LastQueryLine;
1671 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1672 LastQueryLine = CppHashLocLineNo;
1673 LastQueryIDLoc = CppHashLoc;
1674 LastQueryBuffer = CppHashBuf;
1676 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1679 getStreamer().EmitDwarfLocDirective(
1680 getContext().getGenDwarfFileNumber(), Line, 0,
1681 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1685 // If parsing succeeded, match the instruction.
1688 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1689 Info.ParsedOperands, Out,
1690 ErrorInfo, ParsingInlineAsm);
1693 // Don't skip the rest of the line, the instruction parser is responsible for
1698 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1699 /// since they may not be able to be tokenized to get to the end of line token.
1700 void AsmParser::eatToEndOfLine() {
1701 if (!Lexer.is(AsmToken::EndOfStatement))
1702 Lexer.LexUntilEndOfLine();
1707 /// parseCppHashLineFilenameComment as this:
1708 /// ::= # number "filename"
1709 /// or just as a full line comment if it doesn't have a number and a string.
1710 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1711 Lex(); // Eat the hash token.
1713 if (getLexer().isNot(AsmToken::Integer)) {
1714 // Consume the line since in cases it is not a well-formed line directive,
1715 // as if were simply a full line comment.
1720 int64_t LineNumber = getTok().getIntVal();
1723 if (getLexer().isNot(AsmToken::String)) {
1728 StringRef Filename = getTok().getString();
1729 // Get rid of the enclosing quotes.
1730 Filename = Filename.substr(1, Filename.size() - 2);
1732 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1734 CppHashFilename = Filename;
1735 CppHashLineNumber = LineNumber;
1736 CppHashBuf = CurBuffer;
1738 // Ignore any trailing characters, they're just comment.
1743 /// \brief will use the last parsed cpp hash line filename comment
1744 /// for the Filename and LineNo if any in the diagnostic.
1745 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1746 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1747 raw_ostream &OS = errs();
1749 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1750 const SMLoc &DiagLoc = Diag.getLoc();
1751 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1752 unsigned CppHashBuf =
1753 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1755 // Like SourceMgr::printMessage() we need to print the include stack if any
1756 // before printing the message.
1757 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1758 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1759 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
1760 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1761 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1764 // If we have not parsed a cpp hash line filename comment or the source
1765 // manager changed or buffer changed (like in a nested include) then just
1766 // print the normal diagnostic using its Filename and LineNo.
1767 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1768 DiagBuf != CppHashBuf) {
1769 if (Parser->SavedDiagHandler)
1770 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1772 Diag.print(nullptr, OS);
1776 // Use the CppHashFilename and calculate a line number based on the
1777 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1779 const std::string &Filename = Parser->CppHashFilename;
1781 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1782 int CppHashLocLineNo =
1783 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1785 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1787 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1788 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1789 Diag.getLineContents(), Diag.getRanges());
1791 if (Parser->SavedDiagHandler)
1792 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1794 NewDiag.print(nullptr, OS);
1797 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1798 // difference being that that function accepts '@' as part of identifiers and
1799 // we can't do that. AsmLexer.cpp should probably be changed to handle
1800 // '@' as a special case when needed.
1801 static bool isIdentifierChar(char c) {
1802 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1806 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1807 ArrayRef<MCAsmMacroParameter> Parameters,
1808 ArrayRef<MCAsmMacroArgument> A,
1809 bool EnableAtPseudoVariable, const SMLoc &L) {
1810 unsigned NParameters = Parameters.size();
1811 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1812 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1813 return Error(L, "Wrong number of arguments");
1815 // A macro without parameters is handled differently on Darwin:
1816 // gas accepts no arguments and does no substitutions
1817 while (!Body.empty()) {
1818 // Scan for the next substitution.
1819 std::size_t End = Body.size(), Pos = 0;
1820 for (; Pos != End; ++Pos) {
1821 // Check for a substitution or escape.
1822 if (IsDarwin && !NParameters) {
1823 // This macro has no parameters, look for $0, $1, etc.
1824 if (Body[Pos] != '$' || Pos + 1 == End)
1827 char Next = Body[Pos + 1];
1828 if (Next == '$' || Next == 'n' ||
1829 isdigit(static_cast<unsigned char>(Next)))
1832 // This macro has parameters, look for \foo, \bar, etc.
1833 if (Body[Pos] == '\\' && Pos + 1 != End)
1839 OS << Body.slice(0, Pos);
1841 // Check if we reached the end.
1845 if (IsDarwin && !NParameters) {
1846 switch (Body[Pos + 1]) {
1852 // $n => number of arguments
1857 // $[0-9] => argument
1859 // Missing arguments are ignored.
1860 unsigned Index = Body[Pos + 1] - '0';
1861 if (Index >= A.size())
1864 // Otherwise substitute with the token values, with spaces eliminated.
1865 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1866 ie = A[Index].end();
1868 OS << it->getString();
1874 unsigned I = Pos + 1;
1876 // Check for the \@ pseudo-variable.
1877 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
1880 while (isIdentifierChar(Body[I]) && I + 1 != End)
1883 const char *Begin = Body.data() + Pos + 1;
1884 StringRef Argument(Begin, I - (Pos + 1));
1887 if (Argument == "@") {
1888 OS << NumOfMacroInstantiations;
1891 for (; Index < NParameters; ++Index)
1892 if (Parameters[Index].Name == Argument)
1895 if (Index == NParameters) {
1896 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1899 OS << '\\' << Argument;
1903 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1904 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1905 ie = A[Index].end();
1907 // We expect no quotes around the string's contents when
1908 // parsing for varargs.
1909 if (it->getKind() != AsmToken::String || VarargParameter)
1910 OS << it->getString();
1912 OS << it->getStringContents();
1914 Pos += 1 + Argument.size();
1918 // Update the scan point.
1919 Body = Body.substr(Pos);
1925 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
1926 size_t CondStackDepth)
1927 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
1928 CondStackDepth(CondStackDepth) {}
1930 static bool isOperator(AsmToken::TokenKind kind) {
1934 case AsmToken::Plus:
1935 case AsmToken::Minus:
1936 case AsmToken::Tilde:
1937 case AsmToken::Slash:
1938 case AsmToken::Star:
1940 case AsmToken::Equal:
1941 case AsmToken::EqualEqual:
1942 case AsmToken::Pipe:
1943 case AsmToken::PipePipe:
1944 case AsmToken::Caret:
1946 case AsmToken::AmpAmp:
1947 case AsmToken::Exclaim:
1948 case AsmToken::ExclaimEqual:
1949 case AsmToken::Percent:
1950 case AsmToken::Less:
1951 case AsmToken::LessEqual:
1952 case AsmToken::LessLess:
1953 case AsmToken::LessGreater:
1954 case AsmToken::Greater:
1955 case AsmToken::GreaterEqual:
1956 case AsmToken::GreaterGreater:
1962 class AsmLexerSkipSpaceRAII {
1964 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1965 Lexer.setSkipSpace(SkipSpace);
1968 ~AsmLexerSkipSpaceRAII() {
1969 Lexer.setSkipSpace(true);
1977 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1980 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1981 StringRef Str = parseStringToEndOfStatement();
1982 MA.emplace_back(AsmToken::String, Str);
1987 unsigned ParenLevel = 0;
1988 unsigned AddTokens = 0;
1990 // Darwin doesn't use spaces to delmit arguments.
1991 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1994 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1995 return TokError("unexpected token in macro instantiation");
1997 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
2000 if (Lexer.is(AsmToken::Space)) {
2001 Lex(); // Eat spaces
2003 // Spaces can delimit parameters, but could also be part an expression.
2004 // If the token after a space is an operator, add the token and the next
2005 // one into this argument
2007 if (isOperator(Lexer.getKind())) {
2008 // Check to see whether the token is used as an operator,
2009 // or part of an identifier
2010 const char *NextChar = getTok().getEndLoc().getPointer();
2011 if (*NextChar == ' ')
2015 if (!AddTokens && ParenLevel == 0) {
2021 // handleMacroEntry relies on not advancing the lexer here
2022 // to be able to fill in the remaining default parameter values
2023 if (Lexer.is(AsmToken::EndOfStatement))
2026 // Adjust the current parentheses level.
2027 if (Lexer.is(AsmToken::LParen))
2029 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2032 // Append the token to the current argument list.
2033 MA.push_back(getTok());
2039 if (ParenLevel != 0)
2040 return TokError("unbalanced parentheses in macro argument");
2044 // Parse the macro instantiation arguments.
2045 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2046 MCAsmMacroArguments &A) {
2047 const unsigned NParameters = M ? M->Parameters.size() : 0;
2048 bool NamedParametersFound = false;
2049 SmallVector<SMLoc, 4> FALocs;
2051 A.resize(NParameters);
2052 FALocs.resize(NParameters);
2054 // Parse two kinds of macro invocations:
2055 // - macros defined without any parameters accept an arbitrary number of them
2056 // - macros defined with parameters accept at most that many of them
2057 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2058 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2060 SMLoc IDLoc = Lexer.getLoc();
2061 MCAsmMacroParameter FA;
2063 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2064 if (parseIdentifier(FA.Name)) {
2065 Error(IDLoc, "invalid argument identifier for formal argument");
2066 eatToEndOfStatement();
2070 if (!Lexer.is(AsmToken::Equal)) {
2071 TokError("expected '=' after formal parameter identifier");
2072 eatToEndOfStatement();
2077 NamedParametersFound = true;
2080 if (NamedParametersFound && FA.Name.empty()) {
2081 Error(IDLoc, "cannot mix positional and keyword arguments");
2082 eatToEndOfStatement();
2086 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2087 if (parseMacroArgument(FA.Value, Vararg))
2090 unsigned PI = Parameter;
2091 if (!FA.Name.empty()) {
2093 for (FAI = 0; FAI < NParameters; ++FAI)
2094 if (M->Parameters[FAI].Name == FA.Name)
2097 if (FAI >= NParameters) {
2098 assert(M && "expected macro to be defined");
2100 "parameter named '" + FA.Name + "' does not exist for macro '" +
2107 if (!FA.Value.empty()) {
2112 if (FALocs.size() <= PI)
2113 FALocs.resize(PI + 1);
2115 FALocs[PI] = Lexer.getLoc();
2118 // At the end of the statement, fill in remaining arguments that have
2119 // default values. If there aren't any, then the next argument is
2120 // required but missing
2121 if (Lexer.is(AsmToken::EndOfStatement)) {
2122 bool Failure = false;
2123 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2124 if (A[FAI].empty()) {
2125 if (M->Parameters[FAI].Required) {
2126 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2127 "missing value for required parameter "
2128 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2132 if (!M->Parameters[FAI].Value.empty())
2133 A[FAI] = M->Parameters[FAI].Value;
2139 if (Lexer.is(AsmToken::Comma))
2143 return TokError("too many positional arguments");
2146 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2147 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2148 return (I == MacroMap.end()) ? nullptr : &I->getValue();
2151 void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2152 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2155 void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2157 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2158 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2159 // this, although we should protect against infinite loops.
2160 if (ActiveMacros.size() == 20)
2161 return TokError("macros cannot be nested more than 20 levels deep");
2163 MCAsmMacroArguments A;
2164 if (parseMacroArguments(M, A))
2167 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2168 // to hold the macro body with substitutions.
2169 SmallString<256> Buf;
2170 StringRef Body = M->Body;
2171 raw_svector_ostream OS(Buf);
2173 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2176 // We include the .endmacro in the buffer as our cue to exit the macro
2178 OS << ".endmacro\n";
2180 std::unique_ptr<MemoryBuffer> Instantiation =
2181 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2183 // Create the macro instantiation object and add to the current macro
2184 // instantiation stack.
2185 MacroInstantiation *MI = new MacroInstantiation(
2186 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2187 ActiveMacros.push_back(MI);
2189 ++NumOfMacroInstantiations;
2191 // Jump to the macro instantiation and prime the lexer.
2192 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2193 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2199 void AsmParser::handleMacroExit() {
2200 // Jump to the EndOfStatement we should return to, and consume it.
2201 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2204 // Pop the instantiation entry.
2205 delete ActiveMacros.back();
2206 ActiveMacros.pop_back();
2209 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2212 const MCExpr *Value;
2213 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2218 // In the case where we parse an expression starting with a '.', we will
2219 // not generate an error, nor will we create a symbol. In this case we
2220 // should just return out.
2224 // Do the assignment.
2225 Out.EmitAssignment(Sym, Value);
2227 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2232 /// parseIdentifier:
2235 bool AsmParser::parseIdentifier(StringRef &Res) {
2236 // The assembler has relaxed rules for accepting identifiers, in particular we
2237 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2238 // separate tokens. At this level, we have already lexed so we cannot (currently)
2239 // handle this as a context dependent token, instead we detect adjacent tokens
2240 // and return the combined identifier.
2241 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2242 SMLoc PrefixLoc = getLexer().getLoc();
2244 // Consume the prefix character, and check for a following identifier.
2246 if (Lexer.isNot(AsmToken::Identifier))
2249 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2250 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2253 // Construct the joined identifier and consume the token.
2255 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2260 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2263 Res = getTok().getIdentifier();
2265 Lex(); // Consume the identifier token.
2270 /// parseDirectiveSet:
2271 /// ::= .equ identifier ',' expression
2272 /// ::= .equiv identifier ',' expression
2273 /// ::= .set identifier ',' expression
2274 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2277 if (parseIdentifier(Name))
2278 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2280 if (getLexer().isNot(AsmToken::Comma))
2281 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2284 return parseAssignment(Name, allow_redef, true);
2287 bool AsmParser::parseEscapedString(std::string &Data) {
2288 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2291 StringRef Str = getTok().getStringContents();
2292 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2293 if (Str[i] != '\\') {
2298 // Recognize escaped characters. Note that this escape semantics currently
2299 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2302 return TokError("unexpected backslash at end of string");
2304 // Recognize octal sequences.
2305 if ((unsigned)(Str[i] - '0') <= 7) {
2306 // Consume up to three octal characters.
2307 unsigned Value = Str[i] - '0';
2309 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2311 Value = Value * 8 + (Str[i] - '0');
2313 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2315 Value = Value * 8 + (Str[i] - '0');
2320 return TokError("invalid octal escape sequence (out of range)");
2322 Data += (unsigned char)Value;
2326 // Otherwise recognize individual escapes.
2329 // Just reject invalid escape sequences for now.
2330 return TokError("invalid escape sequence (unrecognized character)");
2332 case 'b': Data += '\b'; break;
2333 case 'f': Data += '\f'; break;
2334 case 'n': Data += '\n'; break;
2335 case 'r': Data += '\r'; break;
2336 case 't': Data += '\t'; break;
2337 case '"': Data += '"'; break;
2338 case '\\': Data += '\\'; break;
2345 /// parseDirectiveAscii:
2346 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2347 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2348 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2349 checkForValidSection();
2352 if (getLexer().isNot(AsmToken::String))
2353 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2356 if (parseEscapedString(Data))
2359 getStreamer().EmitBytes(Data);
2361 getStreamer().EmitBytes(StringRef("\0", 1));
2365 if (getLexer().is(AsmToken::EndOfStatement))
2368 if (getLexer().isNot(AsmToken::Comma))
2369 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2378 /// parseDirectiveValue
2379 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2380 bool AsmParser::parseDirectiveValue(unsigned Size) {
2381 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2382 checkForValidSection();
2385 const MCExpr *Value;
2386 SMLoc ExprLoc = getLexer().getLoc();
2387 if (parseExpression(Value))
2390 // Special case constant expressions to match code generator.
2391 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2392 assert(Size <= 8 && "Invalid size");
2393 uint64_t IntValue = MCE->getValue();
2394 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2395 return Error(ExprLoc, "literal value out of range for directive");
2396 getStreamer().EmitIntValue(IntValue, Size);
2398 getStreamer().EmitValue(Value, Size, ExprLoc);
2400 if (getLexer().is(AsmToken::EndOfStatement))
2403 // FIXME: Improve diagnostic.
2404 if (getLexer().isNot(AsmToken::Comma))
2405 return TokError("unexpected token in directive");
2414 /// ParseDirectiveOctaValue
2415 /// ::= .octa [ hexconstant (, hexconstant)* ]
2416 bool AsmParser::parseDirectiveOctaValue() {
2417 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2418 checkForValidSection();
2421 if (Lexer.getKind() == AsmToken::Error)
2423 if (Lexer.getKind() != AsmToken::Integer &&
2424 Lexer.getKind() != AsmToken::BigNum)
2425 return TokError("unknown token in expression");
2427 SMLoc ExprLoc = getLexer().getLoc();
2428 APInt IntValue = getTok().getAPIntVal();
2432 if (IntValue.isIntN(64)) {
2434 lo = IntValue.getZExtValue();
2435 } else if (IntValue.isIntN(128)) {
2436 // It might actually have more than 128 bits, but the top ones are zero.
2437 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2438 lo = IntValue.getLoBits(64).getZExtValue();
2440 return Error(ExprLoc, "literal value out of range for directive");
2442 if (MAI.isLittleEndian()) {
2443 getStreamer().EmitIntValue(lo, 8);
2444 getStreamer().EmitIntValue(hi, 8);
2446 getStreamer().EmitIntValue(hi, 8);
2447 getStreamer().EmitIntValue(lo, 8);
2450 if (getLexer().is(AsmToken::EndOfStatement))
2453 // FIXME: Improve diagnostic.
2454 if (getLexer().isNot(AsmToken::Comma))
2455 return TokError("unexpected token in directive");
2464 /// parseDirectiveRealValue
2465 /// ::= (.single | .double) [ expression (, expression)* ]
2466 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2467 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2468 checkForValidSection();
2471 // We don't truly support arithmetic on floating point expressions, so we
2472 // have to manually parse unary prefixes.
2474 if (getLexer().is(AsmToken::Minus)) {
2477 } else if (getLexer().is(AsmToken::Plus))
2480 if (getLexer().isNot(AsmToken::Integer) &&
2481 getLexer().isNot(AsmToken::Real) &&
2482 getLexer().isNot(AsmToken::Identifier))
2483 return TokError("unexpected token in directive");
2485 // Convert to an APFloat.
2486 APFloat Value(Semantics);
2487 StringRef IDVal = getTok().getString();
2488 if (getLexer().is(AsmToken::Identifier)) {
2489 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2490 Value = APFloat::getInf(Semantics);
2491 else if (!IDVal.compare_lower("nan"))
2492 Value = APFloat::getNaN(Semantics, false, ~0);
2494 return TokError("invalid floating point literal");
2495 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2496 APFloat::opInvalidOp)
2497 return TokError("invalid floating point literal");
2501 // Consume the numeric token.
2504 // Emit the value as an integer.
2505 APInt AsInt = Value.bitcastToAPInt();
2506 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2507 AsInt.getBitWidth() / 8);
2509 if (getLexer().is(AsmToken::EndOfStatement))
2512 if (getLexer().isNot(AsmToken::Comma))
2513 return TokError("unexpected token in directive");
2522 /// parseDirectiveZero
2523 /// ::= .zero expression
2524 bool AsmParser::parseDirectiveZero() {
2525 checkForValidSection();
2528 if (parseAbsoluteExpression(NumBytes))
2532 if (getLexer().is(AsmToken::Comma)) {
2534 if (parseAbsoluteExpression(Val))
2538 if (getLexer().isNot(AsmToken::EndOfStatement))
2539 return TokError("unexpected token in '.zero' directive");
2543 getStreamer().EmitFill(NumBytes, Val);
2548 /// parseDirectiveFill
2549 /// ::= .fill expression [ , expression [ , expression ] ]
2550 bool AsmParser::parseDirectiveFill() {
2551 checkForValidSection();
2553 SMLoc RepeatLoc = getLexer().getLoc();
2555 if (parseAbsoluteExpression(NumValues))
2558 if (NumValues < 0) {
2560 "'.fill' directive with negative repeat count has no effect");
2564 int64_t FillSize = 1;
2565 int64_t FillExpr = 0;
2567 SMLoc SizeLoc, ExprLoc;
2568 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2569 if (getLexer().isNot(AsmToken::Comma))
2570 return TokError("unexpected token in '.fill' directive");
2573 SizeLoc = getLexer().getLoc();
2574 if (parseAbsoluteExpression(FillSize))
2577 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2578 if (getLexer().isNot(AsmToken::Comma))
2579 return TokError("unexpected token in '.fill' directive");
2582 ExprLoc = getLexer().getLoc();
2583 if (parseAbsoluteExpression(FillExpr))
2586 if (getLexer().isNot(AsmToken::EndOfStatement))
2587 return TokError("unexpected token in '.fill' directive");
2594 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2598 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2602 if (!isUInt<32>(FillExpr) && FillSize > 4)
2603 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2605 if (NumValues > 0) {
2606 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2607 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2608 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2609 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2610 if (NonZeroFillSize < FillSize)
2611 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2618 /// parseDirectiveOrg
2619 /// ::= .org expression [ , expression ]
2620 bool AsmParser::parseDirectiveOrg() {
2621 checkForValidSection();
2623 const MCExpr *Offset;
2624 SMLoc Loc = getTok().getLoc();
2625 if (parseExpression(Offset))
2628 // Parse optional fill expression.
2629 int64_t FillExpr = 0;
2630 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2631 if (getLexer().isNot(AsmToken::Comma))
2632 return TokError("unexpected token in '.org' directive");
2635 if (parseAbsoluteExpression(FillExpr))
2638 if (getLexer().isNot(AsmToken::EndOfStatement))
2639 return TokError("unexpected token in '.org' directive");
2644 // Only limited forms of relocatable expressions are accepted here, it
2645 // has to be relative to the current section. The streamer will return
2646 // 'true' if the expression wasn't evaluatable.
2647 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2648 return Error(Loc, "expected assembly-time absolute expression");
2653 /// parseDirectiveAlign
2654 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2655 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2656 checkForValidSection();
2658 SMLoc AlignmentLoc = getLexer().getLoc();
2660 if (parseAbsoluteExpression(Alignment))
2664 bool HasFillExpr = false;
2665 int64_t FillExpr = 0;
2666 int64_t MaxBytesToFill = 0;
2667 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2668 if (getLexer().isNot(AsmToken::Comma))
2669 return TokError("unexpected token in directive");
2672 // The fill expression can be omitted while specifying a maximum number of
2673 // alignment bytes, e.g:
2675 if (getLexer().isNot(AsmToken::Comma)) {
2677 if (parseAbsoluteExpression(FillExpr))
2681 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2682 if (getLexer().isNot(AsmToken::Comma))
2683 return TokError("unexpected token in directive");
2686 MaxBytesLoc = getLexer().getLoc();
2687 if (parseAbsoluteExpression(MaxBytesToFill))
2690 if (getLexer().isNot(AsmToken::EndOfStatement))
2691 return TokError("unexpected token in directive");
2700 // Compute alignment in bytes.
2702 // FIXME: Diagnose overflow.
2703 if (Alignment >= 32) {
2704 Error(AlignmentLoc, "invalid alignment value");
2708 Alignment = 1ULL << Alignment;
2710 // Reject alignments that aren't a power of two, for gas compatibility.
2711 if (!isPowerOf2_64(Alignment))
2712 Error(AlignmentLoc, "alignment must be a power of 2");
2715 // Diagnose non-sensical max bytes to align.
2716 if (MaxBytesLoc.isValid()) {
2717 if (MaxBytesToFill < 1) {
2718 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2719 "many bytes, ignoring maximum bytes expression");
2723 if (MaxBytesToFill >= Alignment) {
2724 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2730 // Check whether we should use optimal code alignment for this .align
2732 const MCSection *Section = getStreamer().getCurrentSection().first;
2733 assert(Section && "must have section to emit alignment");
2734 bool UseCodeAlign = Section->UseCodeAlign();
2735 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2736 ValueSize == 1 && UseCodeAlign) {
2737 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2739 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2740 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2747 /// parseDirectiveFile
2748 /// ::= .file [number] filename
2749 /// ::= .file number directory filename
2750 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2751 // FIXME: I'm not sure what this is.
2752 int64_t FileNumber = -1;
2753 SMLoc FileNumberLoc = getLexer().getLoc();
2754 if (getLexer().is(AsmToken::Integer)) {
2755 FileNumber = getTok().getIntVal();
2759 return TokError("file number less than one");
2762 if (getLexer().isNot(AsmToken::String))
2763 return TokError("unexpected token in '.file' directive");
2765 // Usually the directory and filename together, otherwise just the directory.
2766 // Allow the strings to have escaped octal character sequence.
2767 std::string Path = getTok().getString();
2768 if (parseEscapedString(Path))
2772 StringRef Directory;
2774 std::string FilenameData;
2775 if (getLexer().is(AsmToken::String)) {
2776 if (FileNumber == -1)
2777 return TokError("explicit path specified, but no file number");
2778 if (parseEscapedString(FilenameData))
2780 Filename = FilenameData;
2787 if (getLexer().isNot(AsmToken::EndOfStatement))
2788 return TokError("unexpected token in '.file' directive");
2790 if (FileNumber == -1)
2791 getStreamer().EmitFileDirective(Filename);
2793 if (getContext().getGenDwarfForAssembly())
2795 "input can't have .file dwarf directives when -g is "
2796 "used to generate dwarf debug info for assembly code");
2798 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2800 Error(FileNumberLoc, "file number already allocated");
2806 /// parseDirectiveLine
2807 /// ::= .line [number]
2808 bool AsmParser::parseDirectiveLine() {
2809 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2810 if (getLexer().isNot(AsmToken::Integer))
2811 return TokError("unexpected token in '.line' directive");
2813 int64_t LineNumber = getTok().getIntVal();
2817 // FIXME: Do something with the .line.
2820 if (getLexer().isNot(AsmToken::EndOfStatement))
2821 return TokError("unexpected token in '.line' directive");
2826 /// parseDirectiveLoc
2827 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2828 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2829 /// The first number is a file number, must have been previously assigned with
2830 /// a .file directive, the second number is the line number and optionally the
2831 /// third number is a column position (zero if not specified). The remaining
2832 /// optional items are .loc sub-directives.
2833 bool AsmParser::parseDirectiveLoc() {
2834 if (getLexer().isNot(AsmToken::Integer))
2835 return TokError("unexpected token in '.loc' directive");
2836 int64_t FileNumber = getTok().getIntVal();
2838 return TokError("file number less than one in '.loc' directive");
2839 if (!getContext().isValidDwarfFileNumber(FileNumber))
2840 return TokError("unassigned file number in '.loc' directive");
2843 int64_t LineNumber = 0;
2844 if (getLexer().is(AsmToken::Integer)) {
2845 LineNumber = getTok().getIntVal();
2847 return TokError("line number less than zero in '.loc' directive");
2851 int64_t ColumnPos = 0;
2852 if (getLexer().is(AsmToken::Integer)) {
2853 ColumnPos = getTok().getIntVal();
2855 return TokError("column position less than zero in '.loc' directive");
2859 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2861 int64_t Discriminator = 0;
2862 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2864 if (getLexer().is(AsmToken::EndOfStatement))
2868 SMLoc Loc = getTok().getLoc();
2869 if (parseIdentifier(Name))
2870 return TokError("unexpected token in '.loc' directive");
2872 if (Name == "basic_block")
2873 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2874 else if (Name == "prologue_end")
2875 Flags |= DWARF2_FLAG_PROLOGUE_END;
2876 else if (Name == "epilogue_begin")
2877 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2878 else if (Name == "is_stmt") {
2879 Loc = getTok().getLoc();
2880 const MCExpr *Value;
2881 if (parseExpression(Value))
2883 // The expression must be the constant 0 or 1.
2884 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2885 int Value = MCE->getValue();
2887 Flags &= ~DWARF2_FLAG_IS_STMT;
2888 else if (Value == 1)
2889 Flags |= DWARF2_FLAG_IS_STMT;
2891 return Error(Loc, "is_stmt value not 0 or 1");
2893 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2895 } else if (Name == "isa") {
2896 Loc = getTok().getLoc();
2897 const MCExpr *Value;
2898 if (parseExpression(Value))
2900 // The expression must be a constant greater or equal to 0.
2901 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2902 int Value = MCE->getValue();
2904 return Error(Loc, "isa number less than zero");
2907 return Error(Loc, "isa number not a constant value");
2909 } else if (Name == "discriminator") {
2910 if (parseAbsoluteExpression(Discriminator))
2913 return Error(Loc, "unknown sub-directive in '.loc' directive");
2916 if (getLexer().is(AsmToken::EndOfStatement))
2921 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2922 Isa, Discriminator, StringRef());
2927 /// parseDirectiveStabs
2928 /// ::= .stabs string, number, number, number
2929 bool AsmParser::parseDirectiveStabs() {
2930 return TokError("unsupported directive '.stabs'");
2933 /// parseDirectiveCFISections
2934 /// ::= .cfi_sections section [, section]
2935 bool AsmParser::parseDirectiveCFISections() {
2940 if (parseIdentifier(Name))
2941 return TokError("Expected an identifier");
2943 if (Name == ".eh_frame")
2945 else if (Name == ".debug_frame")
2948 if (getLexer().is(AsmToken::Comma)) {
2951 if (parseIdentifier(Name))
2952 return TokError("Expected an identifier");
2954 if (Name == ".eh_frame")
2956 else if (Name == ".debug_frame")
2960 getStreamer().EmitCFISections(EH, Debug);
2964 /// parseDirectiveCFIStartProc
2965 /// ::= .cfi_startproc [simple]
2966 bool AsmParser::parseDirectiveCFIStartProc() {
2968 if (getLexer().isNot(AsmToken::EndOfStatement))
2969 if (parseIdentifier(Simple) || Simple != "simple")
2970 return TokError("unexpected token in .cfi_startproc directive");
2972 getStreamer().EmitCFIStartProc(!Simple.empty());
2976 /// parseDirectiveCFIEndProc
2977 /// ::= .cfi_endproc
2978 bool AsmParser::parseDirectiveCFIEndProc() {
2979 getStreamer().EmitCFIEndProc();
2983 /// \brief parse register name or number.
2984 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2985 SMLoc DirectiveLoc) {
2988 if (getLexer().isNot(AsmToken::Integer)) {
2989 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2991 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2993 return parseAbsoluteExpression(Register);
2998 /// parseDirectiveCFIDefCfa
2999 /// ::= .cfi_def_cfa register, offset
3000 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3001 int64_t Register = 0;
3002 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3005 if (getLexer().isNot(AsmToken::Comma))
3006 return TokError("unexpected token in directive");
3010 if (parseAbsoluteExpression(Offset))
3013 getStreamer().EmitCFIDefCfa(Register, Offset);
3017 /// parseDirectiveCFIDefCfaOffset
3018 /// ::= .cfi_def_cfa_offset offset
3019 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3021 if (parseAbsoluteExpression(Offset))
3024 getStreamer().EmitCFIDefCfaOffset(Offset);
3028 /// parseDirectiveCFIRegister
3029 /// ::= .cfi_register register, register
3030 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3031 int64_t Register1 = 0;
3032 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3035 if (getLexer().isNot(AsmToken::Comma))
3036 return TokError("unexpected token in directive");
3039 int64_t Register2 = 0;
3040 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3043 getStreamer().EmitCFIRegister(Register1, Register2);
3047 /// parseDirectiveCFIWindowSave
3048 /// ::= .cfi_window_save
3049 bool AsmParser::parseDirectiveCFIWindowSave() {
3050 getStreamer().EmitCFIWindowSave();
3054 /// parseDirectiveCFIAdjustCfaOffset
3055 /// ::= .cfi_adjust_cfa_offset adjustment
3056 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3057 int64_t Adjustment = 0;
3058 if (parseAbsoluteExpression(Adjustment))
3061 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3065 /// parseDirectiveCFIDefCfaRegister
3066 /// ::= .cfi_def_cfa_register register
3067 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3068 int64_t Register = 0;
3069 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3072 getStreamer().EmitCFIDefCfaRegister(Register);
3076 /// parseDirectiveCFIOffset
3077 /// ::= .cfi_offset register, offset
3078 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3079 int64_t Register = 0;
3082 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3085 if (getLexer().isNot(AsmToken::Comma))
3086 return TokError("unexpected token in directive");
3089 if (parseAbsoluteExpression(Offset))
3092 getStreamer().EmitCFIOffset(Register, Offset);
3096 /// parseDirectiveCFIRelOffset
3097 /// ::= .cfi_rel_offset register, offset
3098 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3099 int64_t Register = 0;
3101 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3104 if (getLexer().isNot(AsmToken::Comma))
3105 return TokError("unexpected token in directive");
3109 if (parseAbsoluteExpression(Offset))
3112 getStreamer().EmitCFIRelOffset(Register, Offset);
3116 static bool isValidEncoding(int64_t Encoding) {
3117 if (Encoding & ~0xff)
3120 if (Encoding == dwarf::DW_EH_PE_omit)
3123 const unsigned Format = Encoding & 0xf;
3124 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3125 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3126 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3127 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3130 const unsigned Application = Encoding & 0x70;
3131 if (Application != dwarf::DW_EH_PE_absptr &&
3132 Application != dwarf::DW_EH_PE_pcrel)
3138 /// parseDirectiveCFIPersonalityOrLsda
3139 /// IsPersonality true for cfi_personality, false for cfi_lsda
3140 /// ::= .cfi_personality encoding, [symbol_name]
3141 /// ::= .cfi_lsda encoding, [symbol_name]
3142 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3143 int64_t Encoding = 0;
3144 if (parseAbsoluteExpression(Encoding))
3146 if (Encoding == dwarf::DW_EH_PE_omit)
3149 if (!isValidEncoding(Encoding))
3150 return TokError("unsupported encoding.");
3152 if (getLexer().isNot(AsmToken::Comma))
3153 return TokError("unexpected token in directive");
3157 if (parseIdentifier(Name))
3158 return TokError("expected identifier in directive");
3160 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3163 getStreamer().EmitCFIPersonality(Sym, Encoding);
3165 getStreamer().EmitCFILsda(Sym, Encoding);
3169 /// parseDirectiveCFIRememberState
3170 /// ::= .cfi_remember_state
3171 bool AsmParser::parseDirectiveCFIRememberState() {
3172 getStreamer().EmitCFIRememberState();
3176 /// parseDirectiveCFIRestoreState
3177 /// ::= .cfi_remember_state
3178 bool AsmParser::parseDirectiveCFIRestoreState() {
3179 getStreamer().EmitCFIRestoreState();
3183 /// parseDirectiveCFISameValue
3184 /// ::= .cfi_same_value register
3185 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3186 int64_t Register = 0;
3188 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3191 getStreamer().EmitCFISameValue(Register);
3195 /// parseDirectiveCFIRestore
3196 /// ::= .cfi_restore register
3197 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3198 int64_t Register = 0;
3199 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3202 getStreamer().EmitCFIRestore(Register);
3206 /// parseDirectiveCFIEscape
3207 /// ::= .cfi_escape expression[,...]
3208 bool AsmParser::parseDirectiveCFIEscape() {
3211 if (parseAbsoluteExpression(CurrValue))
3214 Values.push_back((uint8_t)CurrValue);
3216 while (getLexer().is(AsmToken::Comma)) {
3219 if (parseAbsoluteExpression(CurrValue))
3222 Values.push_back((uint8_t)CurrValue);
3225 getStreamer().EmitCFIEscape(Values);
3229 /// parseDirectiveCFISignalFrame
3230 /// ::= .cfi_signal_frame
3231 bool AsmParser::parseDirectiveCFISignalFrame() {
3232 if (getLexer().isNot(AsmToken::EndOfStatement))
3233 return Error(getLexer().getLoc(),
3234 "unexpected token in '.cfi_signal_frame'");
3236 getStreamer().EmitCFISignalFrame();
3240 /// parseDirectiveCFIUndefined
3241 /// ::= .cfi_undefined register
3242 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3243 int64_t Register = 0;
3245 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3248 getStreamer().EmitCFIUndefined(Register);
3252 /// parseDirectiveMacrosOnOff
3255 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3256 if (getLexer().isNot(AsmToken::EndOfStatement))
3257 return Error(getLexer().getLoc(),
3258 "unexpected token in '" + Directive + "' directive");
3260 setMacrosEnabled(Directive == ".macros_on");
3264 /// parseDirectiveMacro
3265 /// ::= .macro name[,] [parameters]
3266 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3268 if (parseIdentifier(Name))
3269 return TokError("expected identifier in '.macro' directive");
3271 if (getLexer().is(AsmToken::Comma))
3274 MCAsmMacroParameters Parameters;
3275 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3277 if (!Parameters.empty() && Parameters.back().Vararg)
3278 return Error(Lexer.getLoc(),
3279 "Vararg parameter '" + Parameters.back().Name +
3280 "' should be last one in the list of parameters.");
3282 MCAsmMacroParameter Parameter;
3283 if (parseIdentifier(Parameter.Name))
3284 return TokError("expected identifier in '.macro' directive");
3286 if (Lexer.is(AsmToken::Colon)) {
3287 Lex(); // consume ':'
3290 StringRef Qualifier;
3292 QualLoc = Lexer.getLoc();
3293 if (parseIdentifier(Qualifier))
3294 return Error(QualLoc, "missing parameter qualifier for "
3295 "'" + Parameter.Name + "' in macro '" + Name + "'");
3297 if (Qualifier == "req")
3298 Parameter.Required = true;
3299 else if (Qualifier == "vararg")
3300 Parameter.Vararg = true;
3302 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3303 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3306 if (getLexer().is(AsmToken::Equal)) {
3311 ParamLoc = Lexer.getLoc();
3312 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3315 if (Parameter.Required)
3316 Warning(ParamLoc, "pointless default value for required parameter "
3317 "'" + Parameter.Name + "' in macro '" + Name + "'");
3320 Parameters.push_back(std::move(Parameter));
3322 if (getLexer().is(AsmToken::Comma))
3326 // Eat the end of statement.
3329 AsmToken EndToken, StartToken = getTok();
3330 unsigned MacroDepth = 0;
3332 // Lex the macro definition.
3334 // Check whether we have reached the end of the file.
3335 if (getLexer().is(AsmToken::Eof))
3336 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3338 // Otherwise, check whether we have reach the .endmacro.
3339 if (getLexer().is(AsmToken::Identifier)) {
3340 if (getTok().getIdentifier() == ".endm" ||
3341 getTok().getIdentifier() == ".endmacro") {
3342 if (MacroDepth == 0) { // Outermost macro.
3343 EndToken = getTok();
3345 if (getLexer().isNot(AsmToken::EndOfStatement))
3346 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3350 // Otherwise we just found the end of an inner macro.
3353 } else if (getTok().getIdentifier() == ".macro") {
3354 // We allow nested macros. Those aren't instantiated until the outermost
3355 // macro is expanded so just ignore them for now.
3360 // Otherwise, scan til the end of the statement.
3361 eatToEndOfStatement();
3364 if (lookupMacro(Name)) {
3365 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3368 const char *BodyStart = StartToken.getLoc().getPointer();
3369 const char *BodyEnd = EndToken.getLoc().getPointer();
3370 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3371 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3372 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
3376 /// checkForBadMacro
3378 /// With the support added for named parameters there may be code out there that
3379 /// is transitioning from positional parameters. In versions of gas that did
3380 /// not support named parameters they would be ignored on the macro definition.
3381 /// But to support both styles of parameters this is not possible so if a macro
3382 /// definition has named parameters but does not use them and has what appears
3383 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3384 /// warning that the positional parameter found in body which have no effect.
3385 /// Hoping the developer will either remove the named parameters from the macro
3386 /// definition so the positional parameters get used if that was what was
3387 /// intended or change the macro to use the named parameters. It is possible
3388 /// this warning will trigger when the none of the named parameters are used
3389 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3390 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3392 ArrayRef<MCAsmMacroParameter> Parameters) {
3393 // If this macro is not defined with named parameters the warning we are
3394 // checking for here doesn't apply.
3395 unsigned NParameters = Parameters.size();
3396 if (NParameters == 0)
3399 bool NamedParametersFound = false;
3400 bool PositionalParametersFound = false;
3402 // Look at the body of the macro for use of both the named parameters and what
3403 // are likely to be positional parameters. This is what expandMacro() is
3404 // doing when it finds the parameters in the body.
3405 while (!Body.empty()) {
3406 // Scan for the next possible parameter.
3407 std::size_t End = Body.size(), Pos = 0;
3408 for (; Pos != End; ++Pos) {
3409 // Check for a substitution or escape.
3410 // This macro is defined with parameters, look for \foo, \bar, etc.
3411 if (Body[Pos] == '\\' && Pos + 1 != End)
3414 // This macro should have parameters, but look for $0, $1, ..., $n too.
3415 if (Body[Pos] != '$' || Pos + 1 == End)
3417 char Next = Body[Pos + 1];
3418 if (Next == '$' || Next == 'n' ||
3419 isdigit(static_cast<unsigned char>(Next)))
3423 // Check if we reached the end.
3427 if (Body[Pos] == '$') {
3428 switch (Body[Pos + 1]) {
3433 // $n => number of arguments
3435 PositionalParametersFound = true;
3438 // $[0-9] => argument
3440 PositionalParametersFound = true;
3446 unsigned I = Pos + 1;
3447 while (isIdentifierChar(Body[I]) && I + 1 != End)
3450 const char *Begin = Body.data() + Pos + 1;
3451 StringRef Argument(Begin, I - (Pos + 1));
3453 for (; Index < NParameters; ++Index)
3454 if (Parameters[Index].Name == Argument)
3457 if (Index == NParameters) {
3458 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3464 NamedParametersFound = true;
3465 Pos += 1 + Argument.size();
3468 // Update the scan point.
3469 Body = Body.substr(Pos);
3472 if (!NamedParametersFound && PositionalParametersFound)
3473 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3474 "used in macro body, possible positional parameter "
3475 "found in body which will have no effect");
3478 /// parseDirectiveExitMacro
3480 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3481 if (getLexer().isNot(AsmToken::EndOfStatement))
3482 return TokError("unexpected token in '" + Directive + "' directive");
3484 if (!isInsideMacroInstantiation())
3485 return TokError("unexpected '" + Directive + "' in file, "
3486 "no current macro definition");
3488 // Exit all conditionals that are active in the current macro.
3489 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3490 TheCondState = TheCondStack.back();
3491 TheCondStack.pop_back();
3498 /// parseDirectiveEndMacro
3501 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3502 if (getLexer().isNot(AsmToken::EndOfStatement))
3503 return TokError("unexpected token in '" + Directive + "' directive");
3505 // If we are inside a macro instantiation, terminate the current
3507 if (isInsideMacroInstantiation()) {
3512 // Otherwise, this .endmacro is a stray entry in the file; well formed
3513 // .endmacro directives are handled during the macro definition parsing.
3514 return TokError("unexpected '" + Directive + "' in file, "
3515 "no current macro definition");
3518 /// parseDirectivePurgeMacro
3520 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3522 if (parseIdentifier(Name))
3523 return TokError("expected identifier in '.purgem' directive");
3525 if (getLexer().isNot(AsmToken::EndOfStatement))
3526 return TokError("unexpected token in '.purgem' directive");
3528 if (!lookupMacro(Name))
3529 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3531 undefineMacro(Name);
3535 /// parseDirectiveBundleAlignMode
3536 /// ::= {.bundle_align_mode} expression
3537 bool AsmParser::parseDirectiveBundleAlignMode() {
3538 checkForValidSection();
3540 // Expect a single argument: an expression that evaluates to a constant
3541 // in the inclusive range 0-30.
3542 SMLoc ExprLoc = getLexer().getLoc();
3543 int64_t AlignSizePow2;
3544 if (parseAbsoluteExpression(AlignSizePow2))
3546 else if (getLexer().isNot(AsmToken::EndOfStatement))
3547 return TokError("unexpected token after expression in"
3548 " '.bundle_align_mode' directive");
3549 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3550 return Error(ExprLoc,
3551 "invalid bundle alignment size (expected between 0 and 30)");
3555 // Because of AlignSizePow2's verified range we can safely truncate it to
3557 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3561 /// parseDirectiveBundleLock
3562 /// ::= {.bundle_lock} [align_to_end]
3563 bool AsmParser::parseDirectiveBundleLock() {
3564 checkForValidSection();
3565 bool AlignToEnd = false;
3567 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3569 SMLoc Loc = getTok().getLoc();
3570 const char *kInvalidOptionError =
3571 "invalid option for '.bundle_lock' directive";
3573 if (parseIdentifier(Option))
3574 return Error(Loc, kInvalidOptionError);
3576 if (Option != "align_to_end")
3577 return Error(Loc, kInvalidOptionError);
3578 else if (getLexer().isNot(AsmToken::EndOfStatement))
3580 "unexpected token after '.bundle_lock' directive option");
3586 getStreamer().EmitBundleLock(AlignToEnd);
3590 /// parseDirectiveBundleLock
3591 /// ::= {.bundle_lock}
3592 bool AsmParser::parseDirectiveBundleUnlock() {
3593 checkForValidSection();
3595 if (getLexer().isNot(AsmToken::EndOfStatement))
3596 return TokError("unexpected token in '.bundle_unlock' directive");
3599 getStreamer().EmitBundleUnlock();
3603 /// parseDirectiveSpace
3604 /// ::= (.skip | .space) expression [ , expression ]
3605 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3606 checkForValidSection();
3609 if (parseAbsoluteExpression(NumBytes))
3612 int64_t FillExpr = 0;
3613 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3614 if (getLexer().isNot(AsmToken::Comma))
3615 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3618 if (parseAbsoluteExpression(FillExpr))
3621 if (getLexer().isNot(AsmToken::EndOfStatement))
3622 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3628 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3631 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3632 getStreamer().EmitFill(NumBytes, FillExpr);
3637 /// parseDirectiveLEB128
3638 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
3639 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3640 checkForValidSection();
3641 const MCExpr *Value;
3644 if (parseExpression(Value))
3648 getStreamer().EmitSLEB128Value(Value);
3650 getStreamer().EmitULEB128Value(Value);
3652 if (getLexer().is(AsmToken::EndOfStatement))
3655 if (getLexer().isNot(AsmToken::Comma))
3656 return TokError("unexpected token in directive");
3663 /// parseDirectiveSymbolAttribute
3664 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3665 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3666 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3669 SMLoc Loc = getTok().getLoc();
3671 if (parseIdentifier(Name))
3672 return Error(Loc, "expected identifier in directive");
3674 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3676 // Assembler local symbols don't make any sense here. Complain loudly.
3677 if (Sym->isTemporary())
3678 return Error(Loc, "non-local symbol required in directive");
3680 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3681 return Error(Loc, "unable to emit symbol attribute");
3683 if (getLexer().is(AsmToken::EndOfStatement))
3686 if (getLexer().isNot(AsmToken::Comma))
3687 return TokError("unexpected token in directive");
3696 /// parseDirectiveComm
3697 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3698 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3699 checkForValidSection();
3701 SMLoc IDLoc = getLexer().getLoc();
3703 if (parseIdentifier(Name))
3704 return TokError("expected identifier in directive");
3706 // Handle the identifier as the key symbol.
3707 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3709 if (getLexer().isNot(AsmToken::Comma))
3710 return TokError("unexpected token in directive");
3714 SMLoc SizeLoc = getLexer().getLoc();
3715 if (parseAbsoluteExpression(Size))
3718 int64_t Pow2Alignment = 0;
3719 SMLoc Pow2AlignmentLoc;
3720 if (getLexer().is(AsmToken::Comma)) {
3722 Pow2AlignmentLoc = getLexer().getLoc();
3723 if (parseAbsoluteExpression(Pow2Alignment))
3726 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3727 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3728 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3730 // If this target takes alignments in bytes (not log) validate and convert.
3731 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3732 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3733 if (!isPowerOf2_64(Pow2Alignment))
3734 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3735 Pow2Alignment = Log2_64(Pow2Alignment);
3739 if (getLexer().isNot(AsmToken::EndOfStatement))
3740 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3744 // NOTE: a size of zero for a .comm should create a undefined symbol
3745 // but a size of .lcomm creates a bss symbol of size zero.
3747 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3748 "be less than zero");
3750 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3751 // may internally end up wanting an alignment in bytes.
3752 // FIXME: Diagnose overflow.
3753 if (Pow2Alignment < 0)
3754 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3755 "alignment, can't be less than zero");
3757 if (!Sym->isUndefined())
3758 return Error(IDLoc, "invalid symbol redefinition");
3760 // Create the Symbol as a common or local common with Size and Pow2Alignment
3762 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3766 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3770 /// parseDirectiveAbort
3771 /// ::= .abort [... message ...]
3772 bool AsmParser::parseDirectiveAbort() {
3773 // FIXME: Use loc from directive.
3774 SMLoc Loc = getLexer().getLoc();
3776 StringRef Str = parseStringToEndOfStatement();
3777 if (getLexer().isNot(AsmToken::EndOfStatement))
3778 return TokError("unexpected token in '.abort' directive");
3783 Error(Loc, ".abort detected. Assembly stopping.");
3785 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3786 // FIXME: Actually abort assembly here.
3791 /// parseDirectiveInclude
3792 /// ::= .include "filename"
3793 bool AsmParser::parseDirectiveInclude() {
3794 if (getLexer().isNot(AsmToken::String))
3795 return TokError("expected string in '.include' directive");
3797 // Allow the strings to have escaped octal character sequence.
3798 std::string Filename;
3799 if (parseEscapedString(Filename))
3801 SMLoc IncludeLoc = getLexer().getLoc();
3804 if (getLexer().isNot(AsmToken::EndOfStatement))
3805 return TokError("unexpected token in '.include' directive");
3807 // Attempt to switch the lexer to the included file before consuming the end
3808 // of statement to avoid losing it when we switch.
3809 if (enterIncludeFile(Filename)) {
3810 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3817 /// parseDirectiveIncbin
3818 /// ::= .incbin "filename"
3819 bool AsmParser::parseDirectiveIncbin() {
3820 if (getLexer().isNot(AsmToken::String))
3821 return TokError("expected string in '.incbin' directive");
3823 // Allow the strings to have escaped octal character sequence.
3824 std::string Filename;
3825 if (parseEscapedString(Filename))
3827 SMLoc IncbinLoc = getLexer().getLoc();
3830 if (getLexer().isNot(AsmToken::EndOfStatement))
3831 return TokError("unexpected token in '.incbin' directive");
3833 // Attempt to process the included file.
3834 if (processIncbinFile(Filename)) {
3835 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3842 /// parseDirectiveIf
3843 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
3844 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
3845 TheCondStack.push_back(TheCondState);
3846 TheCondState.TheCond = AsmCond::IfCond;
3847 if (TheCondState.Ignore) {
3848 eatToEndOfStatement();
3851 if (parseAbsoluteExpression(ExprValue))
3854 if (getLexer().isNot(AsmToken::EndOfStatement))
3855 return TokError("unexpected token in '.if' directive");
3861 llvm_unreachable("unsupported directive");
3866 ExprValue = ExprValue == 0;
3869 ExprValue = ExprValue >= 0;
3872 ExprValue = ExprValue > 0;
3875 ExprValue = ExprValue <= 0;
3878 ExprValue = ExprValue < 0;
3882 TheCondState.CondMet = ExprValue;
3883 TheCondState.Ignore = !TheCondState.CondMet;
3889 /// parseDirectiveIfb
3891 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3892 TheCondStack.push_back(TheCondState);
3893 TheCondState.TheCond = AsmCond::IfCond;
3895 if (TheCondState.Ignore) {
3896 eatToEndOfStatement();
3898 StringRef Str = parseStringToEndOfStatement();
3900 if (getLexer().isNot(AsmToken::EndOfStatement))
3901 return TokError("unexpected token in '.ifb' directive");
3905 TheCondState.CondMet = ExpectBlank == Str.empty();
3906 TheCondState.Ignore = !TheCondState.CondMet;
3912 /// parseDirectiveIfc
3913 /// ::= .ifc string1, string2
3914 /// ::= .ifnc string1, string2
3915 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3916 TheCondStack.push_back(TheCondState);
3917 TheCondState.TheCond = AsmCond::IfCond;
3919 if (TheCondState.Ignore) {
3920 eatToEndOfStatement();
3922 StringRef Str1 = parseStringToComma();
3924 if (getLexer().isNot(AsmToken::Comma))
3925 return TokError("unexpected token in '.ifc' directive");
3929 StringRef Str2 = parseStringToEndOfStatement();
3931 if (getLexer().isNot(AsmToken::EndOfStatement))
3932 return TokError("unexpected token in '.ifc' directive");
3936 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3937 TheCondState.Ignore = !TheCondState.CondMet;
3943 /// parseDirectiveIfeqs
3944 /// ::= .ifeqs string1, string2
3945 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
3946 if (Lexer.isNot(AsmToken::String)) {
3948 TokError("expected string parameter for '.ifeqs' directive");
3950 TokError("expected string parameter for '.ifnes' directive");
3951 eatToEndOfStatement();
3955 StringRef String1 = getTok().getStringContents();
3958 if (Lexer.isNot(AsmToken::Comma)) {
3960 TokError("expected comma after first string for '.ifeqs' directive");
3962 TokError("expected comma after first string for '.ifnes' directive");
3963 eatToEndOfStatement();
3969 if (Lexer.isNot(AsmToken::String)) {
3971 TokError("expected string parameter for '.ifeqs' directive");
3973 TokError("expected string parameter for '.ifnes' directive");
3974 eatToEndOfStatement();
3978 StringRef String2 = getTok().getStringContents();
3981 TheCondStack.push_back(TheCondState);
3982 TheCondState.TheCond = AsmCond::IfCond;
3983 TheCondState.CondMet = ExpectEqual == (String1 == String2);
3984 TheCondState.Ignore = !TheCondState.CondMet;
3989 /// parseDirectiveIfdef
3990 /// ::= .ifdef symbol
3991 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3993 TheCondStack.push_back(TheCondState);
3994 TheCondState.TheCond = AsmCond::IfCond;
3996 if (TheCondState.Ignore) {
3997 eatToEndOfStatement();
3999 if (parseIdentifier(Name))
4000 return TokError("expected identifier after '.ifdef'");
4004 MCSymbol *Sym = getContext().lookupSymbol(Name);
4007 TheCondState.CondMet = (Sym && !Sym->isUndefined());
4009 TheCondState.CondMet = (!Sym || Sym->isUndefined());
4010 TheCondState.Ignore = !TheCondState.CondMet;
4016 /// parseDirectiveElseIf
4017 /// ::= .elseif expression
4018 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4019 if (TheCondState.TheCond != AsmCond::IfCond &&
4020 TheCondState.TheCond != AsmCond::ElseIfCond)
4021 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4023 TheCondState.TheCond = AsmCond::ElseIfCond;
4025 bool LastIgnoreState = false;
4026 if (!TheCondStack.empty())
4027 LastIgnoreState = TheCondStack.back().Ignore;
4028 if (LastIgnoreState || TheCondState.CondMet) {
4029 TheCondState.Ignore = true;
4030 eatToEndOfStatement();
4033 if (parseAbsoluteExpression(ExprValue))
4036 if (getLexer().isNot(AsmToken::EndOfStatement))
4037 return TokError("unexpected token in '.elseif' directive");
4040 TheCondState.CondMet = ExprValue;
4041 TheCondState.Ignore = !TheCondState.CondMet;
4047 /// parseDirectiveElse
4049 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4050 if (getLexer().isNot(AsmToken::EndOfStatement))
4051 return TokError("unexpected token in '.else' directive");
4055 if (TheCondState.TheCond != AsmCond::IfCond &&
4056 TheCondState.TheCond != AsmCond::ElseIfCond)
4057 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4059 TheCondState.TheCond = AsmCond::ElseCond;
4060 bool LastIgnoreState = false;
4061 if (!TheCondStack.empty())
4062 LastIgnoreState = TheCondStack.back().Ignore;
4063 if (LastIgnoreState || TheCondState.CondMet)
4064 TheCondState.Ignore = true;
4066 TheCondState.Ignore = false;
4071 /// parseDirectiveEnd
4073 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4074 if (getLexer().isNot(AsmToken::EndOfStatement))
4075 return TokError("unexpected token in '.end' directive");
4079 while (Lexer.isNot(AsmToken::Eof))
4085 /// parseDirectiveError
4087 /// ::= .error [string]
4088 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4089 if (!TheCondStack.empty()) {
4090 if (TheCondStack.back().Ignore) {
4091 eatToEndOfStatement();
4097 return Error(L, ".err encountered");
4099 StringRef Message = ".error directive invoked in source file";
4100 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4101 if (Lexer.isNot(AsmToken::String)) {
4102 TokError(".error argument must be a string");
4103 eatToEndOfStatement();
4107 Message = getTok().getStringContents();
4115 /// parseDirectiveWarning
4116 /// ::= .warning [string]
4117 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4118 if (!TheCondStack.empty()) {
4119 if (TheCondStack.back().Ignore) {
4120 eatToEndOfStatement();
4125 StringRef Message = ".warning directive invoked in source file";
4126 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4127 if (Lexer.isNot(AsmToken::String)) {
4128 TokError(".warning argument must be a string");
4129 eatToEndOfStatement();
4133 Message = getTok().getStringContents();
4137 Warning(L, Message);
4141 /// parseDirectiveEndIf
4143 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4144 if (getLexer().isNot(AsmToken::EndOfStatement))
4145 return TokError("unexpected token in '.endif' directive");
4149 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4150 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4152 if (!TheCondStack.empty()) {
4153 TheCondState = TheCondStack.back();
4154 TheCondStack.pop_back();
4160 void AsmParser::initializeDirectiveKindMap() {
4161 DirectiveKindMap[".set"] = DK_SET;
4162 DirectiveKindMap[".equ"] = DK_EQU;
4163 DirectiveKindMap[".equiv"] = DK_EQUIV;
4164 DirectiveKindMap[".ascii"] = DK_ASCII;
4165 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4166 DirectiveKindMap[".string"] = DK_STRING;
4167 DirectiveKindMap[".byte"] = DK_BYTE;
4168 DirectiveKindMap[".short"] = DK_SHORT;
4169 DirectiveKindMap[".value"] = DK_VALUE;
4170 DirectiveKindMap[".2byte"] = DK_2BYTE;
4171 DirectiveKindMap[".long"] = DK_LONG;
4172 DirectiveKindMap[".int"] = DK_INT;
4173 DirectiveKindMap[".4byte"] = DK_4BYTE;
4174 DirectiveKindMap[".quad"] = DK_QUAD;
4175 DirectiveKindMap[".8byte"] = DK_8BYTE;
4176 DirectiveKindMap[".octa"] = DK_OCTA;
4177 DirectiveKindMap[".single"] = DK_SINGLE;
4178 DirectiveKindMap[".float"] = DK_FLOAT;
4179 DirectiveKindMap[".double"] = DK_DOUBLE;
4180 DirectiveKindMap[".align"] = DK_ALIGN;
4181 DirectiveKindMap[".align32"] = DK_ALIGN32;
4182 DirectiveKindMap[".balign"] = DK_BALIGN;
4183 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4184 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4185 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4186 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4187 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4188 DirectiveKindMap[".org"] = DK_ORG;
4189 DirectiveKindMap[".fill"] = DK_FILL;
4190 DirectiveKindMap[".zero"] = DK_ZERO;
4191 DirectiveKindMap[".extern"] = DK_EXTERN;
4192 DirectiveKindMap[".globl"] = DK_GLOBL;
4193 DirectiveKindMap[".global"] = DK_GLOBAL;
4194 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4195 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4196 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4197 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4198 DirectiveKindMap[".reference"] = DK_REFERENCE;
4199 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4200 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4201 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4202 DirectiveKindMap[".comm"] = DK_COMM;
4203 DirectiveKindMap[".common"] = DK_COMMON;
4204 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4205 DirectiveKindMap[".abort"] = DK_ABORT;
4206 DirectiveKindMap[".include"] = DK_INCLUDE;
4207 DirectiveKindMap[".incbin"] = DK_INCBIN;
4208 DirectiveKindMap[".code16"] = DK_CODE16;
4209 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4210 DirectiveKindMap[".rept"] = DK_REPT;
4211 DirectiveKindMap[".rep"] = DK_REPT;
4212 DirectiveKindMap[".irp"] = DK_IRP;
4213 DirectiveKindMap[".irpc"] = DK_IRPC;
4214 DirectiveKindMap[".endr"] = DK_ENDR;
4215 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4216 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4217 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4218 DirectiveKindMap[".if"] = DK_IF;
4219 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4220 DirectiveKindMap[".ifge"] = DK_IFGE;
4221 DirectiveKindMap[".ifgt"] = DK_IFGT;
4222 DirectiveKindMap[".ifle"] = DK_IFLE;
4223 DirectiveKindMap[".iflt"] = DK_IFLT;
4224 DirectiveKindMap[".ifne"] = DK_IFNE;
4225 DirectiveKindMap[".ifb"] = DK_IFB;
4226 DirectiveKindMap[".ifnb"] = DK_IFNB;
4227 DirectiveKindMap[".ifc"] = DK_IFC;
4228 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4229 DirectiveKindMap[".ifnc"] = DK_IFNC;
4230 DirectiveKindMap[".ifnes"] = DK_IFNES;
4231 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4232 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4233 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4234 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4235 DirectiveKindMap[".else"] = DK_ELSE;
4236 DirectiveKindMap[".end"] = DK_END;
4237 DirectiveKindMap[".endif"] = DK_ENDIF;
4238 DirectiveKindMap[".skip"] = DK_SKIP;
4239 DirectiveKindMap[".space"] = DK_SPACE;
4240 DirectiveKindMap[".file"] = DK_FILE;
4241 DirectiveKindMap[".line"] = DK_LINE;
4242 DirectiveKindMap[".loc"] = DK_LOC;
4243 DirectiveKindMap[".stabs"] = DK_STABS;
4244 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4245 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4246 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4247 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4248 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4249 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4250 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4251 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4252 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4253 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4254 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4255 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4256 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4257 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4258 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4259 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4260 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4261 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4262 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4263 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4264 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4265 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4266 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4267 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4268 DirectiveKindMap[".macro"] = DK_MACRO;
4269 DirectiveKindMap[".exitm"] = DK_EXITM;
4270 DirectiveKindMap[".endm"] = DK_ENDM;
4271 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4272 DirectiveKindMap[".purgem"] = DK_PURGEM;
4273 DirectiveKindMap[".err"] = DK_ERR;
4274 DirectiveKindMap[".error"] = DK_ERROR;
4275 DirectiveKindMap[".warning"] = DK_WARNING;
4278 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4279 AsmToken EndToken, StartToken = getTok();
4281 unsigned NestLevel = 0;
4283 // Check whether we have reached the end of the file.
4284 if (getLexer().is(AsmToken::Eof)) {
4285 Error(DirectiveLoc, "no matching '.endr' in definition");
4289 if (Lexer.is(AsmToken::Identifier) &&
4290 (getTok().getIdentifier() == ".rept")) {
4294 // Otherwise, check whether we have reached the .endr.
4295 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4296 if (NestLevel == 0) {
4297 EndToken = getTok();
4299 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4300 TokError("unexpected token in '.endr' directive");
4308 // Otherwise, scan till the end of the statement.
4309 eatToEndOfStatement();
4312 const char *BodyStart = StartToken.getLoc().getPointer();
4313 const char *BodyEnd = EndToken.getLoc().getPointer();
4314 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4316 // We Are Anonymous.
4317 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
4318 return &MacroLikeBodies.back();
4321 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4322 raw_svector_ostream &OS) {
4325 std::unique_ptr<MemoryBuffer> Instantiation =
4326 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4328 // Create the macro instantiation object and add to the current macro
4329 // instantiation stack.
4330 MacroInstantiation *MI = new MacroInstantiation(
4331 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
4332 ActiveMacros.push_back(MI);
4334 // Jump to the macro instantiation and prime the lexer.
4335 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
4336 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
4340 /// parseDirectiveRept
4341 /// ::= .rep | .rept count
4342 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4343 const MCExpr *CountExpr;
4344 SMLoc CountLoc = getTok().getLoc();
4345 if (parseExpression(CountExpr))
4349 if (!CountExpr->evaluateAsAbsolute(Count)) {
4350 eatToEndOfStatement();
4351 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4355 return Error(CountLoc, "Count is negative");
4357 if (Lexer.isNot(AsmToken::EndOfStatement))
4358 return TokError("unexpected token in '" + Dir + "' directive");
4360 // Eat the end of statement.
4363 // Lex the rept definition.
4364 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4368 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4369 // to hold the macro body with substitutions.
4370 SmallString<256> Buf;
4371 raw_svector_ostream OS(Buf);
4373 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4374 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
4377 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4382 /// parseDirectiveIrp
4383 /// ::= .irp symbol,values
4384 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4385 MCAsmMacroParameter Parameter;
4387 if (parseIdentifier(Parameter.Name))
4388 return TokError("expected identifier in '.irp' directive");
4390 if (Lexer.isNot(AsmToken::Comma))
4391 return TokError("expected comma in '.irp' directive");
4395 MCAsmMacroArguments A;
4396 if (parseMacroArguments(nullptr, A))
4399 // Eat the end of statement.
4402 // Lex the irp definition.
4403 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4407 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4408 // to hold the macro body with substitutions.
4409 SmallString<256> Buf;
4410 raw_svector_ostream OS(Buf);
4412 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4413 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4414 // This is undocumented, but GAS seems to support it.
4415 if (expandMacro(OS, M->Body, Parameter, *i, true, getTok().getLoc()))
4419 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4424 /// parseDirectiveIrpc
4425 /// ::= .irpc symbol,values
4426 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4427 MCAsmMacroParameter Parameter;
4429 if (parseIdentifier(Parameter.Name))
4430 return TokError("expected identifier in '.irpc' directive");
4432 if (Lexer.isNot(AsmToken::Comma))
4433 return TokError("expected comma in '.irpc' directive");
4437 MCAsmMacroArguments A;
4438 if (parseMacroArguments(nullptr, A))
4441 if (A.size() != 1 || A.front().size() != 1)
4442 return TokError("unexpected token in '.irpc' directive");
4444 // Eat the end of statement.
4447 // Lex the irpc definition.
4448 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4452 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4453 // to hold the macro body with substitutions.
4454 SmallString<256> Buf;
4455 raw_svector_ostream OS(Buf);
4457 StringRef Values = A.front().front().getString();
4458 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4459 MCAsmMacroArgument Arg;
4460 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
4462 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4463 // This is undocumented, but GAS seems to support it.
4464 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
4468 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4473 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4474 if (ActiveMacros.empty())
4475 return TokError("unmatched '.endr' directive");
4477 // The only .repl that should get here are the ones created by
4478 // instantiateMacroLikeBody.
4479 assert(getLexer().is(AsmToken::EndOfStatement));
4485 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4487 const MCExpr *Value;
4488 SMLoc ExprLoc = getLexer().getLoc();
4489 if (parseExpression(Value))
4491 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4493 return Error(ExprLoc, "unexpected expression in _emit");
4494 uint64_t IntValue = MCE->getValue();
4495 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4496 return Error(ExprLoc, "literal value out of range for directive");
4498 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4502 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4503 const MCExpr *Value;
4504 SMLoc ExprLoc = getLexer().getLoc();
4505 if (parseExpression(Value))
4507 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4509 return Error(ExprLoc, "unexpected expression in align");
4510 uint64_t IntValue = MCE->getValue();
4511 if (!isPowerOf2_64(IntValue))
4512 return Error(ExprLoc, "literal value not a power of two greater then zero");
4514 Info.AsmRewrites->push_back(
4515 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4519 // We are comparing pointers, but the pointers are relative to a single string.
4520 // Thus, this should always be deterministic.
4521 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4522 const AsmRewrite *AsmRewriteB) {
4523 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4525 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4528 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4529 // rewrite to the same location. Make sure the SizeDirective rewrite is
4530 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4531 // ensures the sort algorithm is stable.
4532 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4533 AsmRewritePrecedence[AsmRewriteB->Kind])
4536 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4537 AsmRewritePrecedence[AsmRewriteB->Kind])
4539 llvm_unreachable("Unstable rewrite sort.");
4542 bool AsmParser::parseMSInlineAsm(
4543 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4544 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4545 SmallVectorImpl<std::string> &Constraints,
4546 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4547 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4548 SmallVector<void *, 4> InputDecls;
4549 SmallVector<void *, 4> OutputDecls;
4550 SmallVector<bool, 4> InputDeclsAddressOf;
4551 SmallVector<bool, 4> OutputDeclsAddressOf;
4552 SmallVector<std::string, 4> InputConstraints;
4553 SmallVector<std::string, 4> OutputConstraints;
4554 SmallVector<unsigned, 4> ClobberRegs;
4556 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4561 // While we have input, parse each statement.
4562 unsigned InputIdx = 0;
4563 unsigned OutputIdx = 0;
4564 while (getLexer().isNot(AsmToken::Eof)) {
4565 ParseStatementInfo Info(&AsmStrRewrites);
4566 if (parseStatement(Info, &SI))
4569 if (Info.ParseError)
4572 if (Info.Opcode == ~0U)
4575 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4577 // Build the list of clobbers, outputs and inputs.
4578 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4579 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4582 if (Operand.isImm())
4585 // Register operand.
4586 if (Operand.isReg() && !Operand.needAddressOf() &&
4587 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
4588 unsigned NumDefs = Desc.getNumDefs();
4590 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4591 ClobberRegs.push_back(Operand.getReg());
4595 // Expr/Input or Output.
4596 StringRef SymName = Operand.getSymName();
4597 if (SymName.empty())
4600 void *OpDecl = Operand.getOpDecl();
4604 bool isOutput = (i == 1) && Desc.mayStore();
4605 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4608 OutputDecls.push_back(OpDecl);
4609 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4610 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
4611 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4613 InputDecls.push_back(OpDecl);
4614 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4615 InputConstraints.push_back(Operand.getConstraint().str());
4616 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4620 // Consider implicit defs to be clobbers. Think of cpuid and push.
4621 ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
4622 Desc.getNumImplicitDefs());
4623 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
4626 // Set the number of Outputs and Inputs.
4627 NumOutputs = OutputDecls.size();
4628 NumInputs = InputDecls.size();
4630 // Set the unique clobbers.
4631 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4632 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4634 Clobbers.assign(ClobberRegs.size(), std::string());
4635 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4636 raw_string_ostream OS(Clobbers[I]);
4637 IP->printRegName(OS, ClobberRegs[I]);
4640 // Merge the various outputs and inputs. Output are expected first.
4641 if (NumOutputs || NumInputs) {
4642 unsigned NumExprs = NumOutputs + NumInputs;
4643 OpDecls.resize(NumExprs);
4644 Constraints.resize(NumExprs);
4645 for (unsigned i = 0; i < NumOutputs; ++i) {
4646 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4647 Constraints[i] = OutputConstraints[i];
4649 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4650 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4651 Constraints[j] = InputConstraints[i];
4655 // Build the IR assembly string.
4656 std::string AsmStringIR;
4657 raw_string_ostream OS(AsmStringIR);
4658 StringRef ASMString =
4659 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4660 const char *AsmStart = ASMString.begin();
4661 const char *AsmEnd = ASMString.end();
4662 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4663 for (const AsmRewrite &AR : AsmStrRewrites) {
4664 AsmRewriteKind Kind = AR.Kind;
4665 if (Kind == AOK_Delete)
4668 const char *Loc = AR.Loc.getPointer();
4669 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4671 // Emit everything up to the immediate/expression.
4672 if (unsigned Len = Loc - AsmStart)
4673 OS << StringRef(AsmStart, Len);
4675 // Skip the original expression.
4676 if (Kind == AOK_Skip) {
4677 AsmStart = Loc + AR.Len;
4681 unsigned AdditionalSkip = 0;
4682 // Rewrite expressions in $N notation.
4687 OS << "$$" << AR.Val;
4693 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
4696 OS << '$' << InputIdx++;
4699 OS << '$' << OutputIdx++;
4701 case AOK_SizeDirective:
4704 case 8: OS << "byte ptr "; break;
4705 case 16: OS << "word ptr "; break;
4706 case 32: OS << "dword ptr "; break;
4707 case 64: OS << "qword ptr "; break;
4708 case 80: OS << "xword ptr "; break;
4709 case 128: OS << "xmmword ptr "; break;
4710 case 256: OS << "ymmword ptr "; break;
4717 unsigned Val = AR.Val;
4718 OS << ".align " << Val;
4720 // Skip the original immediate.
4721 assert(Val < 10 && "Expected alignment less then 2^10.");
4722 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4725 case AOK_DotOperator:
4726 // Insert the dot if the user omitted it.
4728 if (AsmStringIR.back() != '.')
4734 // Skip the original expression.
4735 AsmStart = Loc + AR.Len + AdditionalSkip;
4738 // Emit the remainder of the asm string.
4739 if (AsmStart != AsmEnd)
4740 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4742 AsmString = OS.str();
4747 namespace MCParserUtils {
4749 /// Returns whether the given symbol is used anywhere in the given expression,
4750 /// or subexpressions.
4751 static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
4752 switch (Value->getKind()) {
4753 case MCExpr::Binary: {
4754 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
4755 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
4756 isSymbolUsedInExpression(Sym, BE->getRHS());
4758 case MCExpr::Target:
4759 case MCExpr::Constant:
4761 case MCExpr::SymbolRef: {
4763 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
4765 return isSymbolUsedInExpression(Sym, S.getVariableValue());
4769 return isSymbolUsedInExpression(
4770 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
4773 llvm_unreachable("Unknown expr kind!");
4776 bool parseAssignmentExpression(StringRef Name, bool allow_redef,
4777 MCAsmParser &Parser, MCSymbol *&Sym,
4778 const MCExpr *&Value) {
4779 MCAsmLexer &Lexer = Parser.getLexer();
4781 // FIXME: Use better location, we should use proper tokens.
4782 SMLoc EqualLoc = Lexer.getLoc();
4784 if (Parser.parseExpression(Value)) {
4785 Parser.TokError("missing expression");
4786 Parser.eatToEndOfStatement();
4790 // Note: we don't count b as used in "a = b". This is to allow
4794 if (Lexer.isNot(AsmToken::EndOfStatement))
4795 return Parser.TokError("unexpected token in assignment");
4797 // Eat the end of statement marker.
4800 // Validate that the LHS is allowed to be a variable (either it has not been
4801 // used as a symbol, or it is an absolute symbol).
4802 Sym = Parser.getContext().lookupSymbol(Name);
4804 // Diagnose assignment to a label.
4806 // FIXME: Diagnostics. Note the location of the definition as a label.
4807 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
4808 if (isSymbolUsedInExpression(Sym, Value))
4809 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
4810 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
4811 ; // Allow redefinitions of undefined symbols only used in directives.
4812 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
4813 ; // Allow redefinitions of variables that haven't yet been used.
4814 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
4815 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
4816 else if (!Sym->isVariable())
4817 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
4818 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
4819 return Parser.Error(EqualLoc,
4820 "invalid reassignment of non-absolute variable '" +
4823 // Don't count these checks as uses.
4824 Sym->setUsed(false);
4825 } else if (Name == ".") {
4826 if (Parser.getStreamer().EmitValueToOffset(Value, 0)) {
4827 Parser.Error(EqualLoc, "expected absolute expression");
4828 Parser.eatToEndOfStatement();
4833 Sym = Parser.getContext().getOrCreateSymbol(Name);
4835 Sym->setRedefinable(allow_redef);
4840 } // namespace MCParserUtils
4843 /// \brief Create an MCAsmParser instance.
4844 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4845 MCStreamer &Out, const MCAsmInfo &MAI) {
4846 return new AsmParser(SM, C, Out, MAI);