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/MC/MCValue.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/MemoryBuffer.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/raw_ostream.h"
50 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
53 /// \brief Helper types for tracking macro definitions.
54 typedef std::vector<AsmToken> MCAsmMacroArgument;
55 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
57 struct MCAsmMacroParameter {
59 MCAsmMacroArgument Value;
63 MCAsmMacroParameter() : Required(false), Vararg(false) {}
66 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
71 MCAsmMacroParameters Parameters;
74 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
75 : Name(N), Body(B), Parameters(std::move(P)) {}
78 /// \brief Helper class for storing information about an active macro
80 struct MacroInstantiation {
81 /// The location of the instantiation.
82 SMLoc InstantiationLoc;
84 /// The buffer where parsing should resume upon instantiation completion.
87 /// The location where parsing should resume upon instantiation completion.
90 /// The depth of TheCondStack at the start of the instantiation.
91 size_t CondStackDepth;
94 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
97 struct ParseStatementInfo {
98 /// \brief The parsed operands from the last parsed statement.
99 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
101 /// \brief The opcode from the last parsed instruction.
104 /// \brief Was there an error parsing the inline assembly?
107 SmallVectorImpl<AsmRewrite> *AsmRewrites;
109 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
110 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
111 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
114 /// \brief The concrete assembly parser instance.
115 class AsmParser : public MCAsmParser {
116 AsmParser(const AsmParser &) = delete;
117 void operator=(const AsmParser &) = delete;
122 const MCAsmInfo &MAI;
124 SourceMgr::DiagHandlerTy SavedDiagHandler;
125 void *SavedDiagContext;
126 std::unique_ptr<MCAsmParserExtension> PlatformParser;
128 /// This is the current buffer index we're lexing from as managed by the
129 /// SourceMgr object.
132 AsmCond TheCondState;
133 std::vector<AsmCond> TheCondStack;
135 /// \brief maps directive names to handler methods in parser
136 /// extensions. Extensions register themselves in this map by calling
137 /// addDirectiveHandler.
138 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
140 /// \brief Map of currently defined macros.
141 StringMap<MCAsmMacro> MacroMap;
143 /// \brief Stack of active macro instantiations.
144 std::vector<MacroInstantiation*> ActiveMacros;
146 /// \brief List of bodies of anonymous macros.
147 std::deque<MCAsmMacro> MacroLikeBodies;
149 /// Boolean tracking whether macro substitution is enabled.
150 unsigned MacrosEnabledFlag : 1;
152 /// \brief Keeps track of how many .macro's have been instantiated.
153 unsigned NumOfMacroInstantiations;
155 /// Flag tracking whether any errors have been encountered.
156 unsigned HadError : 1;
158 /// The values from the last parsed cpp hash file line comment if any.
159 StringRef CppHashFilename;
160 int64_t CppHashLineNumber;
163 /// When generating dwarf for assembly source files we need to calculate the
164 /// logical line number based on the last parsed cpp hash file line comment
165 /// and current line. Since this is slow and messes up the SourceMgr's
166 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
167 SMLoc LastQueryIDLoc;
168 unsigned LastQueryBuffer;
169 unsigned LastQueryLine;
171 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
172 unsigned AssemblerDialect;
174 /// \brief is Darwin compatibility enabled?
177 /// \brief Are we parsing ms-style inline assembly?
178 bool ParsingInlineAsm;
181 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
182 const MCAsmInfo &MAI);
183 ~AsmParser() override;
185 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
187 void addDirectiveHandler(StringRef Directive,
188 ExtensionDirectiveHandler Handler) override {
189 ExtensionDirectiveMap[Directive] = Handler;
192 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
193 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
197 /// @name MCAsmParser Interface
200 SourceMgr &getSourceManager() override { return SrcMgr; }
201 MCAsmLexer &getLexer() override { return Lexer; }
202 MCContext &getContext() override { return Ctx; }
203 MCStreamer &getStreamer() override { return Out; }
204 unsigned getAssemblerDialect() override {
205 if (AssemblerDialect == ~0U)
206 return MAI.getAssemblerDialect();
208 return AssemblerDialect;
210 void setAssemblerDialect(unsigned i) override {
211 AssemblerDialect = i;
214 void Note(SMLoc L, const Twine &Msg,
215 ArrayRef<SMRange> Ranges = None) override;
216 bool Warning(SMLoc L, const Twine &Msg,
217 ArrayRef<SMRange> Ranges = None) override;
218 bool Error(SMLoc L, const Twine &Msg,
219 ArrayRef<SMRange> Ranges = None) override;
221 const AsmToken &Lex() override;
223 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
224 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
226 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
227 unsigned &NumOutputs, unsigned &NumInputs,
228 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
229 SmallVectorImpl<std::string> &Constraints,
230 SmallVectorImpl<std::string> &Clobbers,
231 const MCInstrInfo *MII, const MCInstPrinter *IP,
232 MCAsmParserSemaCallback &SI) override;
234 bool parseExpression(const MCExpr *&Res);
235 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
236 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
237 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
238 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
239 SMLoc &EndLoc) override;
240 bool parseAbsoluteExpression(int64_t &Res) override;
242 /// \brief Parse an identifier or string (as a quoted identifier)
243 /// and set \p Res to the identifier contents.
244 bool parseIdentifier(StringRef &Res) override;
245 void eatToEndOfStatement() override;
247 void checkForValidSection() override;
252 bool parseStatement(ParseStatementInfo &Info,
253 MCAsmParserSemaCallback *SI);
254 void eatToEndOfLine();
255 bool parseCppHashLineFilenameComment(SMLoc L);
257 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
258 ArrayRef<MCAsmMacroParameter> Parameters);
259 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
260 ArrayRef<MCAsmMacroParameter> Parameters,
261 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
264 /// \brief Are macros enabled in the parser?
265 bool areMacrosEnabled() {return MacrosEnabledFlag;}
267 /// \brief Control a flag in the parser that enables or disables macros.
268 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
270 /// \brief Lookup a previously defined macro.
271 /// \param Name Macro name.
272 /// \returns Pointer to macro. NULL if no such macro was defined.
273 const MCAsmMacro* lookupMacro(StringRef Name);
275 /// \brief Define a new macro with the given name and information.
276 void defineMacro(StringRef Name, MCAsmMacro Macro);
278 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
279 void undefineMacro(StringRef Name);
281 /// \brief Are we inside a macro instantiation?
282 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
284 /// \brief Handle entry to macro instantiation.
286 /// \param M The macro.
287 /// \param NameLoc Instantiation location.
288 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
290 /// \brief Handle exit from macro instantiation.
291 void handleMacroExit();
293 /// \brief Extract AsmTokens for a macro argument.
294 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
296 /// \brief Parse all macro arguments for a given macro.
297 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
299 void printMacroInstantiations();
300 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
301 ArrayRef<SMRange> Ranges = None) const {
302 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
304 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
306 /// \brief Enter the specified file. This returns true on failure.
307 bool enterIncludeFile(const std::string &Filename);
309 /// \brief Process the specified file for the .incbin directive.
310 /// This returns true on failure.
311 bool processIncbinFile(const std::string &Filename);
313 /// \brief Reset the current lexer position to that given by \p Loc. The
314 /// current token is not set; clients should ensure Lex() is called
317 /// \param InBuffer If not 0, should be the known buffer id that contains the
319 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
321 /// \brief Parse up to the end of statement and a return the contents from the
322 /// current token until the end of the statement; the current token on exit
323 /// will be either the EndOfStatement or EOF.
324 StringRef parseStringToEndOfStatement() override;
326 /// \brief Parse until the end of a statement or a comma is encountered,
327 /// return the contents from the current token up to the end or comma.
328 StringRef parseStringToComma();
330 bool parseAssignment(StringRef Name, bool allow_redef,
331 bool NoDeadStrip = false);
333 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
334 MCBinaryExpr::Opcode &Kind);
336 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
337 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
338 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
340 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
342 // Generic (target and platform independent) directive parsing.
344 DK_NO_DIRECTIVE, // Placeholder
345 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
347 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
348 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
349 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
350 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
351 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
352 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
353 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
354 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
355 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
356 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
357 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
358 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
359 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
360 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
361 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
362 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
363 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
364 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
365 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
366 DK_MACROS_ON, DK_MACROS_OFF,
367 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
368 DK_SLEB128, DK_ULEB128,
369 DK_ERR, DK_ERROR, DK_WARNING,
373 /// \brief Maps directive name --> DirectiveKind enum, for
374 /// directives parsed by this class.
375 StringMap<DirectiveKind> DirectiveKindMap;
377 // ".ascii", ".asciz", ".string"
378 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
379 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
380 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
381 bool parseDirectiveOctaValue(); // ".octa"
382 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
383 bool parseDirectiveFill(); // ".fill"
384 bool parseDirectiveZero(); // ".zero"
385 // ".set", ".equ", ".equiv"
386 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
387 bool parseDirectiveOrg(); // ".org"
388 // ".align{,32}", ".p2align{,w,l}"
389 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
391 // ".file", ".line", ".loc", ".stabs"
392 bool parseDirectiveFile(SMLoc DirectiveLoc);
393 bool parseDirectiveLine();
394 bool parseDirectiveLoc();
395 bool parseDirectiveStabs();
398 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
399 bool parseDirectiveCFIWindowSave();
400 bool parseDirectiveCFISections();
401 bool parseDirectiveCFIStartProc();
402 bool parseDirectiveCFIEndProc();
403 bool parseDirectiveCFIDefCfaOffset();
404 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
405 bool parseDirectiveCFIAdjustCfaOffset();
406 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
407 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
408 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
409 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
410 bool parseDirectiveCFIRememberState();
411 bool parseDirectiveCFIRestoreState();
412 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
413 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
414 bool parseDirectiveCFIEscape();
415 bool parseDirectiveCFISignalFrame();
416 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
419 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
420 bool parseDirectiveExitMacro(StringRef Directive);
421 bool parseDirectiveEndMacro(StringRef Directive);
422 bool parseDirectiveMacro(SMLoc DirectiveLoc);
423 bool parseDirectiveMacrosOnOff(StringRef Directive);
425 // ".bundle_align_mode"
426 bool parseDirectiveBundleAlignMode();
428 bool parseDirectiveBundleLock();
430 bool parseDirectiveBundleUnlock();
433 bool parseDirectiveSpace(StringRef IDVal);
435 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
436 bool parseDirectiveLEB128(bool Signed);
438 /// \brief Parse a directive like ".globl" which
439 /// accepts a single symbol (which should be a label or an external).
440 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
442 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
444 bool parseDirectiveAbort(); // ".abort"
445 bool parseDirectiveInclude(); // ".include"
446 bool parseDirectiveIncbin(); // ".incbin"
448 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
449 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
450 // ".ifb" or ".ifnb", depending on ExpectBlank.
451 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
452 // ".ifc" or ".ifnc", depending on ExpectEqual.
453 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
454 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
455 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
456 // ".ifdef" or ".ifndef", depending on expect_defined
457 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
458 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
459 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
460 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
461 bool parseEscapedString(std::string &Data) override;
463 const MCExpr *applyModifierToExpr(const MCExpr *E,
464 MCSymbolRefExpr::VariantKind Variant);
466 // Macro-like directives
467 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
468 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
469 raw_svector_ostream &OS);
470 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
471 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
472 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
473 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
475 // "_emit" or "__emit"
476 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
480 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
483 bool parseDirectiveEnd(SMLoc DirectiveLoc);
485 // ".err" or ".error"
486 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
489 bool parseDirectiveWarning(SMLoc DirectiveLoc);
491 void initializeDirectiveKindMap();
497 extern MCAsmParserExtension *createDarwinAsmParser();
498 extern MCAsmParserExtension *createELFAsmParser();
499 extern MCAsmParserExtension *createCOFFAsmParser();
503 enum { DEFAULT_ADDRSPACE = 0 };
505 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
506 const MCAsmInfo &MAI)
507 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
508 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
509 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
510 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
511 // Save the old handler.
512 SavedDiagHandler = SrcMgr.getDiagHandler();
513 SavedDiagContext = SrcMgr.getDiagContext();
514 // Set our own handler which calls the saved handler.
515 SrcMgr.setDiagHandler(DiagHandler, this);
516 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
518 // Initialize the platform / file format parser.
519 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
520 case MCObjectFileInfo::IsCOFF:
521 PlatformParser.reset(createCOFFAsmParser());
523 case MCObjectFileInfo::IsMachO:
524 PlatformParser.reset(createDarwinAsmParser());
527 case MCObjectFileInfo::IsELF:
528 PlatformParser.reset(createELFAsmParser());
532 PlatformParser->Initialize(*this);
533 initializeDirectiveKindMap();
535 NumOfMacroInstantiations = 0;
538 AsmParser::~AsmParser() {
539 assert((HadError || ActiveMacros.empty()) &&
540 "Unexpected active macro instantiation!");
543 void AsmParser::printMacroInstantiations() {
544 // Print the active macro instantiation stack.
545 for (std::vector<MacroInstantiation *>::const_reverse_iterator
546 it = ActiveMacros.rbegin(),
547 ie = ActiveMacros.rend();
549 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
550 "while in macro instantiation");
553 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
554 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
555 printMacroInstantiations();
558 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
559 if(getTargetParser().getTargetOptions().MCNoWarn)
561 if (getTargetParser().getTargetOptions().MCFatalWarnings)
562 return Error(L, Msg, Ranges);
563 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
564 printMacroInstantiations();
568 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
570 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
571 printMacroInstantiations();
575 bool AsmParser::enterIncludeFile(const std::string &Filename) {
576 std::string IncludedFile;
578 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
583 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
587 /// Process the specified .incbin file by searching for it in the include paths
588 /// then just emitting the byte contents of the file to the streamer. This
589 /// returns true on failure.
590 bool AsmParser::processIncbinFile(const std::string &Filename) {
591 std::string IncludedFile;
593 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
597 // Pick up the bytes from the file and emit them.
598 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
602 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
603 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
604 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
608 const AsmToken &AsmParser::Lex() {
609 const AsmToken *tok = &Lexer.Lex();
611 if (tok->is(AsmToken::Eof)) {
612 // If this is the end of an included file, pop the parent file off the
614 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
615 if (ParentIncludeLoc != SMLoc()) {
616 jumpToLoc(ParentIncludeLoc);
621 if (tok->is(AsmToken::Error))
622 Error(Lexer.getErrLoc(), Lexer.getErr());
627 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
628 // Create the initial section, if requested.
629 if (!NoInitialTextSection)
630 Out.InitSections(false);
636 AsmCond StartingCondState = TheCondState;
638 // If we are generating dwarf for assembly source files save the initial text
639 // section and generate a .file directive.
640 if (getContext().getGenDwarfForAssembly()) {
641 MCSection *Sec = getStreamer().getCurrentSection().first;
642 if (!Sec->getBeginSymbol()) {
643 MCSymbol *SectionStartSym = getContext().createTempSymbol();
644 getStreamer().EmitLabel(SectionStartSym);
645 Sec->setBeginSymbol(SectionStartSym);
647 bool InsertResult = getContext().addGenDwarfSection(Sec);
648 assert(InsertResult && ".text section should not have debug info yet");
650 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
651 0, StringRef(), getContext().getMainFileName()));
654 // While we have input, parse each statement.
655 while (Lexer.isNot(AsmToken::Eof)) {
656 ParseStatementInfo Info;
657 if (!parseStatement(Info, nullptr))
660 // We had an error, validate that one was emitted and recover by skipping to
662 assert(HadError && "Parse statement returned an error, but none emitted!");
663 eatToEndOfStatement();
666 if (TheCondState.TheCond != StartingCondState.TheCond ||
667 TheCondState.Ignore != StartingCondState.Ignore)
668 return TokError("unmatched .ifs or .elses");
670 // Check to see there are no empty DwarfFile slots.
671 const auto &LineTables = getContext().getMCDwarfLineTables();
672 if (!LineTables.empty()) {
674 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
675 if (File.Name.empty() && Index != 0)
676 TokError("unassigned file number: " + Twine(Index) +
677 " for .file directives");
682 // Check to see that all assembler local symbols were actually defined.
683 // Targets that don't do subsections via symbols may not want this, though,
684 // so conservatively exclude them. Only do this if we're finalizing, though,
685 // as otherwise we won't necessarilly have seen everything yet.
686 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
687 for (const auto &TableEntry : getContext().getSymbols()) {
688 MCSymbol *Sym = TableEntry.getValue();
689 // Variable symbols may not be marked as defined, so check those
690 // explicitly. If we know it's a variable, we have a definition for
691 // the purposes of this check.
692 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
693 // FIXME: We would really like to refer back to where the symbol was
694 // first referenced for a source location. We need to add something
695 // to track that. Currently, we just point to the end of the file.
696 return Error(getLexer().getLoc(), "assembler local symbol '" +
697 Sym->getName() + "' not defined");
701 // Finalize the output stream if there are no errors and if the client wants
703 if (!HadError && !NoFinalize)
706 return HadError || getContext().hadError();
709 void AsmParser::checkForValidSection() {
710 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
711 TokError("expected section directive before assembly directive");
712 Out.InitSections(false);
716 /// \brief Throw away the rest of the line for testing purposes.
717 void AsmParser::eatToEndOfStatement() {
718 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
722 if (Lexer.is(AsmToken::EndOfStatement))
726 StringRef AsmParser::parseStringToEndOfStatement() {
727 const char *Start = getTok().getLoc().getPointer();
729 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
732 const char *End = getTok().getLoc().getPointer();
733 return StringRef(Start, End - Start);
736 StringRef AsmParser::parseStringToComma() {
737 const char *Start = getTok().getLoc().getPointer();
739 while (Lexer.isNot(AsmToken::EndOfStatement) &&
740 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
743 const char *End = getTok().getLoc().getPointer();
744 return StringRef(Start, End - Start);
747 /// \brief Parse a paren expression and return it.
748 /// NOTE: This assumes the leading '(' has already been consumed.
750 /// parenexpr ::= expr)
752 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
753 if (parseExpression(Res))
755 if (Lexer.isNot(AsmToken::RParen))
756 return TokError("expected ')' in parentheses expression");
757 EndLoc = Lexer.getTok().getEndLoc();
762 /// \brief Parse a bracket expression and return it.
763 /// NOTE: This assumes the leading '[' has already been consumed.
765 /// bracketexpr ::= expr]
767 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
768 if (parseExpression(Res))
770 if (Lexer.isNot(AsmToken::RBrac))
771 return TokError("expected ']' in brackets expression");
772 EndLoc = Lexer.getTok().getEndLoc();
777 /// \brief Parse a primary expression and return it.
778 /// primaryexpr ::= (parenexpr
779 /// primaryexpr ::= symbol
780 /// primaryexpr ::= number
781 /// primaryexpr ::= '.'
782 /// primaryexpr ::= ~,+,- primaryexpr
783 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
784 SMLoc FirstTokenLoc = getLexer().getLoc();
785 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
786 switch (FirstTokenKind) {
788 return TokError("unknown token in expression");
789 // If we have an error assume that we've already handled it.
790 case AsmToken::Error:
792 case AsmToken::Exclaim:
793 Lex(); // Eat the operator.
794 if (parsePrimaryExpr(Res, EndLoc))
796 Res = MCUnaryExpr::createLNot(Res, getContext());
798 case AsmToken::Dollar:
800 case AsmToken::String:
801 case AsmToken::Identifier: {
802 StringRef Identifier;
803 if (parseIdentifier(Identifier)) {
804 if (FirstTokenKind == AsmToken::Dollar) {
805 if (Lexer.getMAI().getDollarIsPC()) {
806 // This is a '$' reference, which references the current PC. Emit a
807 // temporary label to the streamer and refer to it.
808 MCSymbol *Sym = Ctx.createTempSymbol();
810 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
812 EndLoc = FirstTokenLoc;
815 return Error(FirstTokenLoc, "invalid token in expression");
818 // Parse symbol variant
819 std::pair<StringRef, StringRef> Split;
820 if (!MAI.useParensForSymbolVariant()) {
821 if (FirstTokenKind == AsmToken::String) {
822 if (Lexer.is(AsmToken::At)) {
823 Lexer.Lex(); // eat @
824 SMLoc AtLoc = getLexer().getLoc();
826 if (parseIdentifier(VName))
827 return Error(AtLoc, "expected symbol variant after '@'");
829 Split = std::make_pair(Identifier, VName);
832 Split = Identifier.split('@');
834 } else if (Lexer.is(AsmToken::LParen)) {
835 Lexer.Lex(); // eat (
837 parseIdentifier(VName);
838 if (Lexer.isNot(AsmToken::RParen)) {
839 return Error(Lexer.getTok().getLoc(),
840 "unexpected token in variant, expected ')'");
842 Lexer.Lex(); // eat )
843 Split = std::make_pair(Identifier, VName);
846 EndLoc = SMLoc::getFromPointer(Identifier.end());
848 // This is a symbol reference.
849 StringRef SymbolName = Identifier;
850 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
852 // Lookup the symbol variant if used.
853 if (Split.second.size()) {
854 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
855 if (Variant != MCSymbolRefExpr::VK_Invalid) {
856 SymbolName = Split.first;
857 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
858 Variant = MCSymbolRefExpr::VK_None;
860 return Error(SMLoc::getFromPointer(Split.second.begin()),
861 "invalid variant '" + Split.second + "'");
865 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
867 // If this is an absolute variable reference, substitute it now to preserve
868 // semantics in the face of reassignment.
869 if (Sym->isVariable() &&
870 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
872 return Error(EndLoc, "unexpected modifier on variable reference");
874 Res = Sym->getVariableValue(/*SetUsed*/ false);
878 // Otherwise create a symbol ref.
879 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
882 case AsmToken::BigNum:
883 return TokError("literal value out of range for directive");
884 case AsmToken::Integer: {
885 SMLoc Loc = getTok().getLoc();
886 int64_t IntVal = getTok().getIntVal();
887 Res = MCConstantExpr::create(IntVal, getContext());
888 EndLoc = Lexer.getTok().getEndLoc();
890 // Look for 'b' or 'f' following an Integer as a directional label
891 if (Lexer.getKind() == AsmToken::Identifier) {
892 StringRef IDVal = getTok().getString();
893 // Lookup the symbol variant if used.
894 std::pair<StringRef, StringRef> Split = IDVal.split('@');
895 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
896 if (Split.first.size() != IDVal.size()) {
897 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
898 if (Variant == MCSymbolRefExpr::VK_Invalid)
899 return TokError("invalid variant '" + Split.second + "'");
902 if (IDVal == "f" || IDVal == "b") {
904 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
905 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
906 if (IDVal == "b" && Sym->isUndefined())
907 return Error(Loc, "invalid reference to undefined symbol");
908 EndLoc = Lexer.getTok().getEndLoc();
909 Lex(); // Eat identifier.
914 case AsmToken::Real: {
915 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
916 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
917 Res = MCConstantExpr::create(IntVal, getContext());
918 EndLoc = Lexer.getTok().getEndLoc();
922 case AsmToken::Dot: {
923 // This is a '.' reference, which references the current PC. Emit a
924 // temporary label to the streamer and refer to it.
925 MCSymbol *Sym = Ctx.createTempSymbol();
927 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
928 EndLoc = Lexer.getTok().getEndLoc();
929 Lex(); // Eat identifier.
932 case AsmToken::LParen:
933 Lex(); // Eat the '('.
934 return parseParenExpr(Res, EndLoc);
935 case AsmToken::LBrac:
936 if (!PlatformParser->HasBracketExpressions())
937 return TokError("brackets expression not supported on this target");
938 Lex(); // Eat the '['.
939 return parseBracketExpr(Res, EndLoc);
940 case AsmToken::Minus:
941 Lex(); // Eat the operator.
942 if (parsePrimaryExpr(Res, EndLoc))
944 Res = MCUnaryExpr::createMinus(Res, getContext());
947 Lex(); // Eat the operator.
948 if (parsePrimaryExpr(Res, EndLoc))
950 Res = MCUnaryExpr::createPlus(Res, getContext());
952 case AsmToken::Tilde:
953 Lex(); // Eat the operator.
954 if (parsePrimaryExpr(Res, EndLoc))
956 Res = MCUnaryExpr::createNot(Res, getContext());
961 bool AsmParser::parseExpression(const MCExpr *&Res) {
963 return parseExpression(Res, EndLoc);
967 AsmParser::applyModifierToExpr(const MCExpr *E,
968 MCSymbolRefExpr::VariantKind Variant) {
969 // Ask the target implementation about this expression first.
970 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
973 // Recurse over the given expression, rebuilding it to apply the given variant
974 // if there is exactly one symbol.
975 switch (E->getKind()) {
977 case MCExpr::Constant:
980 case MCExpr::SymbolRef: {
981 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
983 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
984 TokError("invalid variant on expression '" + getTok().getIdentifier() +
985 "' (already modified)");
989 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
992 case MCExpr::Unary: {
993 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
994 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
997 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
1000 case MCExpr::Binary: {
1001 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1002 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1003 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1013 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1017 llvm_unreachable("Invalid expression kind!");
1020 /// \brief Parse an expression and return it.
1022 /// expr ::= expr &&,|| expr -> lowest.
1023 /// expr ::= expr |,^,&,! expr
1024 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1025 /// expr ::= expr <<,>> expr
1026 /// expr ::= expr +,- expr
1027 /// expr ::= expr *,/,% expr -> highest.
1028 /// expr ::= primaryexpr
1030 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1031 // Parse the expression.
1033 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1036 // As a special case, we support 'a op b @ modifier' by rewriting the
1037 // expression to include the modifier. This is inefficient, but in general we
1038 // expect users to use 'a@modifier op b'.
1039 if (Lexer.getKind() == AsmToken::At) {
1042 if (Lexer.isNot(AsmToken::Identifier))
1043 return TokError("unexpected symbol modifier following '@'");
1045 MCSymbolRefExpr::VariantKind Variant =
1046 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1047 if (Variant == MCSymbolRefExpr::VK_Invalid)
1048 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1050 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1052 return TokError("invalid modifier '" + getTok().getIdentifier() +
1053 "' (no symbols present)");
1060 // Try to constant fold it up front, if possible.
1062 if (Res->evaluateAsAbsolute(Value))
1063 Res = MCConstantExpr::create(Value, getContext());
1068 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1070 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1073 bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1075 if (parseParenExpr(Res, EndLoc))
1078 for (; ParenDepth > 0; --ParenDepth) {
1079 if (parseBinOpRHS(1, Res, EndLoc))
1082 // We don't Lex() the last RParen.
1083 // This is the same behavior as parseParenExpression().
1084 if (ParenDepth - 1 > 0) {
1085 if (Lexer.isNot(AsmToken::RParen))
1086 return TokError("expected ')' in parentheses expression");
1087 EndLoc = Lexer.getTok().getEndLoc();
1094 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1097 SMLoc StartLoc = Lexer.getLoc();
1098 if (parseExpression(Expr))
1101 if (!Expr->evaluateAsAbsolute(Res))
1102 return Error(StartLoc, "expected absolute expression");
1107 static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1108 MCBinaryExpr::Opcode &Kind,
1109 bool ShouldUseLogicalShr) {
1112 return 0; // not a binop.
1114 // Lowest Precedence: &&, ||
1115 case AsmToken::AmpAmp:
1116 Kind = MCBinaryExpr::LAnd;
1118 case AsmToken::PipePipe:
1119 Kind = MCBinaryExpr::LOr;
1122 // Low Precedence: |, &, ^
1124 // FIXME: gas seems to support '!' as an infix operator?
1125 case AsmToken::Pipe:
1126 Kind = MCBinaryExpr::Or;
1128 case AsmToken::Caret:
1129 Kind = MCBinaryExpr::Xor;
1132 Kind = MCBinaryExpr::And;
1135 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1136 case AsmToken::EqualEqual:
1137 Kind = MCBinaryExpr::EQ;
1139 case AsmToken::ExclaimEqual:
1140 case AsmToken::LessGreater:
1141 Kind = MCBinaryExpr::NE;
1143 case AsmToken::Less:
1144 Kind = MCBinaryExpr::LT;
1146 case AsmToken::LessEqual:
1147 Kind = MCBinaryExpr::LTE;
1149 case AsmToken::Greater:
1150 Kind = MCBinaryExpr::GT;
1152 case AsmToken::GreaterEqual:
1153 Kind = MCBinaryExpr::GTE;
1156 // Intermediate Precedence: <<, >>
1157 case AsmToken::LessLess:
1158 Kind = MCBinaryExpr::Shl;
1160 case AsmToken::GreaterGreater:
1161 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1164 // High Intermediate Precedence: +, -
1165 case AsmToken::Plus:
1166 Kind = MCBinaryExpr::Add;
1168 case AsmToken::Minus:
1169 Kind = MCBinaryExpr::Sub;
1172 // Highest Precedence: *, /, %
1173 case AsmToken::Star:
1174 Kind = MCBinaryExpr::Mul;
1176 case AsmToken::Slash:
1177 Kind = MCBinaryExpr::Div;
1179 case AsmToken::Percent:
1180 Kind = MCBinaryExpr::Mod;
1185 static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1186 MCBinaryExpr::Opcode &Kind,
1187 bool ShouldUseLogicalShr) {
1190 return 0; // not a binop.
1192 // Lowest Precedence: &&, ||
1193 case AsmToken::AmpAmp:
1194 Kind = MCBinaryExpr::LAnd;
1196 case AsmToken::PipePipe:
1197 Kind = MCBinaryExpr::LOr;
1200 // Low Precedence: ==, !=, <>, <, <=, >, >=
1201 case AsmToken::EqualEqual:
1202 Kind = MCBinaryExpr::EQ;
1204 case AsmToken::ExclaimEqual:
1205 case AsmToken::LessGreater:
1206 Kind = MCBinaryExpr::NE;
1208 case AsmToken::Less:
1209 Kind = MCBinaryExpr::LT;
1211 case AsmToken::LessEqual:
1212 Kind = MCBinaryExpr::LTE;
1214 case AsmToken::Greater:
1215 Kind = MCBinaryExpr::GT;
1217 case AsmToken::GreaterEqual:
1218 Kind = MCBinaryExpr::GTE;
1221 // Low Intermediate Precedence: +, -
1222 case AsmToken::Plus:
1223 Kind = MCBinaryExpr::Add;
1225 case AsmToken::Minus:
1226 Kind = MCBinaryExpr::Sub;
1229 // High Intermediate Precedence: |, &, ^
1231 // FIXME: gas seems to support '!' as an infix operator?
1232 case AsmToken::Pipe:
1233 Kind = MCBinaryExpr::Or;
1235 case AsmToken::Caret:
1236 Kind = MCBinaryExpr::Xor;
1239 Kind = MCBinaryExpr::And;
1242 // Highest Precedence: *, /, %, <<, >>
1243 case AsmToken::Star:
1244 Kind = MCBinaryExpr::Mul;
1246 case AsmToken::Slash:
1247 Kind = MCBinaryExpr::Div;
1249 case AsmToken::Percent:
1250 Kind = MCBinaryExpr::Mod;
1252 case AsmToken::LessLess:
1253 Kind = MCBinaryExpr::Shl;
1255 case AsmToken::GreaterGreater:
1256 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1261 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1262 MCBinaryExpr::Opcode &Kind) {
1263 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1264 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1265 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1268 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1269 /// Res contains the LHS of the expression on input.
1270 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1273 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1274 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1276 // If the next token is lower precedence than we are allowed to eat, return
1277 // successfully with what we ate already.
1278 if (TokPrec < Precedence)
1283 // Eat the next primary expression.
1285 if (parsePrimaryExpr(RHS, EndLoc))
1288 // If BinOp binds less tightly with RHS than the operator after RHS, let
1289 // the pending operator take RHS as its LHS.
1290 MCBinaryExpr::Opcode Dummy;
1291 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1292 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1295 // Merge LHS and RHS according to operator.
1296 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
1301 /// ::= EndOfStatement
1302 /// ::= Label* Directive ...Operands... EndOfStatement
1303 /// ::= Label* Identifier OperandList* EndOfStatement
1304 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1305 MCAsmParserSemaCallback *SI) {
1306 if (Lexer.is(AsmToken::EndOfStatement)) {
1312 // Statements always start with an identifier or are a full line comment.
1313 AsmToken ID = getTok();
1314 SMLoc IDLoc = ID.getLoc();
1316 int64_t LocalLabelVal = -1;
1317 // A full line comment is a '#' as the first token.
1318 if (Lexer.is(AsmToken::Hash))
1319 return parseCppHashLineFilenameComment(IDLoc);
1321 // Allow an integer followed by a ':' as a directional local label.
1322 if (Lexer.is(AsmToken::Integer)) {
1323 LocalLabelVal = getTok().getIntVal();
1324 if (LocalLabelVal < 0) {
1325 if (!TheCondState.Ignore)
1326 return TokError("unexpected token at start of statement");
1329 IDVal = getTok().getString();
1330 Lex(); // Consume the integer token to be used as an identifier token.
1331 if (Lexer.getKind() != AsmToken::Colon) {
1332 if (!TheCondState.Ignore)
1333 return TokError("unexpected token at start of statement");
1336 } else if (Lexer.is(AsmToken::Dot)) {
1337 // Treat '.' as a valid identifier in this context.
1340 } else if (Lexer.is(AsmToken::LCurly)) {
1341 // Treat '{' as a valid identifier in this context.
1345 } else if (Lexer.is(AsmToken::RCurly)) {
1346 // Treat '}' as a valid identifier in this context.
1349 } else if (parseIdentifier(IDVal)) {
1350 if (!TheCondState.Ignore)
1351 return TokError("unexpected token at start of statement");
1355 // Handle conditional assembly here before checking for skipping. We
1356 // have to do this so that .endif isn't skipped in a ".if 0" block for
1358 StringMap<DirectiveKind>::const_iterator DirKindIt =
1359 DirectiveKindMap.find(IDVal);
1360 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1362 : DirKindIt->getValue();
1373 return parseDirectiveIf(IDLoc, DirKind);
1375 return parseDirectiveIfb(IDLoc, true);
1377 return parseDirectiveIfb(IDLoc, false);
1379 return parseDirectiveIfc(IDLoc, true);
1381 return parseDirectiveIfeqs(IDLoc, true);
1383 return parseDirectiveIfc(IDLoc, false);
1385 return parseDirectiveIfeqs(IDLoc, false);
1387 return parseDirectiveIfdef(IDLoc, true);
1390 return parseDirectiveIfdef(IDLoc, false);
1392 return parseDirectiveElseIf(IDLoc);
1394 return parseDirectiveElse(IDLoc);
1396 return parseDirectiveEndIf(IDLoc);
1399 // Ignore the statement if in the middle of inactive conditional
1401 if (TheCondState.Ignore) {
1402 eatToEndOfStatement();
1406 // FIXME: Recurse on local labels?
1408 // See what kind of statement we have.
1409 switch (Lexer.getKind()) {
1410 case AsmToken::Colon: {
1411 if (!getTargetParser().isLabel(ID))
1413 checkForValidSection();
1415 // identifier ':' -> Label.
1418 // Diagnose attempt to use '.' as a label.
1420 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1422 // Diagnose attempt to use a variable as a label.
1424 // FIXME: Diagnostics. Note the location of the definition as a label.
1425 // FIXME: This doesn't diagnose assignment to a symbol which has been
1426 // implicitly marked as external.
1428 if (LocalLabelVal == -1) {
1429 if (ParsingInlineAsm && SI) {
1430 StringRef RewrittenLabel =
1431 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1432 assert(RewrittenLabel.size() &&
1433 "We should have an internal name here.");
1434 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1436 IDVal = RewrittenLabel;
1438 Sym = getContext().getOrCreateSymbol(IDVal);
1440 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1442 Sym->redefineIfPossible();
1444 if (!Sym->isUndefined() || Sym->isVariable())
1445 return Error(IDLoc, "invalid symbol redefinition");
1448 if (!ParsingInlineAsm)
1451 // If we are generating dwarf for assembly source files then gather the
1452 // info to make a dwarf label entry for this label if needed.
1453 if (getContext().getGenDwarfForAssembly())
1454 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1457 getTargetParser().onLabelParsed(Sym);
1459 // Consume any end of statement token, if present, to avoid spurious
1460 // AddBlankLine calls().
1461 if (Lexer.is(AsmToken::EndOfStatement)) {
1463 if (Lexer.is(AsmToken::Eof))
1470 case AsmToken::Equal:
1471 if (!getTargetParser().equalIsAsmAssignment())
1473 // identifier '=' ... -> assignment statement
1476 return parseAssignment(IDVal, true);
1478 default: // Normal instruction or directive.
1482 // If macros are enabled, check to see if this is a macro instantiation.
1483 if (areMacrosEnabled())
1484 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1485 return handleMacroEntry(M, IDLoc);
1488 // Otherwise, we have a normal instruction or directive.
1490 // Directives start with "."
1491 if (IDVal[0] == '.' && IDVal != ".") {
1492 // There are several entities interested in parsing directives:
1494 // 1. The target-specific assembly parser. Some directives are target
1495 // specific or may potentially behave differently on certain targets.
1496 // 2. Asm parser extensions. For example, platform-specific parsers
1497 // (like the ELF parser) register themselves as extensions.
1498 // 3. The generic directive parser implemented by this class. These are
1499 // all the directives that behave in a target and platform independent
1500 // manner, or at least have a default behavior that's shared between
1501 // all targets and platforms.
1503 // First query the target-specific parser. It will return 'true' if it
1504 // isn't interested in this directive.
1505 if (!getTargetParser().ParseDirective(ID))
1508 // Next, check the extension directive map to see if any extension has
1509 // registered itself to parse this directive.
1510 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1511 ExtensionDirectiveMap.lookup(IDVal);
1513 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1515 // Finally, if no one else is interested in this directive, it must be
1516 // generic and familiar to this class.
1522 return parseDirectiveSet(IDVal, true);
1524 return parseDirectiveSet(IDVal, false);
1526 return parseDirectiveAscii(IDVal, false);
1529 return parseDirectiveAscii(IDVal, true);
1531 return parseDirectiveValue(1);
1535 return parseDirectiveValue(2);
1539 return parseDirectiveValue(4);
1542 return parseDirectiveValue(8);
1544 return parseDirectiveOctaValue();
1547 return parseDirectiveRealValue(APFloat::IEEEsingle);
1549 return parseDirectiveRealValue(APFloat::IEEEdouble);
1551 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1552 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1555 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1556 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1559 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1561 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1563 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1565 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1567 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1569 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1571 return parseDirectiveOrg();
1573 return parseDirectiveFill();
1575 return parseDirectiveZero();
1577 eatToEndOfStatement(); // .extern is the default, ignore it.
1581 return parseDirectiveSymbolAttribute(MCSA_Global);
1582 case DK_LAZY_REFERENCE:
1583 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1584 case DK_NO_DEAD_STRIP:
1585 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1586 case DK_SYMBOL_RESOLVER:
1587 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1588 case DK_PRIVATE_EXTERN:
1589 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1591 return parseDirectiveSymbolAttribute(MCSA_Reference);
1592 case DK_WEAK_DEFINITION:
1593 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1594 case DK_WEAK_REFERENCE:
1595 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1596 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1597 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1600 return parseDirectiveComm(/*IsLocal=*/false);
1602 return parseDirectiveComm(/*IsLocal=*/true);
1604 return parseDirectiveAbort();
1606 return parseDirectiveInclude();
1608 return parseDirectiveIncbin();
1611 return TokError(Twine(IDVal) + " not supported yet");
1613 return parseDirectiveRept(IDLoc, IDVal);
1615 return parseDirectiveIrp(IDLoc);
1617 return parseDirectiveIrpc(IDLoc);
1619 return parseDirectiveEndr(IDLoc);
1620 case DK_BUNDLE_ALIGN_MODE:
1621 return parseDirectiveBundleAlignMode();
1622 case DK_BUNDLE_LOCK:
1623 return parseDirectiveBundleLock();
1624 case DK_BUNDLE_UNLOCK:
1625 return parseDirectiveBundleUnlock();
1627 return parseDirectiveLEB128(true);
1629 return parseDirectiveLEB128(false);
1632 return parseDirectiveSpace(IDVal);
1634 return parseDirectiveFile(IDLoc);
1636 return parseDirectiveLine();
1638 return parseDirectiveLoc();
1640 return parseDirectiveStabs();
1641 case DK_CFI_SECTIONS:
1642 return parseDirectiveCFISections();
1643 case DK_CFI_STARTPROC:
1644 return parseDirectiveCFIStartProc();
1645 case DK_CFI_ENDPROC:
1646 return parseDirectiveCFIEndProc();
1647 case DK_CFI_DEF_CFA:
1648 return parseDirectiveCFIDefCfa(IDLoc);
1649 case DK_CFI_DEF_CFA_OFFSET:
1650 return parseDirectiveCFIDefCfaOffset();
1651 case DK_CFI_ADJUST_CFA_OFFSET:
1652 return parseDirectiveCFIAdjustCfaOffset();
1653 case DK_CFI_DEF_CFA_REGISTER:
1654 return parseDirectiveCFIDefCfaRegister(IDLoc);
1656 return parseDirectiveCFIOffset(IDLoc);
1657 case DK_CFI_REL_OFFSET:
1658 return parseDirectiveCFIRelOffset(IDLoc);
1659 case DK_CFI_PERSONALITY:
1660 return parseDirectiveCFIPersonalityOrLsda(true);
1662 return parseDirectiveCFIPersonalityOrLsda(false);
1663 case DK_CFI_REMEMBER_STATE:
1664 return parseDirectiveCFIRememberState();
1665 case DK_CFI_RESTORE_STATE:
1666 return parseDirectiveCFIRestoreState();
1667 case DK_CFI_SAME_VALUE:
1668 return parseDirectiveCFISameValue(IDLoc);
1669 case DK_CFI_RESTORE:
1670 return parseDirectiveCFIRestore(IDLoc);
1672 return parseDirectiveCFIEscape();
1673 case DK_CFI_SIGNAL_FRAME:
1674 return parseDirectiveCFISignalFrame();
1675 case DK_CFI_UNDEFINED:
1676 return parseDirectiveCFIUndefined(IDLoc);
1677 case DK_CFI_REGISTER:
1678 return parseDirectiveCFIRegister(IDLoc);
1679 case DK_CFI_WINDOW_SAVE:
1680 return parseDirectiveCFIWindowSave();
1683 return parseDirectiveMacrosOnOff(IDVal);
1685 return parseDirectiveMacro(IDLoc);
1687 return parseDirectiveExitMacro(IDVal);
1690 return parseDirectiveEndMacro(IDVal);
1692 return parseDirectivePurgeMacro(IDLoc);
1694 return parseDirectiveEnd(IDLoc);
1696 return parseDirectiveError(IDLoc, false);
1698 return parseDirectiveError(IDLoc, true);
1700 return parseDirectiveWarning(IDLoc);
1702 return parseDirectiveReloc(IDLoc);
1705 return Error(IDLoc, "unknown directive");
1708 // __asm _emit or __asm __emit
1709 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1710 IDVal == "_EMIT" || IDVal == "__EMIT"))
1711 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1714 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1715 return parseDirectiveMSAlign(IDLoc, Info);
1717 if (ParsingInlineAsm && (IDVal == "even"))
1718 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
1719 checkForValidSection();
1721 // Canonicalize the opcode to lower case.
1722 std::string OpcodeStr = IDVal.lower();
1723 ParseInstructionInfo IInfo(Info.AsmRewrites);
1724 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
1725 Info.ParsedOperands);
1726 Info.ParseError = HadError;
1728 // Dump the parsed representation, if requested.
1729 if (getShowParsedOperands()) {
1730 SmallString<256> Str;
1731 raw_svector_ostream OS(Str);
1732 OS << "parsed instruction: [";
1733 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1736 Info.ParsedOperands[i]->print(OS);
1740 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1743 // If we are generating dwarf for the current section then generate a .loc
1744 // directive for the instruction.
1745 if (!HadError && getContext().getGenDwarfForAssembly() &&
1746 getContext().getGenDwarfSectionSyms().count(
1747 getStreamer().getCurrentSection().first)) {
1749 if (ActiveMacros.empty())
1750 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1752 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
1753 ActiveMacros.front()->ExitBuffer);
1755 // If we previously parsed a cpp hash file line comment then make sure the
1756 // current Dwarf File is for the CppHashFilename if not then emit the
1757 // Dwarf File table for it and adjust the line number for the .loc.
1758 if (CppHashFilename.size()) {
1759 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1760 0, StringRef(), CppHashFilename);
1761 getContext().setGenDwarfFileNumber(FileNumber);
1763 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1764 // cache with the different Loc from the call above we save the last
1765 // info we queried here with SrcMgr.FindLineNumber().
1766 unsigned CppHashLocLineNo;
1767 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1768 CppHashLocLineNo = LastQueryLine;
1770 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1771 LastQueryLine = CppHashLocLineNo;
1772 LastQueryIDLoc = CppHashLoc;
1773 LastQueryBuffer = CppHashBuf;
1775 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1778 getStreamer().EmitDwarfLocDirective(
1779 getContext().getGenDwarfFileNumber(), Line, 0,
1780 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1784 // If parsing succeeded, match the instruction.
1787 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1788 Info.ParsedOperands, Out,
1789 ErrorInfo, ParsingInlineAsm);
1792 // Don't skip the rest of the line, the instruction parser is responsible for
1797 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1798 /// since they may not be able to be tokenized to get to the end of line token.
1799 void AsmParser::eatToEndOfLine() {
1800 if (!Lexer.is(AsmToken::EndOfStatement))
1801 Lexer.LexUntilEndOfLine();
1806 /// parseCppHashLineFilenameComment as this:
1807 /// ::= # number "filename"
1808 /// or just as a full line comment if it doesn't have a number and a string.
1809 bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
1810 Lex(); // Eat the hash token.
1812 if (getLexer().isNot(AsmToken::Integer)) {
1813 // Consume the line since in cases it is not a well-formed line directive,
1814 // as if were simply a full line comment.
1819 int64_t LineNumber = getTok().getIntVal();
1822 if (getLexer().isNot(AsmToken::String)) {
1827 StringRef Filename = getTok().getString();
1828 // Get rid of the enclosing quotes.
1829 Filename = Filename.substr(1, Filename.size() - 2);
1831 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1833 CppHashFilename = Filename;
1834 CppHashLineNumber = LineNumber;
1835 CppHashBuf = CurBuffer;
1837 // Ignore any trailing characters, they're just comment.
1842 /// \brief will use the last parsed cpp hash line filename comment
1843 /// for the Filename and LineNo if any in the diagnostic.
1844 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1845 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1846 raw_ostream &OS = errs();
1848 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1849 SMLoc DiagLoc = Diag.getLoc();
1850 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1851 unsigned CppHashBuf =
1852 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1854 // Like SourceMgr::printMessage() we need to print the include stack if any
1855 // before printing the message.
1856 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1857 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1858 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
1859 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1860 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1863 // If we have not parsed a cpp hash line filename comment or the source
1864 // manager changed or buffer changed (like in a nested include) then just
1865 // print the normal diagnostic using its Filename and LineNo.
1866 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1867 DiagBuf != CppHashBuf) {
1868 if (Parser->SavedDiagHandler)
1869 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1871 Diag.print(nullptr, OS);
1875 // Use the CppHashFilename and calculate a line number based on the
1876 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1878 const std::string &Filename = Parser->CppHashFilename;
1880 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1881 int CppHashLocLineNo =
1882 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1884 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1886 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1887 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1888 Diag.getLineContents(), Diag.getRanges());
1890 if (Parser->SavedDiagHandler)
1891 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1893 NewDiag.print(nullptr, OS);
1896 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1897 // difference being that that function accepts '@' as part of identifiers and
1898 // we can't do that. AsmLexer.cpp should probably be changed to handle
1899 // '@' as a special case when needed.
1900 static bool isIdentifierChar(char c) {
1901 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1905 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1906 ArrayRef<MCAsmMacroParameter> Parameters,
1907 ArrayRef<MCAsmMacroArgument> A,
1908 bool EnableAtPseudoVariable, SMLoc L) {
1909 unsigned NParameters = Parameters.size();
1910 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1911 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1912 return Error(L, "Wrong number of arguments");
1914 // A macro without parameters is handled differently on Darwin:
1915 // gas accepts no arguments and does no substitutions
1916 while (!Body.empty()) {
1917 // Scan for the next substitution.
1918 std::size_t End = Body.size(), Pos = 0;
1919 for (; Pos != End; ++Pos) {
1920 // Check for a substitution or escape.
1921 if (IsDarwin && !NParameters) {
1922 // This macro has no parameters, look for $0, $1, etc.
1923 if (Body[Pos] != '$' || Pos + 1 == End)
1926 char Next = Body[Pos + 1];
1927 if (Next == '$' || Next == 'n' ||
1928 isdigit(static_cast<unsigned char>(Next)))
1931 // This macro has parameters, look for \foo, \bar, etc.
1932 if (Body[Pos] == '\\' && Pos + 1 != End)
1938 OS << Body.slice(0, Pos);
1940 // Check if we reached the end.
1944 if (IsDarwin && !NParameters) {
1945 switch (Body[Pos + 1]) {
1951 // $n => number of arguments
1956 // $[0-9] => argument
1958 // Missing arguments are ignored.
1959 unsigned Index = Body[Pos + 1] - '0';
1960 if (Index >= A.size())
1963 // Otherwise substitute with the token values, with spaces eliminated.
1964 for (const AsmToken &Token : A[Index])
1965 OS << Token.getString();
1971 unsigned I = Pos + 1;
1973 // Check for the \@ pseudo-variable.
1974 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
1977 while (isIdentifierChar(Body[I]) && I + 1 != End)
1980 const char *Begin = Body.data() + Pos + 1;
1981 StringRef Argument(Begin, I - (Pos + 1));
1984 if (Argument == "@") {
1985 OS << NumOfMacroInstantiations;
1988 for (; Index < NParameters; ++Index)
1989 if (Parameters[Index].Name == Argument)
1992 if (Index == NParameters) {
1993 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1996 OS << '\\' << Argument;
2000 bool VarargParameter = HasVararg && Index == (NParameters - 1);
2001 for (const AsmToken &Token : A[Index])
2002 // We expect no quotes around the string's contents when
2003 // parsing for varargs.
2004 if (Token.getKind() != AsmToken::String || VarargParameter)
2005 OS << Token.getString();
2007 OS << Token.getStringContents();
2009 Pos += 1 + Argument.size();
2013 // Update the scan point.
2014 Body = Body.substr(Pos);
2020 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
2021 size_t CondStackDepth)
2022 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
2023 CondStackDepth(CondStackDepth) {}
2025 static bool isOperator(AsmToken::TokenKind kind) {
2029 case AsmToken::Plus:
2030 case AsmToken::Minus:
2031 case AsmToken::Tilde:
2032 case AsmToken::Slash:
2033 case AsmToken::Star:
2035 case AsmToken::Equal:
2036 case AsmToken::EqualEqual:
2037 case AsmToken::Pipe:
2038 case AsmToken::PipePipe:
2039 case AsmToken::Caret:
2041 case AsmToken::AmpAmp:
2042 case AsmToken::Exclaim:
2043 case AsmToken::ExclaimEqual:
2044 case AsmToken::Percent:
2045 case AsmToken::Less:
2046 case AsmToken::LessEqual:
2047 case AsmToken::LessLess:
2048 case AsmToken::LessGreater:
2049 case AsmToken::Greater:
2050 case AsmToken::GreaterEqual:
2051 case AsmToken::GreaterGreater:
2057 class AsmLexerSkipSpaceRAII {
2059 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2060 Lexer.setSkipSpace(SkipSpace);
2063 ~AsmLexerSkipSpaceRAII() {
2064 Lexer.setSkipSpace(true);
2072 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2075 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2076 StringRef Str = parseStringToEndOfStatement();
2077 MA.emplace_back(AsmToken::String, Str);
2082 unsigned ParenLevel = 0;
2083 unsigned AddTokens = 0;
2085 // Darwin doesn't use spaces to delmit arguments.
2086 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
2089 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
2090 return TokError("unexpected token in macro instantiation");
2092 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
2095 if (Lexer.is(AsmToken::Space)) {
2096 Lex(); // Eat spaces
2098 // Spaces can delimit parameters, but could also be part an expression.
2099 // If the token after a space is an operator, add the token and the next
2100 // one into this argument
2102 if (isOperator(Lexer.getKind())) {
2103 // Check to see whether the token is used as an operator,
2104 // or part of an identifier
2105 const char *NextChar = getTok().getEndLoc().getPointer();
2106 if (*NextChar == ' ')
2110 if (!AddTokens && ParenLevel == 0) {
2116 // handleMacroEntry relies on not advancing the lexer here
2117 // to be able to fill in the remaining default parameter values
2118 if (Lexer.is(AsmToken::EndOfStatement))
2121 // Adjust the current parentheses level.
2122 if (Lexer.is(AsmToken::LParen))
2124 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2127 // Append the token to the current argument list.
2128 MA.push_back(getTok());
2134 if (ParenLevel != 0)
2135 return TokError("unbalanced parentheses in macro argument");
2139 // Parse the macro instantiation arguments.
2140 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2141 MCAsmMacroArguments &A) {
2142 const unsigned NParameters = M ? M->Parameters.size() : 0;
2143 bool NamedParametersFound = false;
2144 SmallVector<SMLoc, 4> FALocs;
2146 A.resize(NParameters);
2147 FALocs.resize(NParameters);
2149 // Parse two kinds of macro invocations:
2150 // - macros defined without any parameters accept an arbitrary number of them
2151 // - macros defined with parameters accept at most that many of them
2152 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2153 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2155 SMLoc IDLoc = Lexer.getLoc();
2156 MCAsmMacroParameter FA;
2158 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2159 if (parseIdentifier(FA.Name)) {
2160 Error(IDLoc, "invalid argument identifier for formal argument");
2161 eatToEndOfStatement();
2165 if (!Lexer.is(AsmToken::Equal)) {
2166 TokError("expected '=' after formal parameter identifier");
2167 eatToEndOfStatement();
2172 NamedParametersFound = true;
2175 if (NamedParametersFound && FA.Name.empty()) {
2176 Error(IDLoc, "cannot mix positional and keyword arguments");
2177 eatToEndOfStatement();
2181 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2182 if (parseMacroArgument(FA.Value, Vararg))
2185 unsigned PI = Parameter;
2186 if (!FA.Name.empty()) {
2188 for (FAI = 0; FAI < NParameters; ++FAI)
2189 if (M->Parameters[FAI].Name == FA.Name)
2192 if (FAI >= NParameters) {
2193 assert(M && "expected macro to be defined");
2195 "parameter named '" + FA.Name + "' does not exist for macro '" +
2202 if (!FA.Value.empty()) {
2207 if (FALocs.size() <= PI)
2208 FALocs.resize(PI + 1);
2210 FALocs[PI] = Lexer.getLoc();
2213 // At the end of the statement, fill in remaining arguments that have
2214 // default values. If there aren't any, then the next argument is
2215 // required but missing
2216 if (Lexer.is(AsmToken::EndOfStatement)) {
2217 bool Failure = false;
2218 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2219 if (A[FAI].empty()) {
2220 if (M->Parameters[FAI].Required) {
2221 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2222 "missing value for required parameter "
2223 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2227 if (!M->Parameters[FAI].Value.empty())
2228 A[FAI] = M->Parameters[FAI].Value;
2234 if (Lexer.is(AsmToken::Comma))
2238 return TokError("too many positional arguments");
2241 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2242 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2243 return (I == MacroMap.end()) ? nullptr : &I->getValue();
2246 void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2247 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2250 void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2252 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2253 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2254 // this, although we should protect against infinite loops.
2255 if (ActiveMacros.size() == 20)
2256 return TokError("macros cannot be nested more than 20 levels deep");
2258 MCAsmMacroArguments A;
2259 if (parseMacroArguments(M, A))
2262 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2263 // to hold the macro body with substitutions.
2264 SmallString<256> Buf;
2265 StringRef Body = M->Body;
2266 raw_svector_ostream OS(Buf);
2268 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2271 // We include the .endmacro in the buffer as our cue to exit the macro
2273 OS << ".endmacro\n";
2275 std::unique_ptr<MemoryBuffer> Instantiation =
2276 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2278 // Create the macro instantiation object and add to the current macro
2279 // instantiation stack.
2280 MacroInstantiation *MI = new MacroInstantiation(
2281 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2282 ActiveMacros.push_back(MI);
2284 ++NumOfMacroInstantiations;
2286 // Jump to the macro instantiation and prime the lexer.
2287 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2288 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2294 void AsmParser::handleMacroExit() {
2295 // Jump to the EndOfStatement we should return to, and consume it.
2296 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2299 // Pop the instantiation entry.
2300 delete ActiveMacros.back();
2301 ActiveMacros.pop_back();
2304 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2307 const MCExpr *Value;
2308 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2313 // In the case where we parse an expression starting with a '.', we will
2314 // not generate an error, nor will we create a symbol. In this case we
2315 // should just return out.
2319 // Do the assignment.
2320 Out.EmitAssignment(Sym, Value);
2322 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2327 /// parseIdentifier:
2330 bool AsmParser::parseIdentifier(StringRef &Res) {
2331 // The assembler has relaxed rules for accepting identifiers, in particular we
2332 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2333 // separate tokens. At this level, we have already lexed so we cannot (currently)
2334 // handle this as a context dependent token, instead we detect adjacent tokens
2335 // and return the combined identifier.
2336 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2337 SMLoc PrefixLoc = getLexer().getLoc();
2339 // Consume the prefix character, and check for a following identifier.
2341 if (Lexer.isNot(AsmToken::Identifier))
2344 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2345 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2348 // Construct the joined identifier and consume the token.
2350 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2355 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2358 Res = getTok().getIdentifier();
2360 Lex(); // Consume the identifier token.
2365 /// parseDirectiveSet:
2366 /// ::= .equ identifier ',' expression
2367 /// ::= .equiv identifier ',' expression
2368 /// ::= .set identifier ',' expression
2369 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2372 if (parseIdentifier(Name))
2373 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2375 if (getLexer().isNot(AsmToken::Comma))
2376 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2379 return parseAssignment(Name, allow_redef, true);
2382 bool AsmParser::parseEscapedString(std::string &Data) {
2383 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2386 StringRef Str = getTok().getStringContents();
2387 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2388 if (Str[i] != '\\') {
2393 // Recognize escaped characters. Note that this escape semantics currently
2394 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2397 return TokError("unexpected backslash at end of string");
2399 // Recognize octal sequences.
2400 if ((unsigned)(Str[i] - '0') <= 7) {
2401 // Consume up to three octal characters.
2402 unsigned Value = Str[i] - '0';
2404 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2406 Value = Value * 8 + (Str[i] - '0');
2408 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2410 Value = Value * 8 + (Str[i] - '0');
2415 return TokError("invalid octal escape sequence (out of range)");
2417 Data += (unsigned char)Value;
2421 // Otherwise recognize individual escapes.
2424 // Just reject invalid escape sequences for now.
2425 return TokError("invalid escape sequence (unrecognized character)");
2427 case 'b': Data += '\b'; break;
2428 case 'f': Data += '\f'; break;
2429 case 'n': Data += '\n'; break;
2430 case 'r': Data += '\r'; break;
2431 case 't': Data += '\t'; break;
2432 case '"': Data += '"'; break;
2433 case '\\': Data += '\\'; break;
2440 /// parseDirectiveAscii:
2441 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2442 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2443 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2444 checkForValidSection();
2447 if (getLexer().isNot(AsmToken::String))
2448 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2451 if (parseEscapedString(Data))
2454 getStreamer().EmitBytes(Data);
2456 getStreamer().EmitBytes(StringRef("\0", 1));
2460 if (getLexer().is(AsmToken::EndOfStatement))
2463 if (getLexer().isNot(AsmToken::Comma))
2464 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2473 /// parseDirectiveReloc
2474 /// ::= .reloc expression , identifier [ , expression ]
2475 bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2476 const MCExpr *Offset;
2477 const MCExpr *Expr = nullptr;
2479 SMLoc OffsetLoc = Lexer.getTok().getLoc();
2480 if (parseExpression(Offset))
2483 // We can only deal with constant expressions at the moment.
2484 int64_t OffsetValue;
2485 if (!Offset->evaluateAsAbsolute(OffsetValue))
2486 return Error(OffsetLoc, "expression is not a constant value");
2488 if (Lexer.isNot(AsmToken::Comma))
2489 return TokError("expected comma");
2492 if (Lexer.isNot(AsmToken::Identifier))
2493 return TokError("expected relocation name");
2494 SMLoc NameLoc = Lexer.getTok().getLoc();
2495 StringRef Name = Lexer.getTok().getIdentifier();
2498 if (Lexer.is(AsmToken::Comma)) {
2500 SMLoc ExprLoc = Lexer.getLoc();
2501 if (parseExpression(Expr))
2505 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2506 return Error(ExprLoc, "expression must be relocatable");
2509 if (Lexer.isNot(AsmToken::EndOfStatement))
2510 return TokError("unexpected token in .reloc directive");
2512 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2513 return Error(NameLoc, "unknown relocation name");
2518 /// parseDirectiveValue
2519 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2520 bool AsmParser::parseDirectiveValue(unsigned Size) {
2521 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2522 checkForValidSection();
2525 const MCExpr *Value;
2526 SMLoc ExprLoc = getLexer().getLoc();
2527 if (parseExpression(Value))
2530 // Special case constant expressions to match code generator.
2531 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2532 assert(Size <= 8 && "Invalid size");
2533 uint64_t IntValue = MCE->getValue();
2534 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2535 return Error(ExprLoc, "literal value out of range for directive");
2536 getStreamer().EmitIntValue(IntValue, Size);
2538 getStreamer().EmitValue(Value, Size, ExprLoc);
2540 if (getLexer().is(AsmToken::EndOfStatement))
2543 // FIXME: Improve diagnostic.
2544 if (getLexer().isNot(AsmToken::Comma))
2545 return TokError("unexpected token in directive");
2554 /// ParseDirectiveOctaValue
2555 /// ::= .octa [ hexconstant (, hexconstant)* ]
2556 bool AsmParser::parseDirectiveOctaValue() {
2557 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2558 checkForValidSection();
2561 if (Lexer.getKind() == AsmToken::Error)
2563 if (Lexer.getKind() != AsmToken::Integer &&
2564 Lexer.getKind() != AsmToken::BigNum)
2565 return TokError("unknown token in expression");
2567 SMLoc ExprLoc = getLexer().getLoc();
2568 APInt IntValue = getTok().getAPIntVal();
2572 if (IntValue.isIntN(64)) {
2574 lo = IntValue.getZExtValue();
2575 } else if (IntValue.isIntN(128)) {
2576 // It might actually have more than 128 bits, but the top ones are zero.
2577 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2578 lo = IntValue.getLoBits(64).getZExtValue();
2580 return Error(ExprLoc, "literal value out of range for directive");
2582 if (MAI.isLittleEndian()) {
2583 getStreamer().EmitIntValue(lo, 8);
2584 getStreamer().EmitIntValue(hi, 8);
2586 getStreamer().EmitIntValue(hi, 8);
2587 getStreamer().EmitIntValue(lo, 8);
2590 if (getLexer().is(AsmToken::EndOfStatement))
2593 // FIXME: Improve diagnostic.
2594 if (getLexer().isNot(AsmToken::Comma))
2595 return TokError("unexpected token in directive");
2604 /// parseDirectiveRealValue
2605 /// ::= (.single | .double) [ expression (, expression)* ]
2606 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2607 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2608 checkForValidSection();
2611 // We don't truly support arithmetic on floating point expressions, so we
2612 // have to manually parse unary prefixes.
2614 if (getLexer().is(AsmToken::Minus)) {
2617 } else if (getLexer().is(AsmToken::Plus))
2620 if (getLexer().isNot(AsmToken::Integer) &&
2621 getLexer().isNot(AsmToken::Real) &&
2622 getLexer().isNot(AsmToken::Identifier))
2623 return TokError("unexpected token in directive");
2625 // Convert to an APFloat.
2626 APFloat Value(Semantics);
2627 StringRef IDVal = getTok().getString();
2628 if (getLexer().is(AsmToken::Identifier)) {
2629 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2630 Value = APFloat::getInf(Semantics);
2631 else if (!IDVal.compare_lower("nan"))
2632 Value = APFloat::getNaN(Semantics, false, ~0);
2634 return TokError("invalid floating point literal");
2635 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2636 APFloat::opInvalidOp)
2637 return TokError("invalid floating point literal");
2641 // Consume the numeric token.
2644 // Emit the value as an integer.
2645 APInt AsInt = Value.bitcastToAPInt();
2646 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2647 AsInt.getBitWidth() / 8);
2649 if (getLexer().is(AsmToken::EndOfStatement))
2652 if (getLexer().isNot(AsmToken::Comma))
2653 return TokError("unexpected token in directive");
2662 /// parseDirectiveZero
2663 /// ::= .zero expression
2664 bool AsmParser::parseDirectiveZero() {
2665 checkForValidSection();
2668 if (parseAbsoluteExpression(NumBytes))
2672 if (getLexer().is(AsmToken::Comma)) {
2674 if (parseAbsoluteExpression(Val))
2678 if (getLexer().isNot(AsmToken::EndOfStatement))
2679 return TokError("unexpected token in '.zero' directive");
2683 getStreamer().EmitFill(NumBytes, Val);
2688 /// parseDirectiveFill
2689 /// ::= .fill expression [ , expression [ , expression ] ]
2690 bool AsmParser::parseDirectiveFill() {
2691 checkForValidSection();
2693 SMLoc RepeatLoc = getLexer().getLoc();
2695 if (parseAbsoluteExpression(NumValues))
2698 if (NumValues < 0) {
2700 "'.fill' directive with negative repeat count has no effect");
2704 int64_t FillSize = 1;
2705 int64_t FillExpr = 0;
2707 SMLoc SizeLoc, ExprLoc;
2708 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2709 if (getLexer().isNot(AsmToken::Comma))
2710 return TokError("unexpected token in '.fill' directive");
2713 SizeLoc = getLexer().getLoc();
2714 if (parseAbsoluteExpression(FillSize))
2717 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2718 if (getLexer().isNot(AsmToken::Comma))
2719 return TokError("unexpected token in '.fill' directive");
2722 ExprLoc = getLexer().getLoc();
2723 if (parseAbsoluteExpression(FillExpr))
2726 if (getLexer().isNot(AsmToken::EndOfStatement))
2727 return TokError("unexpected token in '.fill' directive");
2734 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2738 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2742 if (!isUInt<32>(FillExpr) && FillSize > 4)
2743 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2745 if (NumValues > 0) {
2746 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2747 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2748 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2749 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2750 if (NonZeroFillSize < FillSize)
2751 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2758 /// parseDirectiveOrg
2759 /// ::= .org expression [ , expression ]
2760 bool AsmParser::parseDirectiveOrg() {
2761 checkForValidSection();
2763 const MCExpr *Offset;
2764 if (parseExpression(Offset))
2767 // Parse optional fill expression.
2768 int64_t FillExpr = 0;
2769 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2770 if (getLexer().isNot(AsmToken::Comma))
2771 return TokError("unexpected token in '.org' directive");
2774 if (parseAbsoluteExpression(FillExpr))
2777 if (getLexer().isNot(AsmToken::EndOfStatement))
2778 return TokError("unexpected token in '.org' directive");
2782 getStreamer().emitValueToOffset(Offset, FillExpr);
2786 /// parseDirectiveAlign
2787 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2788 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2789 checkForValidSection();
2791 SMLoc AlignmentLoc = getLexer().getLoc();
2793 if (parseAbsoluteExpression(Alignment))
2797 bool HasFillExpr = false;
2798 int64_t FillExpr = 0;
2799 int64_t MaxBytesToFill = 0;
2800 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2801 if (getLexer().isNot(AsmToken::Comma))
2802 return TokError("unexpected token in directive");
2805 // The fill expression can be omitted while specifying a maximum number of
2806 // alignment bytes, e.g:
2808 if (getLexer().isNot(AsmToken::Comma)) {
2810 if (parseAbsoluteExpression(FillExpr))
2814 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2815 if (getLexer().isNot(AsmToken::Comma))
2816 return TokError("unexpected token in directive");
2819 MaxBytesLoc = getLexer().getLoc();
2820 if (parseAbsoluteExpression(MaxBytesToFill))
2823 if (getLexer().isNot(AsmToken::EndOfStatement))
2824 return TokError("unexpected token in directive");
2833 // Compute alignment in bytes.
2835 // FIXME: Diagnose overflow.
2836 if (Alignment >= 32) {
2837 Error(AlignmentLoc, "invalid alignment value");
2841 Alignment = 1ULL << Alignment;
2843 // Reject alignments that aren't either a power of two or zero,
2844 // for gas compatibility. Alignment of zero is silently rounded
2848 if (!isPowerOf2_64(Alignment))
2849 Error(AlignmentLoc, "alignment must be a power of 2");
2852 // Diagnose non-sensical max bytes to align.
2853 if (MaxBytesLoc.isValid()) {
2854 if (MaxBytesToFill < 1) {
2855 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2856 "many bytes, ignoring maximum bytes expression");
2860 if (MaxBytesToFill >= Alignment) {
2861 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2867 // Check whether we should use optimal code alignment for this .align
2869 const MCSection *Section = getStreamer().getCurrentSection().first;
2870 assert(Section && "must have section to emit alignment");
2871 bool UseCodeAlign = Section->UseCodeAlign();
2872 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2873 ValueSize == 1 && UseCodeAlign) {
2874 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2876 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2877 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2884 /// parseDirectiveFile
2885 /// ::= .file [number] filename
2886 /// ::= .file number directory filename
2887 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2888 // FIXME: I'm not sure what this is.
2889 int64_t FileNumber = -1;
2890 SMLoc FileNumberLoc = getLexer().getLoc();
2891 if (getLexer().is(AsmToken::Integer)) {
2892 FileNumber = getTok().getIntVal();
2896 return TokError("file number less than one");
2899 if (getLexer().isNot(AsmToken::String))
2900 return TokError("unexpected token in '.file' directive");
2902 // Usually the directory and filename together, otherwise just the directory.
2903 // Allow the strings to have escaped octal character sequence.
2904 std::string Path = getTok().getString();
2905 if (parseEscapedString(Path))
2909 StringRef Directory;
2911 std::string FilenameData;
2912 if (getLexer().is(AsmToken::String)) {
2913 if (FileNumber == -1)
2914 return TokError("explicit path specified, but no file number");
2915 if (parseEscapedString(FilenameData))
2917 Filename = FilenameData;
2924 if (getLexer().isNot(AsmToken::EndOfStatement))
2925 return TokError("unexpected token in '.file' directive");
2927 if (FileNumber == -1)
2928 getStreamer().EmitFileDirective(Filename);
2930 if (getContext().getGenDwarfForAssembly())
2932 "input can't have .file dwarf directives when -g is "
2933 "used to generate dwarf debug info for assembly code");
2935 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2937 Error(FileNumberLoc, "file number already allocated");
2943 /// parseDirectiveLine
2944 /// ::= .line [number]
2945 bool AsmParser::parseDirectiveLine() {
2946 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2947 if (getLexer().isNot(AsmToken::Integer))
2948 return TokError("unexpected token in '.line' directive");
2950 int64_t LineNumber = getTok().getIntVal();
2954 // FIXME: Do something with the .line.
2957 if (getLexer().isNot(AsmToken::EndOfStatement))
2958 return TokError("unexpected token in '.line' directive");
2963 /// parseDirectiveLoc
2964 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2965 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2966 /// The first number is a file number, must have been previously assigned with
2967 /// a .file directive, the second number is the line number and optionally the
2968 /// third number is a column position (zero if not specified). The remaining
2969 /// optional items are .loc sub-directives.
2970 bool AsmParser::parseDirectiveLoc() {
2971 if (getLexer().isNot(AsmToken::Integer))
2972 return TokError("unexpected token in '.loc' directive");
2973 int64_t FileNumber = getTok().getIntVal();
2975 return TokError("file number less than one in '.loc' directive");
2976 if (!getContext().isValidDwarfFileNumber(FileNumber))
2977 return TokError("unassigned file number in '.loc' directive");
2980 int64_t LineNumber = 0;
2981 if (getLexer().is(AsmToken::Integer)) {
2982 LineNumber = getTok().getIntVal();
2984 return TokError("line number less than zero in '.loc' directive");
2988 int64_t ColumnPos = 0;
2989 if (getLexer().is(AsmToken::Integer)) {
2990 ColumnPos = getTok().getIntVal();
2992 return TokError("column position less than zero in '.loc' directive");
2996 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2998 int64_t Discriminator = 0;
2999 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3001 if (getLexer().is(AsmToken::EndOfStatement))
3005 SMLoc Loc = getTok().getLoc();
3006 if (parseIdentifier(Name))
3007 return TokError("unexpected token in '.loc' directive");
3009 if (Name == "basic_block")
3010 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3011 else if (Name == "prologue_end")
3012 Flags |= DWARF2_FLAG_PROLOGUE_END;
3013 else if (Name == "epilogue_begin")
3014 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3015 else if (Name == "is_stmt") {
3016 Loc = getTok().getLoc();
3017 const MCExpr *Value;
3018 if (parseExpression(Value))
3020 // The expression must be the constant 0 or 1.
3021 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3022 int Value = MCE->getValue();
3024 Flags &= ~DWARF2_FLAG_IS_STMT;
3025 else if (Value == 1)
3026 Flags |= DWARF2_FLAG_IS_STMT;
3028 return Error(Loc, "is_stmt value not 0 or 1");
3030 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3032 } else if (Name == "isa") {
3033 Loc = getTok().getLoc();
3034 const MCExpr *Value;
3035 if (parseExpression(Value))
3037 // The expression must be a constant greater or equal to 0.
3038 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3039 int Value = MCE->getValue();
3041 return Error(Loc, "isa number less than zero");
3044 return Error(Loc, "isa number not a constant value");
3046 } else if (Name == "discriminator") {
3047 if (parseAbsoluteExpression(Discriminator))
3050 return Error(Loc, "unknown sub-directive in '.loc' directive");
3053 if (getLexer().is(AsmToken::EndOfStatement))
3058 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3059 Isa, Discriminator, StringRef());
3064 /// parseDirectiveStabs
3065 /// ::= .stabs string, number, number, number
3066 bool AsmParser::parseDirectiveStabs() {
3067 return TokError("unsupported directive '.stabs'");
3070 /// parseDirectiveCFISections
3071 /// ::= .cfi_sections section [, section]
3072 bool AsmParser::parseDirectiveCFISections() {
3077 if (parseIdentifier(Name))
3078 return TokError("Expected an identifier");
3080 if (Name == ".eh_frame")
3082 else if (Name == ".debug_frame")
3085 if (getLexer().is(AsmToken::Comma)) {
3088 if (parseIdentifier(Name))
3089 return TokError("Expected an identifier");
3091 if (Name == ".eh_frame")
3093 else if (Name == ".debug_frame")
3097 getStreamer().EmitCFISections(EH, Debug);
3101 /// parseDirectiveCFIStartProc
3102 /// ::= .cfi_startproc [simple]
3103 bool AsmParser::parseDirectiveCFIStartProc() {
3105 if (getLexer().isNot(AsmToken::EndOfStatement))
3106 if (parseIdentifier(Simple) || Simple != "simple")
3107 return TokError("unexpected token in .cfi_startproc directive");
3109 getStreamer().EmitCFIStartProc(!Simple.empty());
3113 /// parseDirectiveCFIEndProc
3114 /// ::= .cfi_endproc
3115 bool AsmParser::parseDirectiveCFIEndProc() {
3116 getStreamer().EmitCFIEndProc();
3120 /// \brief parse register name or number.
3121 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
3122 SMLoc DirectiveLoc) {
3125 if (getLexer().isNot(AsmToken::Integer)) {
3126 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3128 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
3130 return parseAbsoluteExpression(Register);
3135 /// parseDirectiveCFIDefCfa
3136 /// ::= .cfi_def_cfa register, offset
3137 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3138 int64_t Register = 0;
3139 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3142 if (getLexer().isNot(AsmToken::Comma))
3143 return TokError("unexpected token in directive");
3147 if (parseAbsoluteExpression(Offset))
3150 getStreamer().EmitCFIDefCfa(Register, Offset);
3154 /// parseDirectiveCFIDefCfaOffset
3155 /// ::= .cfi_def_cfa_offset offset
3156 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3158 if (parseAbsoluteExpression(Offset))
3161 getStreamer().EmitCFIDefCfaOffset(Offset);
3165 /// parseDirectiveCFIRegister
3166 /// ::= .cfi_register register, register
3167 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3168 int64_t Register1 = 0;
3169 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3172 if (getLexer().isNot(AsmToken::Comma))
3173 return TokError("unexpected token in directive");
3176 int64_t Register2 = 0;
3177 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3180 getStreamer().EmitCFIRegister(Register1, Register2);
3184 /// parseDirectiveCFIWindowSave
3185 /// ::= .cfi_window_save
3186 bool AsmParser::parseDirectiveCFIWindowSave() {
3187 getStreamer().EmitCFIWindowSave();
3191 /// parseDirectiveCFIAdjustCfaOffset
3192 /// ::= .cfi_adjust_cfa_offset adjustment
3193 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3194 int64_t Adjustment = 0;
3195 if (parseAbsoluteExpression(Adjustment))
3198 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3202 /// parseDirectiveCFIDefCfaRegister
3203 /// ::= .cfi_def_cfa_register register
3204 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3205 int64_t Register = 0;
3206 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3209 getStreamer().EmitCFIDefCfaRegister(Register);
3213 /// parseDirectiveCFIOffset
3214 /// ::= .cfi_offset register, offset
3215 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3216 int64_t Register = 0;
3219 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3222 if (getLexer().isNot(AsmToken::Comma))
3223 return TokError("unexpected token in directive");
3226 if (parseAbsoluteExpression(Offset))
3229 getStreamer().EmitCFIOffset(Register, Offset);
3233 /// parseDirectiveCFIRelOffset
3234 /// ::= .cfi_rel_offset register, offset
3235 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3236 int64_t Register = 0;
3238 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3241 if (getLexer().isNot(AsmToken::Comma))
3242 return TokError("unexpected token in directive");
3246 if (parseAbsoluteExpression(Offset))
3249 getStreamer().EmitCFIRelOffset(Register, Offset);
3253 static bool isValidEncoding(int64_t Encoding) {
3254 if (Encoding & ~0xff)
3257 if (Encoding == dwarf::DW_EH_PE_omit)
3260 const unsigned Format = Encoding & 0xf;
3261 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3262 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3263 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3264 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3267 const unsigned Application = Encoding & 0x70;
3268 if (Application != dwarf::DW_EH_PE_absptr &&
3269 Application != dwarf::DW_EH_PE_pcrel)
3275 /// parseDirectiveCFIPersonalityOrLsda
3276 /// IsPersonality true for cfi_personality, false for cfi_lsda
3277 /// ::= .cfi_personality encoding, [symbol_name]
3278 /// ::= .cfi_lsda encoding, [symbol_name]
3279 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3280 int64_t Encoding = 0;
3281 if (parseAbsoluteExpression(Encoding))
3283 if (Encoding == dwarf::DW_EH_PE_omit)
3286 if (!isValidEncoding(Encoding))
3287 return TokError("unsupported encoding.");
3289 if (getLexer().isNot(AsmToken::Comma))
3290 return TokError("unexpected token in directive");
3294 if (parseIdentifier(Name))
3295 return TokError("expected identifier in directive");
3297 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3300 getStreamer().EmitCFIPersonality(Sym, Encoding);
3302 getStreamer().EmitCFILsda(Sym, Encoding);
3306 /// parseDirectiveCFIRememberState
3307 /// ::= .cfi_remember_state
3308 bool AsmParser::parseDirectiveCFIRememberState() {
3309 getStreamer().EmitCFIRememberState();
3313 /// parseDirectiveCFIRestoreState
3314 /// ::= .cfi_remember_state
3315 bool AsmParser::parseDirectiveCFIRestoreState() {
3316 getStreamer().EmitCFIRestoreState();
3320 /// parseDirectiveCFISameValue
3321 /// ::= .cfi_same_value register
3322 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3323 int64_t Register = 0;
3325 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3328 getStreamer().EmitCFISameValue(Register);
3332 /// parseDirectiveCFIRestore
3333 /// ::= .cfi_restore register
3334 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3335 int64_t Register = 0;
3336 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3339 getStreamer().EmitCFIRestore(Register);
3343 /// parseDirectiveCFIEscape
3344 /// ::= .cfi_escape expression[,...]
3345 bool AsmParser::parseDirectiveCFIEscape() {
3348 if (parseAbsoluteExpression(CurrValue))
3351 Values.push_back((uint8_t)CurrValue);
3353 while (getLexer().is(AsmToken::Comma)) {
3356 if (parseAbsoluteExpression(CurrValue))
3359 Values.push_back((uint8_t)CurrValue);
3362 getStreamer().EmitCFIEscape(Values);
3366 /// parseDirectiveCFISignalFrame
3367 /// ::= .cfi_signal_frame
3368 bool AsmParser::parseDirectiveCFISignalFrame() {
3369 if (getLexer().isNot(AsmToken::EndOfStatement))
3370 return Error(getLexer().getLoc(),
3371 "unexpected token in '.cfi_signal_frame'");
3373 getStreamer().EmitCFISignalFrame();
3377 /// parseDirectiveCFIUndefined
3378 /// ::= .cfi_undefined register
3379 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3380 int64_t Register = 0;
3382 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3385 getStreamer().EmitCFIUndefined(Register);
3389 /// parseDirectiveMacrosOnOff
3392 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3393 if (getLexer().isNot(AsmToken::EndOfStatement))
3394 return Error(getLexer().getLoc(),
3395 "unexpected token in '" + Directive + "' directive");
3397 setMacrosEnabled(Directive == ".macros_on");
3401 /// parseDirectiveMacro
3402 /// ::= .macro name[,] [parameters]
3403 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3405 if (parseIdentifier(Name))
3406 return TokError("expected identifier in '.macro' directive");
3408 if (getLexer().is(AsmToken::Comma))
3411 MCAsmMacroParameters Parameters;
3412 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3414 if (!Parameters.empty() && Parameters.back().Vararg)
3415 return Error(Lexer.getLoc(),
3416 "Vararg parameter '" + Parameters.back().Name +
3417 "' should be last one in the list of parameters.");
3419 MCAsmMacroParameter Parameter;
3420 if (parseIdentifier(Parameter.Name))
3421 return TokError("expected identifier in '.macro' directive");
3423 if (Lexer.is(AsmToken::Colon)) {
3424 Lex(); // consume ':'
3427 StringRef Qualifier;
3429 QualLoc = Lexer.getLoc();
3430 if (parseIdentifier(Qualifier))
3431 return Error(QualLoc, "missing parameter qualifier for "
3432 "'" + Parameter.Name + "' in macro '" + Name + "'");
3434 if (Qualifier == "req")
3435 Parameter.Required = true;
3436 else if (Qualifier == "vararg")
3437 Parameter.Vararg = true;
3439 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3440 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3443 if (getLexer().is(AsmToken::Equal)) {
3448 ParamLoc = Lexer.getLoc();
3449 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3452 if (Parameter.Required)
3453 Warning(ParamLoc, "pointless default value for required parameter "
3454 "'" + Parameter.Name + "' in macro '" + Name + "'");
3457 Parameters.push_back(std::move(Parameter));
3459 if (getLexer().is(AsmToken::Comma))
3463 // Eat the end of statement.
3466 AsmToken EndToken, StartToken = getTok();
3467 unsigned MacroDepth = 0;
3469 // Lex the macro definition.
3471 // Check whether we have reached the end of the file.
3472 if (getLexer().is(AsmToken::Eof))
3473 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3475 // Otherwise, check whether we have reach the .endmacro.
3476 if (getLexer().is(AsmToken::Identifier)) {
3477 if (getTok().getIdentifier() == ".endm" ||
3478 getTok().getIdentifier() == ".endmacro") {
3479 if (MacroDepth == 0) { // Outermost macro.
3480 EndToken = getTok();
3482 if (getLexer().isNot(AsmToken::EndOfStatement))
3483 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3487 // Otherwise we just found the end of an inner macro.
3490 } else if (getTok().getIdentifier() == ".macro") {
3491 // We allow nested macros. Those aren't instantiated until the outermost
3492 // macro is expanded so just ignore them for now.
3497 // Otherwise, scan til the end of the statement.
3498 eatToEndOfStatement();
3501 if (lookupMacro(Name)) {
3502 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3505 const char *BodyStart = StartToken.getLoc().getPointer();
3506 const char *BodyEnd = EndToken.getLoc().getPointer();
3507 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3508 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3509 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
3513 /// checkForBadMacro
3515 /// With the support added for named parameters there may be code out there that
3516 /// is transitioning from positional parameters. In versions of gas that did
3517 /// not support named parameters they would be ignored on the macro definition.
3518 /// But to support both styles of parameters this is not possible so if a macro
3519 /// definition has named parameters but does not use them and has what appears
3520 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3521 /// warning that the positional parameter found in body which have no effect.
3522 /// Hoping the developer will either remove the named parameters from the macro
3523 /// definition so the positional parameters get used if that was what was
3524 /// intended or change the macro to use the named parameters. It is possible
3525 /// this warning will trigger when the none of the named parameters are used
3526 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3527 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3529 ArrayRef<MCAsmMacroParameter> Parameters) {
3530 // If this macro is not defined with named parameters the warning we are
3531 // checking for here doesn't apply.
3532 unsigned NParameters = Parameters.size();
3533 if (NParameters == 0)
3536 bool NamedParametersFound = false;
3537 bool PositionalParametersFound = false;
3539 // Look at the body of the macro for use of both the named parameters and what
3540 // are likely to be positional parameters. This is what expandMacro() is
3541 // doing when it finds the parameters in the body.
3542 while (!Body.empty()) {
3543 // Scan for the next possible parameter.
3544 std::size_t End = Body.size(), Pos = 0;
3545 for (; Pos != End; ++Pos) {
3546 // Check for a substitution or escape.
3547 // This macro is defined with parameters, look for \foo, \bar, etc.
3548 if (Body[Pos] == '\\' && Pos + 1 != End)
3551 // This macro should have parameters, but look for $0, $1, ..., $n too.
3552 if (Body[Pos] != '$' || Pos + 1 == End)
3554 char Next = Body[Pos + 1];
3555 if (Next == '$' || Next == 'n' ||
3556 isdigit(static_cast<unsigned char>(Next)))
3560 // Check if we reached the end.
3564 if (Body[Pos] == '$') {
3565 switch (Body[Pos + 1]) {
3570 // $n => number of arguments
3572 PositionalParametersFound = true;
3575 // $[0-9] => argument
3577 PositionalParametersFound = true;
3583 unsigned I = Pos + 1;
3584 while (isIdentifierChar(Body[I]) && I + 1 != End)
3587 const char *Begin = Body.data() + Pos + 1;
3588 StringRef Argument(Begin, I - (Pos + 1));
3590 for (; Index < NParameters; ++Index)
3591 if (Parameters[Index].Name == Argument)
3594 if (Index == NParameters) {
3595 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3601 NamedParametersFound = true;
3602 Pos += 1 + Argument.size();
3605 // Update the scan point.
3606 Body = Body.substr(Pos);
3609 if (!NamedParametersFound && PositionalParametersFound)
3610 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3611 "used in macro body, possible positional parameter "
3612 "found in body which will have no effect");
3615 /// parseDirectiveExitMacro
3617 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3618 if (getLexer().isNot(AsmToken::EndOfStatement))
3619 return TokError("unexpected token in '" + Directive + "' directive");
3621 if (!isInsideMacroInstantiation())
3622 return TokError("unexpected '" + Directive + "' in file, "
3623 "no current macro definition");
3625 // Exit all conditionals that are active in the current macro.
3626 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3627 TheCondState = TheCondStack.back();
3628 TheCondStack.pop_back();
3635 /// parseDirectiveEndMacro
3638 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3639 if (getLexer().isNot(AsmToken::EndOfStatement))
3640 return TokError("unexpected token in '" + Directive + "' directive");
3642 // If we are inside a macro instantiation, terminate the current
3644 if (isInsideMacroInstantiation()) {
3649 // Otherwise, this .endmacro is a stray entry in the file; well formed
3650 // .endmacro directives are handled during the macro definition parsing.
3651 return TokError("unexpected '" + Directive + "' in file, "
3652 "no current macro definition");
3655 /// parseDirectivePurgeMacro
3657 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3659 if (parseIdentifier(Name))
3660 return TokError("expected identifier in '.purgem' directive");
3662 if (getLexer().isNot(AsmToken::EndOfStatement))
3663 return TokError("unexpected token in '.purgem' directive");
3665 if (!lookupMacro(Name))
3666 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3668 undefineMacro(Name);
3672 /// parseDirectiveBundleAlignMode
3673 /// ::= {.bundle_align_mode} expression
3674 bool AsmParser::parseDirectiveBundleAlignMode() {
3675 checkForValidSection();
3677 // Expect a single argument: an expression that evaluates to a constant
3678 // in the inclusive range 0-30.
3679 SMLoc ExprLoc = getLexer().getLoc();
3680 int64_t AlignSizePow2;
3681 if (parseAbsoluteExpression(AlignSizePow2))
3683 else if (getLexer().isNot(AsmToken::EndOfStatement))
3684 return TokError("unexpected token after expression in"
3685 " '.bundle_align_mode' directive");
3686 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3687 return Error(ExprLoc,
3688 "invalid bundle alignment size (expected between 0 and 30)");
3692 // Because of AlignSizePow2's verified range we can safely truncate it to
3694 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3698 /// parseDirectiveBundleLock
3699 /// ::= {.bundle_lock} [align_to_end]
3700 bool AsmParser::parseDirectiveBundleLock() {
3701 checkForValidSection();
3702 bool AlignToEnd = false;
3704 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3706 SMLoc Loc = getTok().getLoc();
3707 const char *kInvalidOptionError =
3708 "invalid option for '.bundle_lock' directive";
3710 if (parseIdentifier(Option))
3711 return Error(Loc, kInvalidOptionError);
3713 if (Option != "align_to_end")
3714 return Error(Loc, kInvalidOptionError);
3715 else if (getLexer().isNot(AsmToken::EndOfStatement))
3717 "unexpected token after '.bundle_lock' directive option");
3723 getStreamer().EmitBundleLock(AlignToEnd);
3727 /// parseDirectiveBundleLock
3728 /// ::= {.bundle_lock}
3729 bool AsmParser::parseDirectiveBundleUnlock() {
3730 checkForValidSection();
3732 if (getLexer().isNot(AsmToken::EndOfStatement))
3733 return TokError("unexpected token in '.bundle_unlock' directive");
3736 getStreamer().EmitBundleUnlock();
3740 /// parseDirectiveSpace
3741 /// ::= (.skip | .space) expression [ , expression ]
3742 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3743 checkForValidSection();
3746 if (parseAbsoluteExpression(NumBytes))
3749 int64_t FillExpr = 0;
3750 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3751 if (getLexer().isNot(AsmToken::Comma))
3752 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3755 if (parseAbsoluteExpression(FillExpr))
3758 if (getLexer().isNot(AsmToken::EndOfStatement))
3759 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3765 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3768 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3769 getStreamer().EmitFill(NumBytes, FillExpr);
3774 /// parseDirectiveLEB128
3775 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
3776 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3777 checkForValidSection();
3778 const MCExpr *Value;
3781 if (parseExpression(Value))
3785 getStreamer().EmitSLEB128Value(Value);
3787 getStreamer().EmitULEB128Value(Value);
3789 if (getLexer().is(AsmToken::EndOfStatement))
3792 if (getLexer().isNot(AsmToken::Comma))
3793 return TokError("unexpected token in directive");
3800 /// parseDirectiveSymbolAttribute
3801 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3802 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3803 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3806 SMLoc Loc = getTok().getLoc();
3808 if (parseIdentifier(Name))
3809 return Error(Loc, "expected identifier in directive");
3811 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3813 // Assembler local symbols don't make any sense here. Complain loudly.
3814 if (Sym->isTemporary())
3815 return Error(Loc, "non-local symbol required in directive");
3817 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3818 return Error(Loc, "unable to emit symbol attribute");
3820 if (getLexer().is(AsmToken::EndOfStatement))
3823 if (getLexer().isNot(AsmToken::Comma))
3824 return TokError("unexpected token in directive");
3833 /// parseDirectiveComm
3834 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3835 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3836 checkForValidSection();
3838 SMLoc IDLoc = getLexer().getLoc();
3840 if (parseIdentifier(Name))
3841 return TokError("expected identifier in directive");
3843 // Handle the identifier as the key symbol.
3844 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3846 if (getLexer().isNot(AsmToken::Comma))
3847 return TokError("unexpected token in directive");
3851 SMLoc SizeLoc = getLexer().getLoc();
3852 if (parseAbsoluteExpression(Size))
3855 int64_t Pow2Alignment = 0;
3856 SMLoc Pow2AlignmentLoc;
3857 if (getLexer().is(AsmToken::Comma)) {
3859 Pow2AlignmentLoc = getLexer().getLoc();
3860 if (parseAbsoluteExpression(Pow2Alignment))
3863 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3864 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3865 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3867 // If this target takes alignments in bytes (not log) validate and convert.
3868 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3869 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3870 if (!isPowerOf2_64(Pow2Alignment))
3871 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3872 Pow2Alignment = Log2_64(Pow2Alignment);
3876 if (getLexer().isNot(AsmToken::EndOfStatement))
3877 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3881 // NOTE: a size of zero for a .comm should create a undefined symbol
3882 // but a size of .lcomm creates a bss symbol of size zero.
3884 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3885 "be less than zero");
3887 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3888 // may internally end up wanting an alignment in bytes.
3889 // FIXME: Diagnose overflow.
3890 if (Pow2Alignment < 0)
3891 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3892 "alignment, can't be less than zero");
3894 if (!Sym->isUndefined())
3895 return Error(IDLoc, "invalid symbol redefinition");
3897 // Create the Symbol as a common or local common with Size and Pow2Alignment
3899 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3903 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3907 /// parseDirectiveAbort
3908 /// ::= .abort [... message ...]
3909 bool AsmParser::parseDirectiveAbort() {
3910 // FIXME: Use loc from directive.
3911 SMLoc Loc = getLexer().getLoc();
3913 StringRef Str = parseStringToEndOfStatement();
3914 if (getLexer().isNot(AsmToken::EndOfStatement))
3915 return TokError("unexpected token in '.abort' directive");
3920 Error(Loc, ".abort detected. Assembly stopping.");
3922 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3923 // FIXME: Actually abort assembly here.
3928 /// parseDirectiveInclude
3929 /// ::= .include "filename"
3930 bool AsmParser::parseDirectiveInclude() {
3931 if (getLexer().isNot(AsmToken::String))
3932 return TokError("expected string in '.include' directive");
3934 // Allow the strings to have escaped octal character sequence.
3935 std::string Filename;
3936 if (parseEscapedString(Filename))
3938 SMLoc IncludeLoc = getLexer().getLoc();
3941 if (getLexer().isNot(AsmToken::EndOfStatement))
3942 return TokError("unexpected token in '.include' directive");
3944 // Attempt to switch the lexer to the included file before consuming the end
3945 // of statement to avoid losing it when we switch.
3946 if (enterIncludeFile(Filename)) {
3947 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3954 /// parseDirectiveIncbin
3955 /// ::= .incbin "filename"
3956 bool AsmParser::parseDirectiveIncbin() {
3957 if (getLexer().isNot(AsmToken::String))
3958 return TokError("expected string in '.incbin' directive");
3960 // Allow the strings to have escaped octal character sequence.
3961 std::string Filename;
3962 if (parseEscapedString(Filename))
3964 SMLoc IncbinLoc = getLexer().getLoc();
3967 if (getLexer().isNot(AsmToken::EndOfStatement))
3968 return TokError("unexpected token in '.incbin' directive");
3970 // Attempt to process the included file.
3971 if (processIncbinFile(Filename)) {
3972 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3979 /// parseDirectiveIf
3980 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
3981 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
3982 TheCondStack.push_back(TheCondState);
3983 TheCondState.TheCond = AsmCond::IfCond;
3984 if (TheCondState.Ignore) {
3985 eatToEndOfStatement();
3988 if (parseAbsoluteExpression(ExprValue))
3991 if (getLexer().isNot(AsmToken::EndOfStatement))
3992 return TokError("unexpected token in '.if' directive");
3998 llvm_unreachable("unsupported directive");
4003 ExprValue = ExprValue == 0;
4006 ExprValue = ExprValue >= 0;
4009 ExprValue = ExprValue > 0;
4012 ExprValue = ExprValue <= 0;
4015 ExprValue = ExprValue < 0;
4019 TheCondState.CondMet = ExprValue;
4020 TheCondState.Ignore = !TheCondState.CondMet;
4026 /// parseDirectiveIfb
4028 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
4029 TheCondStack.push_back(TheCondState);
4030 TheCondState.TheCond = AsmCond::IfCond;
4032 if (TheCondState.Ignore) {
4033 eatToEndOfStatement();
4035 StringRef Str = parseStringToEndOfStatement();
4037 if (getLexer().isNot(AsmToken::EndOfStatement))
4038 return TokError("unexpected token in '.ifb' directive");
4042 TheCondState.CondMet = ExpectBlank == Str.empty();
4043 TheCondState.Ignore = !TheCondState.CondMet;
4049 /// parseDirectiveIfc
4050 /// ::= .ifc string1, string2
4051 /// ::= .ifnc string1, string2
4052 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
4053 TheCondStack.push_back(TheCondState);
4054 TheCondState.TheCond = AsmCond::IfCond;
4056 if (TheCondState.Ignore) {
4057 eatToEndOfStatement();
4059 StringRef Str1 = parseStringToComma();
4061 if (getLexer().isNot(AsmToken::Comma))
4062 return TokError("unexpected token in '.ifc' directive");
4066 StringRef Str2 = parseStringToEndOfStatement();
4068 if (getLexer().isNot(AsmToken::EndOfStatement))
4069 return TokError("unexpected token in '.ifc' directive");
4073 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
4074 TheCondState.Ignore = !TheCondState.CondMet;
4080 /// parseDirectiveIfeqs
4081 /// ::= .ifeqs string1, string2
4082 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
4083 if (Lexer.isNot(AsmToken::String)) {
4085 TokError("expected string parameter for '.ifeqs' directive");
4087 TokError("expected string parameter for '.ifnes' directive");
4088 eatToEndOfStatement();
4092 StringRef String1 = getTok().getStringContents();
4095 if (Lexer.isNot(AsmToken::Comma)) {
4097 TokError("expected comma after first string for '.ifeqs' directive");
4099 TokError("expected comma after first string for '.ifnes' directive");
4100 eatToEndOfStatement();
4106 if (Lexer.isNot(AsmToken::String)) {
4108 TokError("expected string parameter for '.ifeqs' directive");
4110 TokError("expected string parameter for '.ifnes' directive");
4111 eatToEndOfStatement();
4115 StringRef String2 = getTok().getStringContents();
4118 TheCondStack.push_back(TheCondState);
4119 TheCondState.TheCond = AsmCond::IfCond;
4120 TheCondState.CondMet = ExpectEqual == (String1 == String2);
4121 TheCondState.Ignore = !TheCondState.CondMet;
4126 /// parseDirectiveIfdef
4127 /// ::= .ifdef symbol
4128 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
4130 TheCondStack.push_back(TheCondState);
4131 TheCondState.TheCond = AsmCond::IfCond;
4133 if (TheCondState.Ignore) {
4134 eatToEndOfStatement();
4136 if (parseIdentifier(Name))
4137 return TokError("expected identifier after '.ifdef'");
4141 MCSymbol *Sym = getContext().lookupSymbol(Name);
4144 TheCondState.CondMet = (Sym && !Sym->isUndefined());
4146 TheCondState.CondMet = (!Sym || Sym->isUndefined());
4147 TheCondState.Ignore = !TheCondState.CondMet;
4153 /// parseDirectiveElseIf
4154 /// ::= .elseif expression
4155 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4156 if (TheCondState.TheCond != AsmCond::IfCond &&
4157 TheCondState.TheCond != AsmCond::ElseIfCond)
4158 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4160 TheCondState.TheCond = AsmCond::ElseIfCond;
4162 bool LastIgnoreState = false;
4163 if (!TheCondStack.empty())
4164 LastIgnoreState = TheCondStack.back().Ignore;
4165 if (LastIgnoreState || TheCondState.CondMet) {
4166 TheCondState.Ignore = true;
4167 eatToEndOfStatement();
4170 if (parseAbsoluteExpression(ExprValue))
4173 if (getLexer().isNot(AsmToken::EndOfStatement))
4174 return TokError("unexpected token in '.elseif' directive");
4177 TheCondState.CondMet = ExprValue;
4178 TheCondState.Ignore = !TheCondState.CondMet;
4184 /// parseDirectiveElse
4186 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4187 if (getLexer().isNot(AsmToken::EndOfStatement))
4188 return TokError("unexpected token in '.else' directive");
4192 if (TheCondState.TheCond != AsmCond::IfCond &&
4193 TheCondState.TheCond != AsmCond::ElseIfCond)
4194 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4196 TheCondState.TheCond = AsmCond::ElseCond;
4197 bool LastIgnoreState = false;
4198 if (!TheCondStack.empty())
4199 LastIgnoreState = TheCondStack.back().Ignore;
4200 if (LastIgnoreState || TheCondState.CondMet)
4201 TheCondState.Ignore = true;
4203 TheCondState.Ignore = false;
4208 /// parseDirectiveEnd
4210 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4211 if (getLexer().isNot(AsmToken::EndOfStatement))
4212 return TokError("unexpected token in '.end' directive");
4216 while (Lexer.isNot(AsmToken::Eof))
4222 /// parseDirectiveError
4224 /// ::= .error [string]
4225 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4226 if (!TheCondStack.empty()) {
4227 if (TheCondStack.back().Ignore) {
4228 eatToEndOfStatement();
4234 return Error(L, ".err encountered");
4236 StringRef Message = ".error directive invoked in source file";
4237 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4238 if (Lexer.isNot(AsmToken::String)) {
4239 TokError(".error argument must be a string");
4240 eatToEndOfStatement();
4244 Message = getTok().getStringContents();
4252 /// parseDirectiveWarning
4253 /// ::= .warning [string]
4254 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4255 if (!TheCondStack.empty()) {
4256 if (TheCondStack.back().Ignore) {
4257 eatToEndOfStatement();
4262 StringRef Message = ".warning directive invoked in source file";
4263 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4264 if (Lexer.isNot(AsmToken::String)) {
4265 TokError(".warning argument must be a string");
4266 eatToEndOfStatement();
4270 Message = getTok().getStringContents();
4274 Warning(L, Message);
4278 /// parseDirectiveEndIf
4280 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4281 if (getLexer().isNot(AsmToken::EndOfStatement))
4282 return TokError("unexpected token in '.endif' directive");
4286 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4287 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4289 if (!TheCondStack.empty()) {
4290 TheCondState = TheCondStack.back();
4291 TheCondStack.pop_back();
4297 void AsmParser::initializeDirectiveKindMap() {
4298 DirectiveKindMap[".set"] = DK_SET;
4299 DirectiveKindMap[".equ"] = DK_EQU;
4300 DirectiveKindMap[".equiv"] = DK_EQUIV;
4301 DirectiveKindMap[".ascii"] = DK_ASCII;
4302 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4303 DirectiveKindMap[".string"] = DK_STRING;
4304 DirectiveKindMap[".byte"] = DK_BYTE;
4305 DirectiveKindMap[".short"] = DK_SHORT;
4306 DirectiveKindMap[".value"] = DK_VALUE;
4307 DirectiveKindMap[".2byte"] = DK_2BYTE;
4308 DirectiveKindMap[".long"] = DK_LONG;
4309 DirectiveKindMap[".int"] = DK_INT;
4310 DirectiveKindMap[".4byte"] = DK_4BYTE;
4311 DirectiveKindMap[".quad"] = DK_QUAD;
4312 DirectiveKindMap[".8byte"] = DK_8BYTE;
4313 DirectiveKindMap[".octa"] = DK_OCTA;
4314 DirectiveKindMap[".single"] = DK_SINGLE;
4315 DirectiveKindMap[".float"] = DK_FLOAT;
4316 DirectiveKindMap[".double"] = DK_DOUBLE;
4317 DirectiveKindMap[".align"] = DK_ALIGN;
4318 DirectiveKindMap[".align32"] = DK_ALIGN32;
4319 DirectiveKindMap[".balign"] = DK_BALIGN;
4320 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4321 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4322 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4323 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4324 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4325 DirectiveKindMap[".org"] = DK_ORG;
4326 DirectiveKindMap[".fill"] = DK_FILL;
4327 DirectiveKindMap[".zero"] = DK_ZERO;
4328 DirectiveKindMap[".extern"] = DK_EXTERN;
4329 DirectiveKindMap[".globl"] = DK_GLOBL;
4330 DirectiveKindMap[".global"] = DK_GLOBAL;
4331 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4332 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4333 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4334 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4335 DirectiveKindMap[".reference"] = DK_REFERENCE;
4336 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4337 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4338 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4339 DirectiveKindMap[".comm"] = DK_COMM;
4340 DirectiveKindMap[".common"] = DK_COMMON;
4341 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4342 DirectiveKindMap[".abort"] = DK_ABORT;
4343 DirectiveKindMap[".include"] = DK_INCLUDE;
4344 DirectiveKindMap[".incbin"] = DK_INCBIN;
4345 DirectiveKindMap[".code16"] = DK_CODE16;
4346 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4347 DirectiveKindMap[".rept"] = DK_REPT;
4348 DirectiveKindMap[".rep"] = DK_REPT;
4349 DirectiveKindMap[".irp"] = DK_IRP;
4350 DirectiveKindMap[".irpc"] = DK_IRPC;
4351 DirectiveKindMap[".endr"] = DK_ENDR;
4352 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4353 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4354 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4355 DirectiveKindMap[".if"] = DK_IF;
4356 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4357 DirectiveKindMap[".ifge"] = DK_IFGE;
4358 DirectiveKindMap[".ifgt"] = DK_IFGT;
4359 DirectiveKindMap[".ifle"] = DK_IFLE;
4360 DirectiveKindMap[".iflt"] = DK_IFLT;
4361 DirectiveKindMap[".ifne"] = DK_IFNE;
4362 DirectiveKindMap[".ifb"] = DK_IFB;
4363 DirectiveKindMap[".ifnb"] = DK_IFNB;
4364 DirectiveKindMap[".ifc"] = DK_IFC;
4365 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4366 DirectiveKindMap[".ifnc"] = DK_IFNC;
4367 DirectiveKindMap[".ifnes"] = DK_IFNES;
4368 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4369 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4370 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4371 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4372 DirectiveKindMap[".else"] = DK_ELSE;
4373 DirectiveKindMap[".end"] = DK_END;
4374 DirectiveKindMap[".endif"] = DK_ENDIF;
4375 DirectiveKindMap[".skip"] = DK_SKIP;
4376 DirectiveKindMap[".space"] = DK_SPACE;
4377 DirectiveKindMap[".file"] = DK_FILE;
4378 DirectiveKindMap[".line"] = DK_LINE;
4379 DirectiveKindMap[".loc"] = DK_LOC;
4380 DirectiveKindMap[".stabs"] = DK_STABS;
4381 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4382 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4383 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4384 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4385 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4386 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4387 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4388 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4389 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4390 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4391 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4392 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4393 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4394 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4395 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4396 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4397 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4398 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4399 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4400 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4401 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4402 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4403 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4404 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4405 DirectiveKindMap[".macro"] = DK_MACRO;
4406 DirectiveKindMap[".exitm"] = DK_EXITM;
4407 DirectiveKindMap[".endm"] = DK_ENDM;
4408 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4409 DirectiveKindMap[".purgem"] = DK_PURGEM;
4410 DirectiveKindMap[".err"] = DK_ERR;
4411 DirectiveKindMap[".error"] = DK_ERROR;
4412 DirectiveKindMap[".warning"] = DK_WARNING;
4413 DirectiveKindMap[".reloc"] = DK_RELOC;
4416 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4417 AsmToken EndToken, StartToken = getTok();
4419 unsigned NestLevel = 0;
4421 // Check whether we have reached the end of the file.
4422 if (getLexer().is(AsmToken::Eof)) {
4423 Error(DirectiveLoc, "no matching '.endr' in definition");
4427 if (Lexer.is(AsmToken::Identifier) &&
4428 (getTok().getIdentifier() == ".rept")) {
4432 // Otherwise, check whether we have reached the .endr.
4433 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4434 if (NestLevel == 0) {
4435 EndToken = getTok();
4437 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4438 TokError("unexpected token in '.endr' directive");
4446 // Otherwise, scan till the end of the statement.
4447 eatToEndOfStatement();
4450 const char *BodyStart = StartToken.getLoc().getPointer();
4451 const char *BodyEnd = EndToken.getLoc().getPointer();
4452 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4454 // We Are Anonymous.
4455 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
4456 return &MacroLikeBodies.back();
4459 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4460 raw_svector_ostream &OS) {
4463 std::unique_ptr<MemoryBuffer> Instantiation =
4464 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4466 // Create the macro instantiation object and add to the current macro
4467 // instantiation stack.
4468 MacroInstantiation *MI = new MacroInstantiation(
4469 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
4470 ActiveMacros.push_back(MI);
4472 // Jump to the macro instantiation and prime the lexer.
4473 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
4474 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
4478 /// parseDirectiveRept
4479 /// ::= .rep | .rept count
4480 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4481 const MCExpr *CountExpr;
4482 SMLoc CountLoc = getTok().getLoc();
4483 if (parseExpression(CountExpr))
4487 if (!CountExpr->evaluateAsAbsolute(Count)) {
4488 eatToEndOfStatement();
4489 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4493 return Error(CountLoc, "Count is negative");
4495 if (Lexer.isNot(AsmToken::EndOfStatement))
4496 return TokError("unexpected token in '" + Dir + "' directive");
4498 // Eat the end of statement.
4501 // Lex the rept definition.
4502 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4506 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4507 // to hold the macro body with substitutions.
4508 SmallString<256> Buf;
4509 raw_svector_ostream OS(Buf);
4511 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4512 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
4515 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4520 /// parseDirectiveIrp
4521 /// ::= .irp symbol,values
4522 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4523 MCAsmMacroParameter Parameter;
4525 if (parseIdentifier(Parameter.Name))
4526 return TokError("expected identifier in '.irp' directive");
4528 if (Lexer.isNot(AsmToken::Comma))
4529 return TokError("expected comma in '.irp' directive");
4533 MCAsmMacroArguments A;
4534 if (parseMacroArguments(nullptr, A))
4537 // Eat the end of statement.
4540 // Lex the irp definition.
4541 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4545 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4546 // to hold the macro body with substitutions.
4547 SmallString<256> Buf;
4548 raw_svector_ostream OS(Buf);
4550 for (const MCAsmMacroArgument &Arg : A) {
4551 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4552 // This is undocumented, but GAS seems to support it.
4553 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
4557 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4562 /// parseDirectiveIrpc
4563 /// ::= .irpc symbol,values
4564 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4565 MCAsmMacroParameter Parameter;
4567 if (parseIdentifier(Parameter.Name))
4568 return TokError("expected identifier in '.irpc' directive");
4570 if (Lexer.isNot(AsmToken::Comma))
4571 return TokError("expected comma in '.irpc' directive");
4575 MCAsmMacroArguments A;
4576 if (parseMacroArguments(nullptr, A))
4579 if (A.size() != 1 || A.front().size() != 1)
4580 return TokError("unexpected token in '.irpc' directive");
4582 // Eat the end of statement.
4585 // Lex the irpc definition.
4586 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4590 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4591 // to hold the macro body with substitutions.
4592 SmallString<256> Buf;
4593 raw_svector_ostream OS(Buf);
4595 StringRef Values = A.front().front().getString();
4596 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4597 MCAsmMacroArgument Arg;
4598 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
4600 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4601 // This is undocumented, but GAS seems to support it.
4602 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
4606 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4611 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4612 if (ActiveMacros.empty())
4613 return TokError("unmatched '.endr' directive");
4615 // The only .repl that should get here are the ones created by
4616 // instantiateMacroLikeBody.
4617 assert(getLexer().is(AsmToken::EndOfStatement));
4623 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4625 const MCExpr *Value;
4626 SMLoc ExprLoc = getLexer().getLoc();
4627 if (parseExpression(Value))
4629 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4631 return Error(ExprLoc, "unexpected expression in _emit");
4632 uint64_t IntValue = MCE->getValue();
4633 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
4634 return Error(ExprLoc, "literal value out of range for directive");
4636 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
4640 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4641 const MCExpr *Value;
4642 SMLoc ExprLoc = getLexer().getLoc();
4643 if (parseExpression(Value))
4645 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4647 return Error(ExprLoc, "unexpected expression in align");
4648 uint64_t IntValue = MCE->getValue();
4649 if (!isPowerOf2_64(IntValue))
4650 return Error(ExprLoc, "literal value not a power of two greater then zero");
4652 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
4656 // We are comparing pointers, but the pointers are relative to a single string.
4657 // Thus, this should always be deterministic.
4658 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4659 const AsmRewrite *AsmRewriteB) {
4660 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4662 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4665 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4666 // rewrite to the same location. Make sure the SizeDirective rewrite is
4667 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4668 // ensures the sort algorithm is stable.
4669 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4670 AsmRewritePrecedence[AsmRewriteB->Kind])
4673 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4674 AsmRewritePrecedence[AsmRewriteB->Kind])
4676 llvm_unreachable("Unstable rewrite sort.");
4679 bool AsmParser::parseMSInlineAsm(
4680 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4681 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4682 SmallVectorImpl<std::string> &Constraints,
4683 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4684 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4685 SmallVector<void *, 4> InputDecls;
4686 SmallVector<void *, 4> OutputDecls;
4687 SmallVector<bool, 4> InputDeclsAddressOf;
4688 SmallVector<bool, 4> OutputDeclsAddressOf;
4689 SmallVector<std::string, 4> InputConstraints;
4690 SmallVector<std::string, 4> OutputConstraints;
4691 SmallVector<unsigned, 4> ClobberRegs;
4693 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4698 // While we have input, parse each statement.
4699 unsigned InputIdx = 0;
4700 unsigned OutputIdx = 0;
4701 while (getLexer().isNot(AsmToken::Eof)) {
4702 ParseStatementInfo Info(&AsmStrRewrites);
4703 if (parseStatement(Info, &SI))
4706 if (Info.ParseError)
4709 if (Info.Opcode == ~0U)
4712 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4714 // Build the list of clobbers, outputs and inputs.
4715 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4716 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4719 if (Operand.isImm())
4722 // Register operand.
4723 if (Operand.isReg() && !Operand.needAddressOf() &&
4724 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
4725 unsigned NumDefs = Desc.getNumDefs();
4727 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4728 ClobberRegs.push_back(Operand.getReg());
4732 // Expr/Input or Output.
4733 StringRef SymName = Operand.getSymName();
4734 if (SymName.empty())
4737 void *OpDecl = Operand.getOpDecl();
4741 bool isOutput = (i == 1) && Desc.mayStore();
4742 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4745 OutputDecls.push_back(OpDecl);
4746 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4747 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
4748 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
4750 InputDecls.push_back(OpDecl);
4751 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4752 InputConstraints.push_back(Operand.getConstraint().str());
4753 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
4757 // Consider implicit defs to be clobbers. Think of cpuid and push.
4758 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
4759 Desc.getNumImplicitDefs());
4760 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
4763 // Set the number of Outputs and Inputs.
4764 NumOutputs = OutputDecls.size();
4765 NumInputs = InputDecls.size();
4767 // Set the unique clobbers.
4768 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4769 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4771 Clobbers.assign(ClobberRegs.size(), std::string());
4772 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4773 raw_string_ostream OS(Clobbers[I]);
4774 IP->printRegName(OS, ClobberRegs[I]);
4777 // Merge the various outputs and inputs. Output are expected first.
4778 if (NumOutputs || NumInputs) {
4779 unsigned NumExprs = NumOutputs + NumInputs;
4780 OpDecls.resize(NumExprs);
4781 Constraints.resize(NumExprs);
4782 for (unsigned i = 0; i < NumOutputs; ++i) {
4783 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4784 Constraints[i] = OutputConstraints[i];
4786 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4787 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4788 Constraints[j] = InputConstraints[i];
4792 // Build the IR assembly string.
4793 std::string AsmStringIR;
4794 raw_string_ostream OS(AsmStringIR);
4795 StringRef ASMString =
4796 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4797 const char *AsmStart = ASMString.begin();
4798 const char *AsmEnd = ASMString.end();
4799 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4800 for (const AsmRewrite &AR : AsmStrRewrites) {
4801 AsmRewriteKind Kind = AR.Kind;
4802 if (Kind == AOK_Delete)
4805 const char *Loc = AR.Loc.getPointer();
4806 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4808 // Emit everything up to the immediate/expression.
4809 if (unsigned Len = Loc - AsmStart)
4810 OS << StringRef(AsmStart, Len);
4812 // Skip the original expression.
4813 if (Kind == AOK_Skip) {
4814 AsmStart = Loc + AR.Len;
4818 unsigned AdditionalSkip = 0;
4819 // Rewrite expressions in $N notation.
4824 OS << "$$" << AR.Val;
4830 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
4833 OS << '$' << InputIdx++;
4836 OS << '$' << OutputIdx++;
4838 case AOK_SizeDirective:
4841 case 8: OS << "byte ptr "; break;
4842 case 16: OS << "word ptr "; break;
4843 case 32: OS << "dword ptr "; break;
4844 case 64: OS << "qword ptr "; break;
4845 case 80: OS << "xword ptr "; break;
4846 case 128: OS << "xmmword ptr "; break;
4847 case 256: OS << "ymmword ptr "; break;
4854 // MS alignment directives are measured in bytes. If the native assembler
4855 // measures alignment in bytes, we can pass it straight through.
4857 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
4860 // Alignment is in log2 form, so print that instead and skip the original
4862 unsigned Val = AR.Val;
4864 assert(Val < 10 && "Expected alignment less then 2^10.");
4865 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4871 case AOK_DotOperator:
4872 // Insert the dot if the user omitted it.
4874 if (AsmStringIR.back() != '.')
4880 // Skip the original expression.
4881 AsmStart = Loc + AR.Len + AdditionalSkip;
4884 // Emit the remainder of the asm string.
4885 if (AsmStart != AsmEnd)
4886 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4888 AsmString = OS.str();
4893 namespace MCParserUtils {
4895 /// Returns whether the given symbol is used anywhere in the given expression,
4896 /// or subexpressions.
4897 static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
4898 switch (Value->getKind()) {
4899 case MCExpr::Binary: {
4900 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
4901 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
4902 isSymbolUsedInExpression(Sym, BE->getRHS());
4904 case MCExpr::Target:
4905 case MCExpr::Constant:
4907 case MCExpr::SymbolRef: {
4909 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
4911 return isSymbolUsedInExpression(Sym, S.getVariableValue());
4915 return isSymbolUsedInExpression(
4916 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
4919 llvm_unreachable("Unknown expr kind!");
4922 bool parseAssignmentExpression(StringRef Name, bool allow_redef,
4923 MCAsmParser &Parser, MCSymbol *&Sym,
4924 const MCExpr *&Value) {
4925 MCAsmLexer &Lexer = Parser.getLexer();
4927 // FIXME: Use better location, we should use proper tokens.
4928 SMLoc EqualLoc = Lexer.getLoc();
4930 if (Parser.parseExpression(Value)) {
4931 Parser.TokError("missing expression");
4932 Parser.eatToEndOfStatement();
4936 // Note: we don't count b as used in "a = b". This is to allow
4940 if (Lexer.isNot(AsmToken::EndOfStatement))
4941 return Parser.TokError("unexpected token in assignment");
4943 // Eat the end of statement marker.
4946 // Validate that the LHS is allowed to be a variable (either it has not been
4947 // used as a symbol, or it is an absolute symbol).
4948 Sym = Parser.getContext().lookupSymbol(Name);
4950 // Diagnose assignment to a label.
4952 // FIXME: Diagnostics. Note the location of the definition as a label.
4953 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
4954 if (isSymbolUsedInExpression(Sym, Value))
4955 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
4956 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
4958 ; // Allow redefinitions of undefined symbols only used in directives.
4959 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
4960 ; // Allow redefinitions of variables that haven't yet been used.
4961 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
4962 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
4963 else if (!Sym->isVariable())
4964 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
4965 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
4966 return Parser.Error(EqualLoc,
4967 "invalid reassignment of non-absolute variable '" +
4969 } else if (Name == ".") {
4970 Parser.getStreamer().emitValueToOffset(Value, 0);
4973 Sym = Parser.getContext().getOrCreateSymbol(Name);
4975 Sym->setRedefinable(allow_redef);
4980 } // namespace MCParserUtils
4983 /// \brief Create an MCAsmParser instance.
4984 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4985 MCStreamer &Out, const MCAsmInfo &MAI) {
4986 return new AsmParser(SM, C, Out, MAI);