1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCParser/AsmCond.h"
27 #include "llvm/MC/MCParser/AsmLexer.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCTargetAsmParser.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/raw_ostream.h"
48 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
51 /// \brief Helper types for tracking macro definitions.
52 typedef std::vector<AsmToken> MCAsmMacroArgument;
53 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
55 struct MCAsmMacroParameter {
57 MCAsmMacroArgument Value;
61 MCAsmMacroParameter() : Required(false), Vararg(false) {}
64 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
69 MCAsmMacroParameters Parameters;
72 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
73 : Name(N), Body(B), Parameters(std::move(P)) {}
76 /// \brief Helper class for storing information about an active macro
78 struct MacroInstantiation {
79 /// The location of the instantiation.
80 SMLoc InstantiationLoc;
82 /// The buffer where parsing should resume upon instantiation completion.
85 /// The location where parsing should resume upon instantiation completion.
88 /// The depth of TheCondStack at the start of the instantiation.
89 size_t CondStackDepth;
92 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
95 struct ParseStatementInfo {
96 /// \brief The parsed operands from the last parsed statement.
97 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
99 /// \brief The opcode from the last parsed instruction.
102 /// \brief Was there an error parsing the inline assembly?
105 SmallVectorImpl<AsmRewrite> *AsmRewrites;
107 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
108 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
109 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
112 /// \brief The concrete assembly parser instance.
113 class AsmParser : public MCAsmParser {
114 AsmParser(const AsmParser &) = delete;
115 void operator=(const AsmParser &) = delete;
120 const MCAsmInfo &MAI;
122 SourceMgr::DiagHandlerTy SavedDiagHandler;
123 void *SavedDiagContext;
124 std::unique_ptr<MCAsmParserExtension> PlatformParser;
126 /// This is the current buffer index we're lexing from as managed by the
127 /// SourceMgr object.
130 AsmCond TheCondState;
131 std::vector<AsmCond> TheCondStack;
133 /// \brief maps directive names to handler methods in parser
134 /// extensions. Extensions register themselves in this map by calling
135 /// addDirectiveHandler.
136 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
138 /// \brief Map of currently defined macros.
139 StringMap<MCAsmMacro> MacroMap;
141 /// \brief Stack of active macro instantiations.
142 std::vector<MacroInstantiation*> ActiveMacros;
144 /// \brief List of bodies of anonymous macros.
145 std::deque<MCAsmMacro> MacroLikeBodies;
147 /// Boolean tracking whether macro substitution is enabled.
148 unsigned MacrosEnabledFlag : 1;
150 /// \brief Keeps track of how many .macro's have been instantiated.
151 unsigned NumOfMacroInstantiations;
153 /// Flag tracking whether any errors have been encountered.
154 unsigned HadError : 1;
156 /// The values from the last parsed cpp hash file line comment if any.
157 StringRef CppHashFilename;
158 int64_t CppHashLineNumber;
161 /// When generating dwarf for assembly source files we need to calculate the
162 /// logical line number based on the last parsed cpp hash file line comment
163 /// and current line. Since this is slow and messes up the SourceMgr's
164 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
165 SMLoc LastQueryIDLoc;
166 unsigned LastQueryBuffer;
167 unsigned LastQueryLine;
169 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
170 unsigned AssemblerDialect;
172 /// \brief is Darwin compatibility enabled?
175 /// \brief Are we parsing ms-style inline assembly?
176 bool ParsingInlineAsm;
179 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
180 const MCAsmInfo &MAI);
181 ~AsmParser() override;
183 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
185 void addDirectiveHandler(StringRef Directive,
186 ExtensionDirectiveHandler Handler) override {
187 ExtensionDirectiveMap[Directive] = Handler;
190 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
191 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
195 /// @name MCAsmParser Interface
198 SourceMgr &getSourceManager() override { return SrcMgr; }
199 MCAsmLexer &getLexer() override { return Lexer; }
200 MCContext &getContext() override { return Ctx; }
201 MCStreamer &getStreamer() override { return Out; }
202 unsigned getAssemblerDialect() override {
203 if (AssemblerDialect == ~0U)
204 return MAI.getAssemblerDialect();
206 return AssemblerDialect;
208 void setAssemblerDialect(unsigned i) override {
209 AssemblerDialect = i;
212 void Note(SMLoc L, const Twine &Msg,
213 ArrayRef<SMRange> Ranges = None) override;
214 bool Warning(SMLoc L, const Twine &Msg,
215 ArrayRef<SMRange> Ranges = None) override;
216 bool Error(SMLoc L, const Twine &Msg,
217 ArrayRef<SMRange> Ranges = None) override;
219 const AsmToken &Lex() override;
221 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
222 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
224 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
225 unsigned &NumOutputs, unsigned &NumInputs,
226 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
227 SmallVectorImpl<std::string> &Constraints,
228 SmallVectorImpl<std::string> &Clobbers,
229 const MCInstrInfo *MII, const MCInstPrinter *IP,
230 MCAsmParserSemaCallback &SI) override;
232 bool parseExpression(const MCExpr *&Res);
233 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
234 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
235 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
236 bool parseAbsoluteExpression(int64_t &Res) override;
238 /// \brief Parse an identifier or string (as a quoted identifier)
239 /// and set \p Res to the identifier contents.
240 bool parseIdentifier(StringRef &Res) override;
241 void eatToEndOfStatement() override;
243 void checkForValidSection() override;
248 bool parseStatement(ParseStatementInfo &Info,
249 MCAsmParserSemaCallback *SI);
250 void eatToEndOfLine();
251 bool parseCppHashLineFilenameComment(const SMLoc &L);
253 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
254 ArrayRef<MCAsmMacroParameter> Parameters);
255 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
256 ArrayRef<MCAsmMacroParameter> Parameters,
257 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
260 /// \brief Are macros enabled in the parser?
261 bool areMacrosEnabled() {return MacrosEnabledFlag;}
263 /// \brief Control a flag in the parser that enables or disables macros.
264 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
266 /// \brief Lookup a previously defined macro.
267 /// \param Name Macro name.
268 /// \returns Pointer to macro. NULL if no such macro was defined.
269 const MCAsmMacro* lookupMacro(StringRef Name);
271 /// \brief Define a new macro with the given name and information.
272 void defineMacro(StringRef Name, MCAsmMacro Macro);
274 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
275 void undefineMacro(StringRef Name);
277 /// \brief Are we inside a macro instantiation?
278 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
280 /// \brief Handle entry to macro instantiation.
282 /// \param M The macro.
283 /// \param NameLoc Instantiation location.
284 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
286 /// \brief Handle exit from macro instantiation.
287 void handleMacroExit();
289 /// \brief Extract AsmTokens for a macro argument.
290 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
292 /// \brief Parse all macro arguments for a given macro.
293 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
295 void printMacroInstantiations();
296 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
297 ArrayRef<SMRange> Ranges = None) const {
298 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
300 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
302 /// \brief Enter the specified file. This returns true on failure.
303 bool enterIncludeFile(const std::string &Filename);
305 /// \brief Process the specified file for the .incbin directive.
306 /// This returns true on failure.
307 bool processIncbinFile(const std::string &Filename);
309 /// \brief Reset the current lexer position to that given by \p Loc. The
310 /// current token is not set; clients should ensure Lex() is called
313 /// \param InBuffer If not 0, should be the known buffer id that contains the
315 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
317 /// \brief Parse up to the end of statement and a return the contents from the
318 /// current token until the end of the statement; the current token on exit
319 /// will be either the EndOfStatement or EOF.
320 StringRef parseStringToEndOfStatement() override;
322 /// \brief Parse until the end of a statement or a comma is encountered,
323 /// return the contents from the current token up to the end or comma.
324 StringRef parseStringToComma();
326 bool parseAssignment(StringRef Name, bool allow_redef,
327 bool NoDeadStrip = false);
329 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
330 MCBinaryExpr::Opcode &Kind);
332 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
333 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
334 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
336 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
338 // Generic (target and platform independent) directive parsing.
340 DK_NO_DIRECTIVE, // Placeholder
341 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
342 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
343 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
344 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
345 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
346 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
347 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
348 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
349 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
350 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
351 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
352 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
353 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
354 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
355 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
356 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
357 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
358 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
359 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
360 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
361 DK_MACROS_ON, DK_MACROS_OFF,
362 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
363 DK_SLEB128, DK_ULEB128,
364 DK_ERR, DK_ERROR, DK_WARNING,
368 /// \brief Maps directive name --> DirectiveKind enum, for
369 /// directives parsed by this class.
370 StringMap<DirectiveKind> DirectiveKindMap;
372 // ".ascii", ".asciz", ".string"
373 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
374 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
375 bool parseDirectiveOctaValue(); // ".octa"
376 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
377 bool parseDirectiveFill(); // ".fill"
378 bool parseDirectiveZero(); // ".zero"
379 // ".set", ".equ", ".equiv"
380 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
381 bool parseDirectiveOrg(); // ".org"
382 // ".align{,32}", ".p2align{,w,l}"
383 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
385 // ".file", ".line", ".loc", ".stabs"
386 bool parseDirectiveFile(SMLoc DirectiveLoc);
387 bool parseDirectiveLine();
388 bool parseDirectiveLoc();
389 bool parseDirectiveStabs();
392 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
393 bool parseDirectiveCFIWindowSave();
394 bool parseDirectiveCFISections();
395 bool parseDirectiveCFIStartProc();
396 bool parseDirectiveCFIEndProc();
397 bool parseDirectiveCFIDefCfaOffset();
398 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
399 bool parseDirectiveCFIAdjustCfaOffset();
400 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
401 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
403 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
404 bool parseDirectiveCFIRememberState();
405 bool parseDirectiveCFIRestoreState();
406 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
407 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
408 bool parseDirectiveCFIEscape();
409 bool parseDirectiveCFISignalFrame();
410 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
413 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
414 bool parseDirectiveExitMacro(StringRef Directive);
415 bool parseDirectiveEndMacro(StringRef Directive);
416 bool parseDirectiveMacro(SMLoc DirectiveLoc);
417 bool parseDirectiveMacrosOnOff(StringRef Directive);
419 // ".bundle_align_mode"
420 bool parseDirectiveBundleAlignMode();
422 bool parseDirectiveBundleLock();
424 bool parseDirectiveBundleUnlock();
427 bool parseDirectiveSpace(StringRef IDVal);
429 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
430 bool parseDirectiveLEB128(bool Signed);
432 /// \brief Parse a directive like ".globl" which
433 /// accepts a single symbol (which should be a label or an external).
434 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
436 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
438 bool parseDirectiveAbort(); // ".abort"
439 bool parseDirectiveInclude(); // ".include"
440 bool parseDirectiveIncbin(); // ".incbin"
442 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
443 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
444 // ".ifb" or ".ifnb", depending on ExpectBlank.
445 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
446 // ".ifc" or ".ifnc", depending on ExpectEqual.
447 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
448 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
449 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
450 // ".ifdef" or ".ifndef", depending on expect_defined
451 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
452 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
453 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
454 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
455 bool parseEscapedString(std::string &Data) override;
457 const MCExpr *applyModifierToExpr(const MCExpr *E,
458 MCSymbolRefExpr::VariantKind Variant);
460 // Macro-like directives
461 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
462 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
463 raw_svector_ostream &OS);
464 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
465 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
466 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
467 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
469 // "_emit" or "__emit"
470 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
474 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
477 bool parseDirectiveEnd(SMLoc DirectiveLoc);
479 // ".err" or ".error"
480 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
483 bool parseDirectiveWarning(SMLoc DirectiveLoc);
485 void initializeDirectiveKindMap();
491 extern MCAsmParserExtension *createDarwinAsmParser();
492 extern MCAsmParserExtension *createELFAsmParser();
493 extern MCAsmParserExtension *createCOFFAsmParser();
497 enum { DEFAULT_ADDRSPACE = 0 };
499 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
500 const MCAsmInfo &MAI)
501 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
502 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
503 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
504 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
505 // Save the old handler.
506 SavedDiagHandler = SrcMgr.getDiagHandler();
507 SavedDiagContext = SrcMgr.getDiagContext();
508 // Set our own handler which calls the saved handler.
509 SrcMgr.setDiagHandler(DiagHandler, this);
510 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
512 // Initialize the platform / file format parser.
513 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
514 case MCObjectFileInfo::IsCOFF:
515 PlatformParser.reset(createCOFFAsmParser());
517 case MCObjectFileInfo::IsMachO:
518 PlatformParser.reset(createDarwinAsmParser());
521 case MCObjectFileInfo::IsELF:
522 PlatformParser.reset(createELFAsmParser());
526 PlatformParser->Initialize(*this);
527 initializeDirectiveKindMap();
529 NumOfMacroInstantiations = 0;
532 AsmParser::~AsmParser() {
533 assert((HadError || ActiveMacros.empty()) &&
534 "Unexpected active macro instantiation!");
537 void AsmParser::printMacroInstantiations() {
538 // Print the active macro instantiation stack.
539 for (std::vector<MacroInstantiation *>::const_reverse_iterator
540 it = ActiveMacros.rbegin(),
541 ie = ActiveMacros.rend();
543 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
544 "while in macro instantiation");
547 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
548 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
549 printMacroInstantiations();
552 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
553 if (getTargetParser().getTargetOptions().MCFatalWarnings)
554 return Error(L, Msg, Ranges);
555 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
556 printMacroInstantiations();
560 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
562 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
563 printMacroInstantiations();
567 bool AsmParser::enterIncludeFile(const std::string &Filename) {
568 std::string IncludedFile;
570 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
575 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
579 /// Process the specified .incbin file by searching for it in the include paths
580 /// then just emitting the byte contents of the file to the streamer. This
581 /// returns true on failure.
582 bool AsmParser::processIncbinFile(const std::string &Filename) {
583 std::string IncludedFile;
585 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
589 // Pick up the bytes from the file and emit them.
590 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
594 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
595 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
596 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
600 const AsmToken &AsmParser::Lex() {
601 const AsmToken *tok = &Lexer.Lex();
603 if (tok->is(AsmToken::Eof)) {
604 // If this is the end of an included file, pop the parent file off the
606 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
607 if (ParentIncludeLoc != SMLoc()) {
608 jumpToLoc(ParentIncludeLoc);
613 if (tok->is(AsmToken::Error))
614 Error(Lexer.getErrLoc(), Lexer.getErr());
619 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
620 // Create the initial section, if requested.
621 if (!NoInitialTextSection)
622 Out.InitSections(false);
628 AsmCond StartingCondState = TheCondState;
630 // If we are generating dwarf for assembly source files save the initial text
631 // section and generate a .file directive.
632 if (getContext().getGenDwarfForAssembly()) {
633 MCSection *Sec = getStreamer().getCurrentSection().first;
634 if (!Sec->getBeginSymbol()) {
635 MCSymbol *SectionStartSym = getContext().createTempSymbol();
636 getStreamer().EmitLabel(SectionStartSym);
637 Sec->setBeginSymbol(SectionStartSym);
639 bool InsertResult = getContext().addGenDwarfSection(Sec);
640 assert(InsertResult && ".text section should not have debug info yet");
642 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
643 0, StringRef(), getContext().getMainFileName()));
646 // While we have input, parse each statement.
647 while (Lexer.isNot(AsmToken::Eof)) {
648 ParseStatementInfo Info;
649 if (!parseStatement(Info, nullptr))
652 // We had an error, validate that one was emitted and recover by skipping to
654 assert(HadError && "Parse statement returned an error, but none emitted!");
655 eatToEndOfStatement();
658 if (TheCondState.TheCond != StartingCondState.TheCond ||
659 TheCondState.Ignore != StartingCondState.Ignore)
660 return TokError("unmatched .ifs or .elses");
662 // Check to see there are no empty DwarfFile slots.
663 const auto &LineTables = getContext().getMCDwarfLineTables();
664 if (!LineTables.empty()) {
666 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
667 if (File.Name.empty() && Index != 0)
668 TokError("unassigned file number: " + Twine(Index) +
669 " for .file directives");
674 // Check to see that all assembler local symbols were actually defined.
675 // Targets that don't do subsections via symbols may not want this, though,
676 // so conservatively exclude them. Only do this if we're finalizing, though,
677 // as otherwise we won't necessarilly have seen everything yet.
678 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
679 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
680 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
683 MCSymbol *Sym = i->getValue();
684 // Variable symbols may not be marked as defined, so check those
685 // explicitly. If we know it's a variable, we have a definition for
686 // the purposes of this check.
687 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
688 // FIXME: We would really like to refer back to where the symbol was
689 // first referenced for a source location. We need to add something
690 // to track that. Currently, we just point to the end of the file.
692 getLexer().getLoc(), SourceMgr::DK_Error,
693 "assembler local symbol '" + Sym->getName() + "' not defined");
697 // Finalize the output stream if there are no errors and if the client wants
699 if (!HadError && !NoFinalize)
705 void AsmParser::checkForValidSection() {
706 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
707 TokError("expected section directive before assembly directive");
708 Out.InitSections(false);
712 /// \brief Throw away the rest of the line for testing purposes.
713 void AsmParser::eatToEndOfStatement() {
714 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
718 if (Lexer.is(AsmToken::EndOfStatement))
722 StringRef AsmParser::parseStringToEndOfStatement() {
723 const char *Start = getTok().getLoc().getPointer();
725 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
728 const char *End = getTok().getLoc().getPointer();
729 return StringRef(Start, End - Start);
732 StringRef AsmParser::parseStringToComma() {
733 const char *Start = getTok().getLoc().getPointer();
735 while (Lexer.isNot(AsmToken::EndOfStatement) &&
736 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
739 const char *End = getTok().getLoc().getPointer();
740 return StringRef(Start, End - Start);
743 /// \brief Parse a paren expression and return it.
744 /// NOTE: This assumes the leading '(' has already been consumed.
746 /// parenexpr ::= expr)
748 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
749 if (parseExpression(Res))
751 if (Lexer.isNot(AsmToken::RParen))
752 return TokError("expected ')' in parentheses expression");
753 EndLoc = Lexer.getTok().getEndLoc();
758 /// \brief Parse a bracket expression and return it.
759 /// NOTE: This assumes the leading '[' has already been consumed.
761 /// bracketexpr ::= expr]
763 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
764 if (parseExpression(Res))
766 if (Lexer.isNot(AsmToken::RBrac))
767 return TokError("expected ']' in brackets expression");
768 EndLoc = Lexer.getTok().getEndLoc();
773 /// \brief Parse a primary expression and return it.
774 /// primaryexpr ::= (parenexpr
775 /// primaryexpr ::= symbol
776 /// primaryexpr ::= number
777 /// primaryexpr ::= '.'
778 /// primaryexpr ::= ~,+,- primaryexpr
779 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
780 SMLoc FirstTokenLoc = getLexer().getLoc();
781 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
782 switch (FirstTokenKind) {
784 return TokError("unknown token in expression");
785 // If we have an error assume that we've already handled it.
786 case AsmToken::Error:
788 case AsmToken::Exclaim:
789 Lex(); // Eat the operator.
790 if (parsePrimaryExpr(Res, EndLoc))
792 Res = MCUnaryExpr::CreateLNot(Res, getContext());
794 case AsmToken::Dollar:
796 case AsmToken::String:
797 case AsmToken::Identifier: {
798 StringRef Identifier;
799 if (parseIdentifier(Identifier)) {
800 if (FirstTokenKind == AsmToken::Dollar) {
801 if (Lexer.getMAI().getDollarIsPC()) {
802 // This is a '$' reference, which references the current PC. Emit a
803 // temporary label to the streamer and refer to it.
804 MCSymbol *Sym = Ctx.createTempSymbol();
806 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
808 EndLoc = FirstTokenLoc;
811 return Error(FirstTokenLoc, "invalid token in expression");
814 // Parse symbol variant
815 std::pair<StringRef, StringRef> Split;
816 if (!MAI.useParensForSymbolVariant()) {
817 if (FirstTokenKind == AsmToken::String) {
818 if (Lexer.is(AsmToken::At)) {
819 Lexer.Lex(); // eat @
820 SMLoc AtLoc = getLexer().getLoc();
822 if (parseIdentifier(VName))
823 return Error(AtLoc, "expected symbol variant after '@'");
825 Split = std::make_pair(Identifier, VName);
828 Split = Identifier.split('@');
830 } else if (Lexer.is(AsmToken::LParen)) {
831 Lexer.Lex(); // eat (
833 parseIdentifier(VName);
834 if (Lexer.isNot(AsmToken::RParen)) {
835 return Error(Lexer.getTok().getLoc(),
836 "unexpected token in variant, expected ')'");
838 Lexer.Lex(); // eat )
839 Split = std::make_pair(Identifier, VName);
842 EndLoc = SMLoc::getFromPointer(Identifier.end());
844 // This is a symbol reference.
845 StringRef SymbolName = Identifier;
846 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
848 // Lookup the symbol variant if used.
849 if (Split.second.size()) {
850 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
851 if (Variant != MCSymbolRefExpr::VK_Invalid) {
852 SymbolName = Split.first;
853 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
854 Variant = MCSymbolRefExpr::VK_None;
856 return Error(SMLoc::getFromPointer(Split.second.begin()),
857 "invalid variant '" + Split.second + "'");
861 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
863 // If this is an absolute variable reference, substitute it now to preserve
864 // semantics in the face of reassignment.
865 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
867 return Error(EndLoc, "unexpected modifier on variable reference");
869 Res = Sym->getVariableValue();
873 // Otherwise create a symbol ref.
874 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
877 case AsmToken::BigNum:
878 return TokError("literal value out of range for directive");
879 case AsmToken::Integer: {
880 SMLoc Loc = getTok().getLoc();
881 int64_t IntVal = getTok().getIntVal();
882 Res = MCConstantExpr::Create(IntVal, getContext());
883 EndLoc = Lexer.getTok().getEndLoc();
885 // Look for 'b' or 'f' following an Integer as a directional label
886 if (Lexer.getKind() == AsmToken::Identifier) {
887 StringRef IDVal = getTok().getString();
888 // Lookup the symbol variant if used.
889 std::pair<StringRef, StringRef> Split = IDVal.split('@');
890 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
891 if (Split.first.size() != IDVal.size()) {
892 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
893 if (Variant == MCSymbolRefExpr::VK_Invalid)
894 return TokError("invalid variant '" + Split.second + "'");
897 if (IDVal == "f" || IDVal == "b") {
899 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
900 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
901 if (IDVal == "b" && Sym->isUndefined())
902 return Error(Loc, "invalid reference to undefined symbol");
903 EndLoc = Lexer.getTok().getEndLoc();
904 Lex(); // Eat identifier.
909 case AsmToken::Real: {
910 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
911 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
912 Res = MCConstantExpr::Create(IntVal, getContext());
913 EndLoc = Lexer.getTok().getEndLoc();
917 case AsmToken::Dot: {
918 // This is a '.' reference, which references the current PC. Emit a
919 // temporary label to the streamer and refer to it.
920 MCSymbol *Sym = Ctx.createTempSymbol();
922 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
923 EndLoc = Lexer.getTok().getEndLoc();
924 Lex(); // Eat identifier.
927 case AsmToken::LParen:
928 Lex(); // Eat the '('.
929 return parseParenExpr(Res, EndLoc);
930 case AsmToken::LBrac:
931 if (!PlatformParser->HasBracketExpressions())
932 return TokError("brackets expression not supported on this target");
933 Lex(); // Eat the '['.
934 return parseBracketExpr(Res, EndLoc);
935 case AsmToken::Minus:
936 Lex(); // Eat the operator.
937 if (parsePrimaryExpr(Res, EndLoc))
939 Res = MCUnaryExpr::CreateMinus(Res, getContext());
942 Lex(); // Eat the operator.
943 if (parsePrimaryExpr(Res, EndLoc))
945 Res = MCUnaryExpr::CreatePlus(Res, getContext());
947 case AsmToken::Tilde:
948 Lex(); // Eat the operator.
949 if (parsePrimaryExpr(Res, EndLoc))
951 Res = MCUnaryExpr::CreateNot(Res, getContext());
956 bool AsmParser::parseExpression(const MCExpr *&Res) {
958 return parseExpression(Res, EndLoc);
962 AsmParser::applyModifierToExpr(const MCExpr *E,
963 MCSymbolRefExpr::VariantKind Variant) {
964 // Ask the target implementation about this expression first.
965 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
968 // Recurse over the given expression, rebuilding it to apply the given variant
969 // if there is exactly one symbol.
970 switch (E->getKind()) {
972 case MCExpr::Constant:
975 case MCExpr::SymbolRef: {
976 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
978 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
979 TokError("invalid variant on expression '" + getTok().getIdentifier() +
980 "' (already modified)");
984 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
987 case MCExpr::Unary: {
988 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
989 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
992 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
995 case MCExpr::Binary: {
996 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
997 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
998 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1008 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
1012 llvm_unreachable("Invalid expression kind!");
1015 /// \brief Parse an expression and return it.
1017 /// expr ::= expr &&,|| expr -> lowest.
1018 /// expr ::= expr |,^,&,! expr
1019 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1020 /// expr ::= expr <<,>> expr
1021 /// expr ::= expr +,- expr
1022 /// expr ::= expr *,/,% expr -> highest.
1023 /// expr ::= primaryexpr
1025 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1026 // Parse the expression.
1028 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1031 // As a special case, we support 'a op b @ modifier' by rewriting the
1032 // expression to include the modifier. This is inefficient, but in general we
1033 // expect users to use 'a@modifier op b'.
1034 if (Lexer.getKind() == AsmToken::At) {
1037 if (Lexer.isNot(AsmToken::Identifier))
1038 return TokError("unexpected symbol modifier following '@'");
1040 MCSymbolRefExpr::VariantKind Variant =
1041 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1042 if (Variant == MCSymbolRefExpr::VK_Invalid)
1043 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1045 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1047 return TokError("invalid modifier '" + getTok().getIdentifier() +
1048 "' (no symbols present)");
1055 // Try to constant fold it up front, if possible.
1057 if (Res->EvaluateAsAbsolute(Value))
1058 Res = MCConstantExpr::Create(Value, getContext());
1063 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1065 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1068 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1071 SMLoc StartLoc = Lexer.getLoc();
1072 if (parseExpression(Expr))
1075 if (!Expr->EvaluateAsAbsolute(Res))
1076 return Error(StartLoc, "expected absolute expression");
1081 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1082 MCBinaryExpr::Opcode &Kind) {
1085 return 0; // not a binop.
1087 // Lowest Precedence: &&, ||
1088 case AsmToken::AmpAmp:
1089 Kind = MCBinaryExpr::LAnd;
1091 case AsmToken::PipePipe:
1092 Kind = MCBinaryExpr::LOr;
1095 // Low Precedence: |, &, ^
1097 // FIXME: gas seems to support '!' as an infix operator?
1098 case AsmToken::Pipe:
1099 Kind = MCBinaryExpr::Or;
1101 case AsmToken::Caret:
1102 Kind = MCBinaryExpr::Xor;
1105 Kind = MCBinaryExpr::And;
1108 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1109 case AsmToken::EqualEqual:
1110 Kind = MCBinaryExpr::EQ;
1112 case AsmToken::ExclaimEqual:
1113 case AsmToken::LessGreater:
1114 Kind = MCBinaryExpr::NE;
1116 case AsmToken::Less:
1117 Kind = MCBinaryExpr::LT;
1119 case AsmToken::LessEqual:
1120 Kind = MCBinaryExpr::LTE;
1122 case AsmToken::Greater:
1123 Kind = MCBinaryExpr::GT;
1125 case AsmToken::GreaterEqual:
1126 Kind = MCBinaryExpr::GTE;
1129 // Intermediate Precedence: <<, >>
1130 case AsmToken::LessLess:
1131 Kind = MCBinaryExpr::Shl;
1133 case AsmToken::GreaterGreater:
1134 Kind = MAI.shouldUseLogicalShr() ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1137 // High Intermediate Precedence: +, -
1138 case AsmToken::Plus:
1139 Kind = MCBinaryExpr::Add;
1141 case AsmToken::Minus:
1142 Kind = MCBinaryExpr::Sub;
1145 // Highest Precedence: *, /, %
1146 case AsmToken::Star:
1147 Kind = MCBinaryExpr::Mul;
1149 case AsmToken::Slash:
1150 Kind = MCBinaryExpr::Div;
1152 case AsmToken::Percent:
1153 Kind = MCBinaryExpr::Mod;
1158 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1159 /// Res contains the LHS of the expression on input.
1160 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1163 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1164 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1166 // If the next token is lower precedence than we are allowed to eat, return
1167 // successfully with what we ate already.
1168 if (TokPrec < Precedence)
1173 // Eat the next primary expression.
1175 if (parsePrimaryExpr(RHS, EndLoc))
1178 // If BinOp binds less tightly with RHS than the operator after RHS, let
1179 // the pending operator take RHS as its LHS.
1180 MCBinaryExpr::Opcode Dummy;
1181 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1182 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1185 // Merge LHS and RHS according to operator.
1186 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1191 /// ::= EndOfStatement
1192 /// ::= Label* Directive ...Operands... EndOfStatement
1193 /// ::= Label* Identifier OperandList* EndOfStatement
1194 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1195 MCAsmParserSemaCallback *SI) {
1196 if (Lexer.is(AsmToken::EndOfStatement)) {
1202 // Statements always start with an identifier or are a full line comment.
1203 AsmToken ID = getTok();
1204 SMLoc IDLoc = ID.getLoc();
1206 int64_t LocalLabelVal = -1;
1207 // A full line comment is a '#' as the first token.
1208 if (Lexer.is(AsmToken::Hash))
1209 return parseCppHashLineFilenameComment(IDLoc);
1211 // Allow an integer followed by a ':' as a directional local label.
1212 if (Lexer.is(AsmToken::Integer)) {
1213 LocalLabelVal = getTok().getIntVal();
1214 if (LocalLabelVal < 0) {
1215 if (!TheCondState.Ignore)
1216 return TokError("unexpected token at start of statement");
1219 IDVal = getTok().getString();
1220 Lex(); // Consume the integer token to be used as an identifier token.
1221 if (Lexer.getKind() != AsmToken::Colon) {
1222 if (!TheCondState.Ignore)
1223 return TokError("unexpected token at start of statement");
1226 } else if (Lexer.is(AsmToken::Dot)) {
1227 // Treat '.' as a valid identifier in this context.
1230 } else if (parseIdentifier(IDVal)) {
1231 if (!TheCondState.Ignore)
1232 return TokError("unexpected token at start of statement");
1236 // Handle conditional assembly here before checking for skipping. We
1237 // have to do this so that .endif isn't skipped in a ".if 0" block for
1239 StringMap<DirectiveKind>::const_iterator DirKindIt =
1240 DirectiveKindMap.find(IDVal);
1241 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1243 : DirKindIt->getValue();
1254 return parseDirectiveIf(IDLoc, DirKind);
1256 return parseDirectiveIfb(IDLoc, true);
1258 return parseDirectiveIfb(IDLoc, false);
1260 return parseDirectiveIfc(IDLoc, true);
1262 return parseDirectiveIfeqs(IDLoc, true);
1264 return parseDirectiveIfc(IDLoc, false);
1266 return parseDirectiveIfeqs(IDLoc, false);
1268 return parseDirectiveIfdef(IDLoc, true);
1271 return parseDirectiveIfdef(IDLoc, false);
1273 return parseDirectiveElseIf(IDLoc);
1275 return parseDirectiveElse(IDLoc);
1277 return parseDirectiveEndIf(IDLoc);
1280 // Ignore the statement if in the middle of inactive conditional
1282 if (TheCondState.Ignore) {
1283 eatToEndOfStatement();
1287 // FIXME: Recurse on local labels?
1289 // See what kind of statement we have.
1290 switch (Lexer.getKind()) {
1291 case AsmToken::Colon: {
1292 checkForValidSection();
1294 // identifier ':' -> Label.
1297 // Diagnose attempt to use '.' as a label.
1299 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1301 // Diagnose attempt to use a variable as a label.
1303 // FIXME: Diagnostics. Note the location of the definition as a label.
1304 // FIXME: This doesn't diagnose assignment to a symbol which has been
1305 // implicitly marked as external.
1307 if (LocalLabelVal == -1) {
1308 if (ParsingInlineAsm && SI) {
1309 StringRef RewrittenLabel = SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1310 assert(RewrittenLabel.size() && "We should have an internal name here.");
1311 Info.AsmRewrites->push_back(AsmRewrite(AOK_Label, IDLoc,
1312 IDVal.size(), RewrittenLabel));
1313 IDVal = RewrittenLabel;
1315 Sym = getContext().getOrCreateSymbol(IDVal);
1317 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1319 Sym->redefineIfPossible();
1321 if (!Sym->isUndefined() || Sym->isVariable())
1322 return Error(IDLoc, "invalid symbol redefinition");
1325 if (!ParsingInlineAsm)
1328 // If we are generating dwarf for assembly source files then gather the
1329 // info to make a dwarf label entry for this label if needed.
1330 if (getContext().getGenDwarfForAssembly())
1331 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1334 getTargetParser().onLabelParsed(Sym);
1336 // Consume any end of statement token, if present, to avoid spurious
1337 // AddBlankLine calls().
1338 if (Lexer.is(AsmToken::EndOfStatement)) {
1340 if (Lexer.is(AsmToken::Eof))
1347 case AsmToken::Equal:
1348 // identifier '=' ... -> assignment statement
1351 return parseAssignment(IDVal, true);
1353 default: // Normal instruction or directive.
1357 // If macros are enabled, check to see if this is a macro instantiation.
1358 if (areMacrosEnabled())
1359 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1360 return handleMacroEntry(M, IDLoc);
1363 // Otherwise, we have a normal instruction or directive.
1365 // Directives start with "."
1366 if (IDVal[0] == '.' && IDVal != ".") {
1367 // There are several entities interested in parsing directives:
1369 // 1. The target-specific assembly parser. Some directives are target
1370 // specific or may potentially behave differently on certain targets.
1371 // 2. Asm parser extensions. For example, platform-specific parsers
1372 // (like the ELF parser) register themselves as extensions.
1373 // 3. The generic directive parser implemented by this class. These are
1374 // all the directives that behave in a target and platform independent
1375 // manner, or at least have a default behavior that's shared between
1376 // all targets and platforms.
1378 // First query the target-specific parser. It will return 'true' if it
1379 // isn't interested in this directive.
1380 if (!getTargetParser().ParseDirective(ID))
1383 // Next, check the extension directive map to see if any extension has
1384 // registered itself to parse this directive.
1385 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1386 ExtensionDirectiveMap.lookup(IDVal);
1388 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1390 // Finally, if no one else is interested in this directive, it must be
1391 // generic and familiar to this class.
1397 return parseDirectiveSet(IDVal, true);
1399 return parseDirectiveSet(IDVal, false);
1401 return parseDirectiveAscii(IDVal, false);
1404 return parseDirectiveAscii(IDVal, true);
1406 return parseDirectiveValue(1);
1410 return parseDirectiveValue(2);
1414 return parseDirectiveValue(4);
1417 return parseDirectiveValue(8);
1419 return parseDirectiveOctaValue();
1422 return parseDirectiveRealValue(APFloat::IEEEsingle);
1424 return parseDirectiveRealValue(APFloat::IEEEdouble);
1426 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1427 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1430 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1431 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1434 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1436 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1438 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1440 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1442 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1444 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1446 return parseDirectiveOrg();
1448 return parseDirectiveFill();
1450 return parseDirectiveZero();
1452 eatToEndOfStatement(); // .extern is the default, ignore it.
1456 return parseDirectiveSymbolAttribute(MCSA_Global);
1457 case DK_LAZY_REFERENCE:
1458 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1459 case DK_NO_DEAD_STRIP:
1460 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1461 case DK_SYMBOL_RESOLVER:
1462 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1463 case DK_PRIVATE_EXTERN:
1464 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1466 return parseDirectiveSymbolAttribute(MCSA_Reference);
1467 case DK_WEAK_DEFINITION:
1468 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1469 case DK_WEAK_REFERENCE:
1470 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1471 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1472 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1475 return parseDirectiveComm(/*IsLocal=*/false);
1477 return parseDirectiveComm(/*IsLocal=*/true);
1479 return parseDirectiveAbort();
1481 return parseDirectiveInclude();
1483 return parseDirectiveIncbin();
1486 return TokError(Twine(IDVal) + " not supported yet");
1488 return parseDirectiveRept(IDLoc, IDVal);
1490 return parseDirectiveIrp(IDLoc);
1492 return parseDirectiveIrpc(IDLoc);
1494 return parseDirectiveEndr(IDLoc);
1495 case DK_BUNDLE_ALIGN_MODE:
1496 return parseDirectiveBundleAlignMode();
1497 case DK_BUNDLE_LOCK:
1498 return parseDirectiveBundleLock();
1499 case DK_BUNDLE_UNLOCK:
1500 return parseDirectiveBundleUnlock();
1502 return parseDirectiveLEB128(true);
1504 return parseDirectiveLEB128(false);
1507 return parseDirectiveSpace(IDVal);
1509 return parseDirectiveFile(IDLoc);
1511 return parseDirectiveLine();
1513 return parseDirectiveLoc();
1515 return parseDirectiveStabs();
1516 case DK_CFI_SECTIONS:
1517 return parseDirectiveCFISections();
1518 case DK_CFI_STARTPROC:
1519 return parseDirectiveCFIStartProc();
1520 case DK_CFI_ENDPROC:
1521 return parseDirectiveCFIEndProc();
1522 case DK_CFI_DEF_CFA:
1523 return parseDirectiveCFIDefCfa(IDLoc);
1524 case DK_CFI_DEF_CFA_OFFSET:
1525 return parseDirectiveCFIDefCfaOffset();
1526 case DK_CFI_ADJUST_CFA_OFFSET:
1527 return parseDirectiveCFIAdjustCfaOffset();
1528 case DK_CFI_DEF_CFA_REGISTER:
1529 return parseDirectiveCFIDefCfaRegister(IDLoc);
1531 return parseDirectiveCFIOffset(IDLoc);
1532 case DK_CFI_REL_OFFSET:
1533 return parseDirectiveCFIRelOffset(IDLoc);
1534 case DK_CFI_PERSONALITY:
1535 return parseDirectiveCFIPersonalityOrLsda(true);
1537 return parseDirectiveCFIPersonalityOrLsda(false);
1538 case DK_CFI_REMEMBER_STATE:
1539 return parseDirectiveCFIRememberState();
1540 case DK_CFI_RESTORE_STATE:
1541 return parseDirectiveCFIRestoreState();
1542 case DK_CFI_SAME_VALUE:
1543 return parseDirectiveCFISameValue(IDLoc);
1544 case DK_CFI_RESTORE:
1545 return parseDirectiveCFIRestore(IDLoc);
1547 return parseDirectiveCFIEscape();
1548 case DK_CFI_SIGNAL_FRAME:
1549 return parseDirectiveCFISignalFrame();
1550 case DK_CFI_UNDEFINED:
1551 return parseDirectiveCFIUndefined(IDLoc);
1552 case DK_CFI_REGISTER:
1553 return parseDirectiveCFIRegister(IDLoc);
1554 case DK_CFI_WINDOW_SAVE:
1555 return parseDirectiveCFIWindowSave();
1558 return parseDirectiveMacrosOnOff(IDVal);
1560 return parseDirectiveMacro(IDLoc);
1562 return parseDirectiveExitMacro(IDVal);
1565 return parseDirectiveEndMacro(IDVal);
1567 return parseDirectivePurgeMacro(IDLoc);
1569 return parseDirectiveEnd(IDLoc);
1571 return parseDirectiveError(IDLoc, false);
1573 return parseDirectiveError(IDLoc, true);
1575 return parseDirectiveWarning(IDLoc);
1578 return Error(IDLoc, "unknown directive");
1581 // __asm _emit or __asm __emit
1582 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1583 IDVal == "_EMIT" || IDVal == "__EMIT"))
1584 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1587 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1588 return parseDirectiveMSAlign(IDLoc, Info);
1590 checkForValidSection();
1592 // Canonicalize the opcode to lower case.
1593 std::string OpcodeStr = IDVal.lower();
1594 ParseInstructionInfo IInfo(Info.AsmRewrites);
1595 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1596 Info.ParsedOperands);
1597 Info.ParseError = HadError;
1599 // Dump the parsed representation, if requested.
1600 if (getShowParsedOperands()) {
1601 SmallString<256> Str;
1602 raw_svector_ostream OS(Str);
1603 OS << "parsed instruction: [";
1604 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1607 Info.ParsedOperands[i]->print(OS);
1611 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1614 // If we are generating dwarf for the current section then generate a .loc
1615 // directive for the instruction.
1616 if (!HadError && getContext().getGenDwarfForAssembly() &&
1617 getContext().getGenDwarfSectionSyms().count(
1618 getStreamer().getCurrentSection().first)) {
1620 if (ActiveMacros.empty())
1621 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1623 Line = SrcMgr.FindLineNumber(ActiveMacros.back()->InstantiationLoc,
1624 ActiveMacros.back()->ExitBuffer);
1626 // If we previously parsed a cpp hash file line comment then make sure the
1627 // current Dwarf File is for the CppHashFilename if not then emit the
1628 // Dwarf File table for it and adjust the line number for the .loc.
1629 if (CppHashFilename.size()) {
1630 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1631 0, StringRef(), CppHashFilename);
1632 getContext().setGenDwarfFileNumber(FileNumber);
1634 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1635 // cache with the different Loc from the call above we save the last
1636 // info we queried here with SrcMgr.FindLineNumber().
1637 unsigned CppHashLocLineNo;
1638 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1639 CppHashLocLineNo = LastQueryLine;
1641 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1642 LastQueryLine = CppHashLocLineNo;
1643 LastQueryIDLoc = CppHashLoc;
1644 LastQueryBuffer = CppHashBuf;
1646 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1649 getStreamer().EmitDwarfLocDirective(
1650 getContext().getGenDwarfFileNumber(), Line, 0,
1651 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1655 // If parsing succeeded, match the instruction.
1658 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1659 Info.ParsedOperands, Out,
1660 ErrorInfo, ParsingInlineAsm);
1663 // Don't skip the rest of the line, the instruction parser is responsible for
1668 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1669 /// since they may not be able to be tokenized to get to the end of line token.
1670 void AsmParser::eatToEndOfLine() {
1671 if (!Lexer.is(AsmToken::EndOfStatement))
1672 Lexer.LexUntilEndOfLine();
1677 /// parseCppHashLineFilenameComment as this:
1678 /// ::= # number "filename"
1679 /// or just as a full line comment if it doesn't have a number and a string.
1680 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1681 Lex(); // Eat the hash token.
1683 if (getLexer().isNot(AsmToken::Integer)) {
1684 // Consume the line since in cases it is not a well-formed line directive,
1685 // as if were simply a full line comment.
1690 int64_t LineNumber = getTok().getIntVal();
1693 if (getLexer().isNot(AsmToken::String)) {
1698 StringRef Filename = getTok().getString();
1699 // Get rid of the enclosing quotes.
1700 Filename = Filename.substr(1, Filename.size() - 2);
1702 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1704 CppHashFilename = Filename;
1705 CppHashLineNumber = LineNumber;
1706 CppHashBuf = CurBuffer;
1708 // Ignore any trailing characters, they're just comment.
1713 /// \brief will use the last parsed cpp hash line filename comment
1714 /// for the Filename and LineNo if any in the diagnostic.
1715 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1716 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1717 raw_ostream &OS = errs();
1719 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1720 const SMLoc &DiagLoc = Diag.getLoc();
1721 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1722 unsigned CppHashBuf =
1723 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1725 // Like SourceMgr::printMessage() we need to print the include stack if any
1726 // before printing the message.
1727 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1728 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1729 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
1730 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1731 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1734 // If we have not parsed a cpp hash line filename comment or the source
1735 // manager changed or buffer changed (like in a nested include) then just
1736 // print the normal diagnostic using its Filename and LineNo.
1737 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1738 DiagBuf != CppHashBuf) {
1739 if (Parser->SavedDiagHandler)
1740 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1742 Diag.print(nullptr, OS);
1746 // Use the CppHashFilename and calculate a line number based on the
1747 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1749 const std::string &Filename = Parser->CppHashFilename;
1751 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1752 int CppHashLocLineNo =
1753 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1755 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1757 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1758 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1759 Diag.getLineContents(), Diag.getRanges());
1761 if (Parser->SavedDiagHandler)
1762 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1764 NewDiag.print(nullptr, OS);
1767 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1768 // difference being that that function accepts '@' as part of identifiers and
1769 // we can't do that. AsmLexer.cpp should probably be changed to handle
1770 // '@' as a special case when needed.
1771 static bool isIdentifierChar(char c) {
1772 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1776 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1777 ArrayRef<MCAsmMacroParameter> Parameters,
1778 ArrayRef<MCAsmMacroArgument> A,
1779 bool EnableAtPseudoVariable, const SMLoc &L) {
1780 unsigned NParameters = Parameters.size();
1781 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1782 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1783 return Error(L, "Wrong number of arguments");
1785 // A macro without parameters is handled differently on Darwin:
1786 // gas accepts no arguments and does no substitutions
1787 while (!Body.empty()) {
1788 // Scan for the next substitution.
1789 std::size_t End = Body.size(), Pos = 0;
1790 for (; Pos != End; ++Pos) {
1791 // Check for a substitution or escape.
1792 if (IsDarwin && !NParameters) {
1793 // This macro has no parameters, look for $0, $1, etc.
1794 if (Body[Pos] != '$' || Pos + 1 == End)
1797 char Next = Body[Pos + 1];
1798 if (Next == '$' || Next == 'n' ||
1799 isdigit(static_cast<unsigned char>(Next)))
1802 // This macro has parameters, look for \foo, \bar, etc.
1803 if (Body[Pos] == '\\' && Pos + 1 != End)
1809 OS << Body.slice(0, Pos);
1811 // Check if we reached the end.
1815 if (IsDarwin && !NParameters) {
1816 switch (Body[Pos + 1]) {
1822 // $n => number of arguments
1827 // $[0-9] => argument
1829 // Missing arguments are ignored.
1830 unsigned Index = Body[Pos + 1] - '0';
1831 if (Index >= A.size())
1834 // Otherwise substitute with the token values, with spaces eliminated.
1835 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1836 ie = A[Index].end();
1838 OS << it->getString();
1844 unsigned I = Pos + 1;
1846 // Check for the \@ pseudo-variable.
1847 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
1850 while (isIdentifierChar(Body[I]) && I + 1 != End)
1853 const char *Begin = Body.data() + Pos + 1;
1854 StringRef Argument(Begin, I - (Pos + 1));
1857 if (Argument == "@") {
1858 OS << NumOfMacroInstantiations;
1861 for (; Index < NParameters; ++Index)
1862 if (Parameters[Index].Name == Argument)
1865 if (Index == NParameters) {
1866 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1869 OS << '\\' << Argument;
1873 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1874 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1875 ie = A[Index].end();
1877 // We expect no quotes around the string's contents when
1878 // parsing for varargs.
1879 if (it->getKind() != AsmToken::String || VarargParameter)
1880 OS << it->getString();
1882 OS << it->getStringContents();
1884 Pos += 1 + Argument.size();
1888 // Update the scan point.
1889 Body = Body.substr(Pos);
1895 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
1896 size_t CondStackDepth)
1897 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
1898 CondStackDepth(CondStackDepth) {}
1900 static bool isOperator(AsmToken::TokenKind kind) {
1904 case AsmToken::Plus:
1905 case AsmToken::Minus:
1906 case AsmToken::Tilde:
1907 case AsmToken::Slash:
1908 case AsmToken::Star:
1910 case AsmToken::Equal:
1911 case AsmToken::EqualEqual:
1912 case AsmToken::Pipe:
1913 case AsmToken::PipePipe:
1914 case AsmToken::Caret:
1916 case AsmToken::AmpAmp:
1917 case AsmToken::Exclaim:
1918 case AsmToken::ExclaimEqual:
1919 case AsmToken::Percent:
1920 case AsmToken::Less:
1921 case AsmToken::LessEqual:
1922 case AsmToken::LessLess:
1923 case AsmToken::LessGreater:
1924 case AsmToken::Greater:
1925 case AsmToken::GreaterEqual:
1926 case AsmToken::GreaterGreater:
1932 class AsmLexerSkipSpaceRAII {
1934 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1935 Lexer.setSkipSpace(SkipSpace);
1938 ~AsmLexerSkipSpaceRAII() {
1939 Lexer.setSkipSpace(true);
1947 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1950 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1951 StringRef Str = parseStringToEndOfStatement();
1952 MA.push_back(AsmToken(AsmToken::String, Str));
1957 unsigned ParenLevel = 0;
1958 unsigned AddTokens = 0;
1960 // Darwin doesn't use spaces to delmit arguments.
1961 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1964 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1965 return TokError("unexpected token in macro instantiation");
1967 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1970 if (Lexer.is(AsmToken::Space)) {
1971 Lex(); // Eat spaces
1973 // Spaces can delimit parameters, but could also be part an expression.
1974 // If the token after a space is an operator, add the token and the next
1975 // one into this argument
1977 if (isOperator(Lexer.getKind())) {
1978 // Check to see whether the token is used as an operator,
1979 // or part of an identifier
1980 const char *NextChar = getTok().getEndLoc().getPointer();
1981 if (*NextChar == ' ')
1985 if (!AddTokens && ParenLevel == 0) {
1991 // handleMacroEntry relies on not advancing the lexer here
1992 // to be able to fill in the remaining default parameter values
1993 if (Lexer.is(AsmToken::EndOfStatement))
1996 // Adjust the current parentheses level.
1997 if (Lexer.is(AsmToken::LParen))
1999 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2002 // Append the token to the current argument list.
2003 MA.push_back(getTok());
2009 if (ParenLevel != 0)
2010 return TokError("unbalanced parentheses in macro argument");
2014 // Parse the macro instantiation arguments.
2015 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2016 MCAsmMacroArguments &A) {
2017 const unsigned NParameters = M ? M->Parameters.size() : 0;
2018 bool NamedParametersFound = false;
2019 SmallVector<SMLoc, 4> FALocs;
2021 A.resize(NParameters);
2022 FALocs.resize(NParameters);
2024 // Parse two kinds of macro invocations:
2025 // - macros defined without any parameters accept an arbitrary number of them
2026 // - macros defined with parameters accept at most that many of them
2027 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2028 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2030 SMLoc IDLoc = Lexer.getLoc();
2031 MCAsmMacroParameter FA;
2033 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2034 if (parseIdentifier(FA.Name)) {
2035 Error(IDLoc, "invalid argument identifier for formal argument");
2036 eatToEndOfStatement();
2040 if (!Lexer.is(AsmToken::Equal)) {
2041 TokError("expected '=' after formal parameter identifier");
2042 eatToEndOfStatement();
2047 NamedParametersFound = true;
2050 if (NamedParametersFound && FA.Name.empty()) {
2051 Error(IDLoc, "cannot mix positional and keyword arguments");
2052 eatToEndOfStatement();
2056 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2057 if (parseMacroArgument(FA.Value, Vararg))
2060 unsigned PI = Parameter;
2061 if (!FA.Name.empty()) {
2063 for (FAI = 0; FAI < NParameters; ++FAI)
2064 if (M->Parameters[FAI].Name == FA.Name)
2067 if (FAI >= NParameters) {
2068 assert(M && "expected macro to be defined");
2070 "parameter named '" + FA.Name + "' does not exist for macro '" +
2077 if (!FA.Value.empty()) {
2082 if (FALocs.size() <= PI)
2083 FALocs.resize(PI + 1);
2085 FALocs[PI] = Lexer.getLoc();
2088 // At the end of the statement, fill in remaining arguments that have
2089 // default values. If there aren't any, then the next argument is
2090 // required but missing
2091 if (Lexer.is(AsmToken::EndOfStatement)) {
2092 bool Failure = false;
2093 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2094 if (A[FAI].empty()) {
2095 if (M->Parameters[FAI].Required) {
2096 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2097 "missing value for required parameter "
2098 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2102 if (!M->Parameters[FAI].Value.empty())
2103 A[FAI] = M->Parameters[FAI].Value;
2109 if (Lexer.is(AsmToken::Comma))
2113 return TokError("too many positional arguments");
2116 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2117 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2118 return (I == MacroMap.end()) ? nullptr : &I->getValue();
2121 void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2122 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2125 void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2127 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2128 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2129 // this, although we should protect against infinite loops.
2130 if (ActiveMacros.size() == 20)
2131 return TokError("macros cannot be nested more than 20 levels deep");
2133 MCAsmMacroArguments A;
2134 if (parseMacroArguments(M, A))
2137 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2138 // to hold the macro body with substitutions.
2139 SmallString<256> Buf;
2140 StringRef Body = M->Body;
2141 raw_svector_ostream OS(Buf);
2143 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2146 // We include the .endmacro in the buffer as our cue to exit the macro
2148 OS << ".endmacro\n";
2150 std::unique_ptr<MemoryBuffer> Instantiation =
2151 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2153 // Create the macro instantiation object and add to the current macro
2154 // instantiation stack.
2155 MacroInstantiation *MI = new MacroInstantiation(
2156 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2157 ActiveMacros.push_back(MI);
2159 ++NumOfMacroInstantiations;
2161 // Jump to the macro instantiation and prime the lexer.
2162 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2163 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2169 void AsmParser::handleMacroExit() {
2170 // Jump to the EndOfStatement we should return to, and consume it.
2171 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2174 // Pop the instantiation entry.
2175 delete ActiveMacros.back();
2176 ActiveMacros.pop_back();
2179 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2180 switch (Value->getKind()) {
2181 case MCExpr::Binary: {
2182 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2183 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2185 case MCExpr::Target:
2186 case MCExpr::Constant:
2188 case MCExpr::SymbolRef: {
2190 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2192 return isUsedIn(Sym, S.getVariableValue());
2196 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2199 llvm_unreachable("Unknown expr kind!");
2202 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2204 // FIXME: Use better location, we should use proper tokens.
2205 SMLoc EqualLoc = Lexer.getLoc();
2207 const MCExpr *Value;
2208 if (parseExpression(Value))
2211 // Note: we don't count b as used in "a = b". This is to allow
2215 if (Lexer.isNot(AsmToken::EndOfStatement))
2216 return TokError("unexpected token in assignment");
2218 // Eat the end of statement marker.
2221 // Validate that the LHS is allowed to be a variable (either it has not been
2222 // used as a symbol, or it is an absolute symbol).
2223 MCSymbol *Sym = getContext().lookupSymbol(Name);
2225 // Diagnose assignment to a label.
2227 // FIXME: Diagnostics. Note the location of the definition as a label.
2228 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2229 if (isUsedIn(Sym, Value))
2230 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2231 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2232 ; // Allow redefinitions of undefined symbols only used in directives.
2233 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2234 ; // Allow redefinitions of variables that haven't yet been used.
2235 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2236 return Error(EqualLoc, "redefinition of '" + Name + "'");
2237 else if (!Sym->isVariable())
2238 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2239 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2240 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2243 // Don't count these checks as uses.
2244 Sym->setUsed(false);
2245 } else if (Name == ".") {
2246 if (Out.EmitValueToOffset(Value, 0)) {
2247 Error(EqualLoc, "expected absolute expression");
2248 eatToEndOfStatement();
2252 Sym = getContext().getOrCreateSymbol(Name);
2254 Sym->setRedefinable(allow_redef);
2256 // Do the assignment.
2257 Out.EmitAssignment(Sym, Value);
2259 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2264 /// parseIdentifier:
2267 bool AsmParser::parseIdentifier(StringRef &Res) {
2268 // The assembler has relaxed rules for accepting identifiers, in particular we
2269 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2270 // separate tokens. At this level, we have already lexed so we cannot (currently)
2271 // handle this as a context dependent token, instead we detect adjacent tokens
2272 // and return the combined identifier.
2273 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2274 SMLoc PrefixLoc = getLexer().getLoc();
2276 // Consume the prefix character, and check for a following identifier.
2278 if (Lexer.isNot(AsmToken::Identifier))
2281 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2282 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2285 // Construct the joined identifier and consume the token.
2287 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2292 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2295 Res = getTok().getIdentifier();
2297 Lex(); // Consume the identifier token.
2302 /// parseDirectiveSet:
2303 /// ::= .equ identifier ',' expression
2304 /// ::= .equiv identifier ',' expression
2305 /// ::= .set identifier ',' expression
2306 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2309 if (parseIdentifier(Name))
2310 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2312 if (getLexer().isNot(AsmToken::Comma))
2313 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2316 return parseAssignment(Name, allow_redef, true);
2319 bool AsmParser::parseEscapedString(std::string &Data) {
2320 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2323 StringRef Str = getTok().getStringContents();
2324 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2325 if (Str[i] != '\\') {
2330 // Recognize escaped characters. Note that this escape semantics currently
2331 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2334 return TokError("unexpected backslash at end of string");
2336 // Recognize octal sequences.
2337 if ((unsigned)(Str[i] - '0') <= 7) {
2338 // Consume up to three octal characters.
2339 unsigned Value = Str[i] - '0';
2341 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2343 Value = Value * 8 + (Str[i] - '0');
2345 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2347 Value = Value * 8 + (Str[i] - '0');
2352 return TokError("invalid octal escape sequence (out of range)");
2354 Data += (unsigned char)Value;
2358 // Otherwise recognize individual escapes.
2361 // Just reject invalid escape sequences for now.
2362 return TokError("invalid escape sequence (unrecognized character)");
2364 case 'b': Data += '\b'; break;
2365 case 'f': Data += '\f'; break;
2366 case 'n': Data += '\n'; break;
2367 case 'r': Data += '\r'; break;
2368 case 't': Data += '\t'; break;
2369 case '"': Data += '"'; break;
2370 case '\\': Data += '\\'; break;
2377 /// parseDirectiveAscii:
2378 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2379 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2380 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2381 checkForValidSection();
2384 if (getLexer().isNot(AsmToken::String))
2385 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2388 if (parseEscapedString(Data))
2391 getStreamer().EmitBytes(Data);
2393 getStreamer().EmitBytes(StringRef("\0", 1));
2397 if (getLexer().is(AsmToken::EndOfStatement))
2400 if (getLexer().isNot(AsmToken::Comma))
2401 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2410 /// parseDirectiveValue
2411 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2412 bool AsmParser::parseDirectiveValue(unsigned Size) {
2413 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2414 checkForValidSection();
2417 const MCExpr *Value;
2418 SMLoc ExprLoc = getLexer().getLoc();
2419 if (parseExpression(Value))
2422 // Special case constant expressions to match code generator.
2423 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2424 assert(Size <= 8 && "Invalid size");
2425 uint64_t IntValue = MCE->getValue();
2426 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2427 return Error(ExprLoc, "literal value out of range for directive");
2428 getStreamer().EmitIntValue(IntValue, Size);
2430 getStreamer().EmitValue(Value, Size, ExprLoc);
2432 if (getLexer().is(AsmToken::EndOfStatement))
2435 // FIXME: Improve diagnostic.
2436 if (getLexer().isNot(AsmToken::Comma))
2437 return TokError("unexpected token in directive");
2446 /// ParseDirectiveOctaValue
2447 /// ::= .octa [ hexconstant (, hexconstant)* ]
2448 bool AsmParser::parseDirectiveOctaValue() {
2449 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2450 checkForValidSection();
2453 if (Lexer.getKind() == AsmToken::Error)
2455 if (Lexer.getKind() != AsmToken::Integer &&
2456 Lexer.getKind() != AsmToken::BigNum)
2457 return TokError("unknown token in expression");
2459 SMLoc ExprLoc = getLexer().getLoc();
2460 APInt IntValue = getTok().getAPIntVal();
2464 if (IntValue.isIntN(64)) {
2466 lo = IntValue.getZExtValue();
2467 } else if (IntValue.isIntN(128)) {
2468 // It might actually have more than 128 bits, but the top ones are zero.
2469 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2470 lo = IntValue.getLoBits(64).getZExtValue();
2472 return Error(ExprLoc, "literal value out of range for directive");
2474 if (MAI.isLittleEndian()) {
2475 getStreamer().EmitIntValue(lo, 8);
2476 getStreamer().EmitIntValue(hi, 8);
2478 getStreamer().EmitIntValue(hi, 8);
2479 getStreamer().EmitIntValue(lo, 8);
2482 if (getLexer().is(AsmToken::EndOfStatement))
2485 // FIXME: Improve diagnostic.
2486 if (getLexer().isNot(AsmToken::Comma))
2487 return TokError("unexpected token in directive");
2496 /// parseDirectiveRealValue
2497 /// ::= (.single | .double) [ expression (, expression)* ]
2498 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2499 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2500 checkForValidSection();
2503 // We don't truly support arithmetic on floating point expressions, so we
2504 // have to manually parse unary prefixes.
2506 if (getLexer().is(AsmToken::Minus)) {
2509 } else if (getLexer().is(AsmToken::Plus))
2512 if (getLexer().isNot(AsmToken::Integer) &&
2513 getLexer().isNot(AsmToken::Real) &&
2514 getLexer().isNot(AsmToken::Identifier))
2515 return TokError("unexpected token in directive");
2517 // Convert to an APFloat.
2518 APFloat Value(Semantics);
2519 StringRef IDVal = getTok().getString();
2520 if (getLexer().is(AsmToken::Identifier)) {
2521 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2522 Value = APFloat::getInf(Semantics);
2523 else if (!IDVal.compare_lower("nan"))
2524 Value = APFloat::getNaN(Semantics, false, ~0);
2526 return TokError("invalid floating point literal");
2527 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2528 APFloat::opInvalidOp)
2529 return TokError("invalid floating point literal");
2533 // Consume the numeric token.
2536 // Emit the value as an integer.
2537 APInt AsInt = Value.bitcastToAPInt();
2538 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2539 AsInt.getBitWidth() / 8);
2541 if (getLexer().is(AsmToken::EndOfStatement))
2544 if (getLexer().isNot(AsmToken::Comma))
2545 return TokError("unexpected token in directive");
2554 /// parseDirectiveZero
2555 /// ::= .zero expression
2556 bool AsmParser::parseDirectiveZero() {
2557 checkForValidSection();
2560 if (parseAbsoluteExpression(NumBytes))
2564 if (getLexer().is(AsmToken::Comma)) {
2566 if (parseAbsoluteExpression(Val))
2570 if (getLexer().isNot(AsmToken::EndOfStatement))
2571 return TokError("unexpected token in '.zero' directive");
2575 getStreamer().EmitFill(NumBytes, Val);
2580 /// parseDirectiveFill
2581 /// ::= .fill expression [ , expression [ , expression ] ]
2582 bool AsmParser::parseDirectiveFill() {
2583 checkForValidSection();
2585 SMLoc RepeatLoc = getLexer().getLoc();
2587 if (parseAbsoluteExpression(NumValues))
2590 if (NumValues < 0) {
2592 "'.fill' directive with negative repeat count has no effect");
2596 int64_t FillSize = 1;
2597 int64_t FillExpr = 0;
2599 SMLoc SizeLoc, ExprLoc;
2600 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2601 if (getLexer().isNot(AsmToken::Comma))
2602 return TokError("unexpected token in '.fill' directive");
2605 SizeLoc = getLexer().getLoc();
2606 if (parseAbsoluteExpression(FillSize))
2609 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2610 if (getLexer().isNot(AsmToken::Comma))
2611 return TokError("unexpected token in '.fill' directive");
2614 ExprLoc = getLexer().getLoc();
2615 if (parseAbsoluteExpression(FillExpr))
2618 if (getLexer().isNot(AsmToken::EndOfStatement))
2619 return TokError("unexpected token in '.fill' directive");
2626 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2630 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2634 if (!isUInt<32>(FillExpr) && FillSize > 4)
2635 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2637 if (NumValues > 0) {
2638 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2639 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2640 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2641 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2642 if (NonZeroFillSize < FillSize)
2643 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2650 /// parseDirectiveOrg
2651 /// ::= .org expression [ , expression ]
2652 bool AsmParser::parseDirectiveOrg() {
2653 checkForValidSection();
2655 const MCExpr *Offset;
2656 SMLoc Loc = getTok().getLoc();
2657 if (parseExpression(Offset))
2660 // Parse optional fill expression.
2661 int64_t FillExpr = 0;
2662 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2663 if (getLexer().isNot(AsmToken::Comma))
2664 return TokError("unexpected token in '.org' directive");
2667 if (parseAbsoluteExpression(FillExpr))
2670 if (getLexer().isNot(AsmToken::EndOfStatement))
2671 return TokError("unexpected token in '.org' directive");
2676 // Only limited forms of relocatable expressions are accepted here, it
2677 // has to be relative to the current section. The streamer will return
2678 // 'true' if the expression wasn't evaluatable.
2679 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2680 return Error(Loc, "expected assembly-time absolute expression");
2685 /// parseDirectiveAlign
2686 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2687 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2688 checkForValidSection();
2690 SMLoc AlignmentLoc = getLexer().getLoc();
2692 if (parseAbsoluteExpression(Alignment))
2696 bool HasFillExpr = false;
2697 int64_t FillExpr = 0;
2698 int64_t MaxBytesToFill = 0;
2699 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2700 if (getLexer().isNot(AsmToken::Comma))
2701 return TokError("unexpected token in directive");
2704 // The fill expression can be omitted while specifying a maximum number of
2705 // alignment bytes, e.g:
2707 if (getLexer().isNot(AsmToken::Comma)) {
2709 if (parseAbsoluteExpression(FillExpr))
2713 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2714 if (getLexer().isNot(AsmToken::Comma))
2715 return TokError("unexpected token in directive");
2718 MaxBytesLoc = getLexer().getLoc();
2719 if (parseAbsoluteExpression(MaxBytesToFill))
2722 if (getLexer().isNot(AsmToken::EndOfStatement))
2723 return TokError("unexpected token in directive");
2732 // Compute alignment in bytes.
2734 // FIXME: Diagnose overflow.
2735 if (Alignment >= 32) {
2736 Error(AlignmentLoc, "invalid alignment value");
2740 Alignment = 1ULL << Alignment;
2742 // Reject alignments that aren't a power of two, for gas compatibility.
2743 if (!isPowerOf2_64(Alignment))
2744 Error(AlignmentLoc, "alignment must be a power of 2");
2747 // Diagnose non-sensical max bytes to align.
2748 if (MaxBytesLoc.isValid()) {
2749 if (MaxBytesToFill < 1) {
2750 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2751 "many bytes, ignoring maximum bytes expression");
2755 if (MaxBytesToFill >= Alignment) {
2756 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2762 // Check whether we should use optimal code alignment for this .align
2764 const MCSection *Section = getStreamer().getCurrentSection().first;
2765 assert(Section && "must have section to emit alignment");
2766 bool UseCodeAlign = Section->UseCodeAlign();
2767 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2768 ValueSize == 1 && UseCodeAlign) {
2769 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2771 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2772 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2779 /// parseDirectiveFile
2780 /// ::= .file [number] filename
2781 /// ::= .file number directory filename
2782 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2783 // FIXME: I'm not sure what this is.
2784 int64_t FileNumber = -1;
2785 SMLoc FileNumberLoc = getLexer().getLoc();
2786 if (getLexer().is(AsmToken::Integer)) {
2787 FileNumber = getTok().getIntVal();
2791 return TokError("file number less than one");
2794 if (getLexer().isNot(AsmToken::String))
2795 return TokError("unexpected token in '.file' directive");
2797 // Usually the directory and filename together, otherwise just the directory.
2798 // Allow the strings to have escaped octal character sequence.
2799 std::string Path = getTok().getString();
2800 if (parseEscapedString(Path))
2804 StringRef Directory;
2806 std::string FilenameData;
2807 if (getLexer().is(AsmToken::String)) {
2808 if (FileNumber == -1)
2809 return TokError("explicit path specified, but no file number");
2810 if (parseEscapedString(FilenameData))
2812 Filename = FilenameData;
2819 if (getLexer().isNot(AsmToken::EndOfStatement))
2820 return TokError("unexpected token in '.file' directive");
2822 if (FileNumber == -1)
2823 getStreamer().EmitFileDirective(Filename);
2825 if (getContext().getGenDwarfForAssembly())
2827 "input can't have .file dwarf directives when -g is "
2828 "used to generate dwarf debug info for assembly code");
2830 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2832 Error(FileNumberLoc, "file number already allocated");
2838 /// parseDirectiveLine
2839 /// ::= .line [number]
2840 bool AsmParser::parseDirectiveLine() {
2841 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2842 if (getLexer().isNot(AsmToken::Integer))
2843 return TokError("unexpected token in '.line' directive");
2845 int64_t LineNumber = getTok().getIntVal();
2849 // FIXME: Do something with the .line.
2852 if (getLexer().isNot(AsmToken::EndOfStatement))
2853 return TokError("unexpected token in '.line' directive");
2858 /// parseDirectiveLoc
2859 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2860 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2861 /// The first number is a file number, must have been previously assigned with
2862 /// a .file directive, the second number is the line number and optionally the
2863 /// third number is a column position (zero if not specified). The remaining
2864 /// optional items are .loc sub-directives.
2865 bool AsmParser::parseDirectiveLoc() {
2866 if (getLexer().isNot(AsmToken::Integer))
2867 return TokError("unexpected token in '.loc' directive");
2868 int64_t FileNumber = getTok().getIntVal();
2870 return TokError("file number less than one in '.loc' directive");
2871 if (!getContext().isValidDwarfFileNumber(FileNumber))
2872 return TokError("unassigned file number in '.loc' directive");
2875 int64_t LineNumber = 0;
2876 if (getLexer().is(AsmToken::Integer)) {
2877 LineNumber = getTok().getIntVal();
2879 return TokError("line number less than zero in '.loc' directive");
2883 int64_t ColumnPos = 0;
2884 if (getLexer().is(AsmToken::Integer)) {
2885 ColumnPos = getTok().getIntVal();
2887 return TokError("column position less than zero in '.loc' directive");
2891 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2893 int64_t Discriminator = 0;
2894 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2896 if (getLexer().is(AsmToken::EndOfStatement))
2900 SMLoc Loc = getTok().getLoc();
2901 if (parseIdentifier(Name))
2902 return TokError("unexpected token in '.loc' directive");
2904 if (Name == "basic_block")
2905 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2906 else if (Name == "prologue_end")
2907 Flags |= DWARF2_FLAG_PROLOGUE_END;
2908 else if (Name == "epilogue_begin")
2909 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2910 else if (Name == "is_stmt") {
2911 Loc = getTok().getLoc();
2912 const MCExpr *Value;
2913 if (parseExpression(Value))
2915 // The expression must be the constant 0 or 1.
2916 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2917 int Value = MCE->getValue();
2919 Flags &= ~DWARF2_FLAG_IS_STMT;
2920 else if (Value == 1)
2921 Flags |= DWARF2_FLAG_IS_STMT;
2923 return Error(Loc, "is_stmt value not 0 or 1");
2925 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2927 } else if (Name == "isa") {
2928 Loc = getTok().getLoc();
2929 const MCExpr *Value;
2930 if (parseExpression(Value))
2932 // The expression must be a constant greater or equal to 0.
2933 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2934 int Value = MCE->getValue();
2936 return Error(Loc, "isa number less than zero");
2939 return Error(Loc, "isa number not a constant value");
2941 } else if (Name == "discriminator") {
2942 if (parseAbsoluteExpression(Discriminator))
2945 return Error(Loc, "unknown sub-directive in '.loc' directive");
2948 if (getLexer().is(AsmToken::EndOfStatement))
2953 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2954 Isa, Discriminator, StringRef());
2959 /// parseDirectiveStabs
2960 /// ::= .stabs string, number, number, number
2961 bool AsmParser::parseDirectiveStabs() {
2962 return TokError("unsupported directive '.stabs'");
2965 /// parseDirectiveCFISections
2966 /// ::= .cfi_sections section [, section]
2967 bool AsmParser::parseDirectiveCFISections() {
2972 if (parseIdentifier(Name))
2973 return TokError("Expected an identifier");
2975 if (Name == ".eh_frame")
2977 else if (Name == ".debug_frame")
2980 if (getLexer().is(AsmToken::Comma)) {
2983 if (parseIdentifier(Name))
2984 return TokError("Expected an identifier");
2986 if (Name == ".eh_frame")
2988 else if (Name == ".debug_frame")
2992 getStreamer().EmitCFISections(EH, Debug);
2996 /// parseDirectiveCFIStartProc
2997 /// ::= .cfi_startproc [simple]
2998 bool AsmParser::parseDirectiveCFIStartProc() {
3000 if (getLexer().isNot(AsmToken::EndOfStatement))
3001 if (parseIdentifier(Simple) || Simple != "simple")
3002 return TokError("unexpected token in .cfi_startproc directive");
3004 getStreamer().EmitCFIStartProc(!Simple.empty());
3008 /// parseDirectiveCFIEndProc
3009 /// ::= .cfi_endproc
3010 bool AsmParser::parseDirectiveCFIEndProc() {
3011 getStreamer().EmitCFIEndProc();
3015 /// \brief parse register name or number.
3016 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
3017 SMLoc DirectiveLoc) {
3020 if (getLexer().isNot(AsmToken::Integer)) {
3021 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3023 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
3025 return parseAbsoluteExpression(Register);
3030 /// parseDirectiveCFIDefCfa
3031 /// ::= .cfi_def_cfa register, offset
3032 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3033 int64_t Register = 0;
3034 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3037 if (getLexer().isNot(AsmToken::Comma))
3038 return TokError("unexpected token in directive");
3042 if (parseAbsoluteExpression(Offset))
3045 getStreamer().EmitCFIDefCfa(Register, Offset);
3049 /// parseDirectiveCFIDefCfaOffset
3050 /// ::= .cfi_def_cfa_offset offset
3051 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3053 if (parseAbsoluteExpression(Offset))
3056 getStreamer().EmitCFIDefCfaOffset(Offset);
3060 /// parseDirectiveCFIRegister
3061 /// ::= .cfi_register register, register
3062 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3063 int64_t Register1 = 0;
3064 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3067 if (getLexer().isNot(AsmToken::Comma))
3068 return TokError("unexpected token in directive");
3071 int64_t Register2 = 0;
3072 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3075 getStreamer().EmitCFIRegister(Register1, Register2);
3079 /// parseDirectiveCFIWindowSave
3080 /// ::= .cfi_window_save
3081 bool AsmParser::parseDirectiveCFIWindowSave() {
3082 getStreamer().EmitCFIWindowSave();
3086 /// parseDirectiveCFIAdjustCfaOffset
3087 /// ::= .cfi_adjust_cfa_offset adjustment
3088 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3089 int64_t Adjustment = 0;
3090 if (parseAbsoluteExpression(Adjustment))
3093 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3097 /// parseDirectiveCFIDefCfaRegister
3098 /// ::= .cfi_def_cfa_register register
3099 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3100 int64_t Register = 0;
3101 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3104 getStreamer().EmitCFIDefCfaRegister(Register);
3108 /// parseDirectiveCFIOffset
3109 /// ::= .cfi_offset register, offset
3110 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3111 int64_t Register = 0;
3114 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3117 if (getLexer().isNot(AsmToken::Comma))
3118 return TokError("unexpected token in directive");
3121 if (parseAbsoluteExpression(Offset))
3124 getStreamer().EmitCFIOffset(Register, Offset);
3128 /// parseDirectiveCFIRelOffset
3129 /// ::= .cfi_rel_offset register, offset
3130 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3131 int64_t Register = 0;
3133 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3136 if (getLexer().isNot(AsmToken::Comma))
3137 return TokError("unexpected token in directive");
3141 if (parseAbsoluteExpression(Offset))
3144 getStreamer().EmitCFIRelOffset(Register, Offset);
3148 static bool isValidEncoding(int64_t Encoding) {
3149 if (Encoding & ~0xff)
3152 if (Encoding == dwarf::DW_EH_PE_omit)
3155 const unsigned Format = Encoding & 0xf;
3156 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3157 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3158 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3159 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3162 const unsigned Application = Encoding & 0x70;
3163 if (Application != dwarf::DW_EH_PE_absptr &&
3164 Application != dwarf::DW_EH_PE_pcrel)
3170 /// parseDirectiveCFIPersonalityOrLsda
3171 /// IsPersonality true for cfi_personality, false for cfi_lsda
3172 /// ::= .cfi_personality encoding, [symbol_name]
3173 /// ::= .cfi_lsda encoding, [symbol_name]
3174 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3175 int64_t Encoding = 0;
3176 if (parseAbsoluteExpression(Encoding))
3178 if (Encoding == dwarf::DW_EH_PE_omit)
3181 if (!isValidEncoding(Encoding))
3182 return TokError("unsupported encoding.");
3184 if (getLexer().isNot(AsmToken::Comma))
3185 return TokError("unexpected token in directive");
3189 if (parseIdentifier(Name))
3190 return TokError("expected identifier in directive");
3192 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3195 getStreamer().EmitCFIPersonality(Sym, Encoding);
3197 getStreamer().EmitCFILsda(Sym, Encoding);
3201 /// parseDirectiveCFIRememberState
3202 /// ::= .cfi_remember_state
3203 bool AsmParser::parseDirectiveCFIRememberState() {
3204 getStreamer().EmitCFIRememberState();
3208 /// parseDirectiveCFIRestoreState
3209 /// ::= .cfi_remember_state
3210 bool AsmParser::parseDirectiveCFIRestoreState() {
3211 getStreamer().EmitCFIRestoreState();
3215 /// parseDirectiveCFISameValue
3216 /// ::= .cfi_same_value register
3217 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3218 int64_t Register = 0;
3220 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3223 getStreamer().EmitCFISameValue(Register);
3227 /// parseDirectiveCFIRestore
3228 /// ::= .cfi_restore register
3229 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3230 int64_t Register = 0;
3231 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3234 getStreamer().EmitCFIRestore(Register);
3238 /// parseDirectiveCFIEscape
3239 /// ::= .cfi_escape expression[,...]
3240 bool AsmParser::parseDirectiveCFIEscape() {
3243 if (parseAbsoluteExpression(CurrValue))
3246 Values.push_back((uint8_t)CurrValue);
3248 while (getLexer().is(AsmToken::Comma)) {
3251 if (parseAbsoluteExpression(CurrValue))
3254 Values.push_back((uint8_t)CurrValue);
3257 getStreamer().EmitCFIEscape(Values);
3261 /// parseDirectiveCFISignalFrame
3262 /// ::= .cfi_signal_frame
3263 bool AsmParser::parseDirectiveCFISignalFrame() {
3264 if (getLexer().isNot(AsmToken::EndOfStatement))
3265 return Error(getLexer().getLoc(),
3266 "unexpected token in '.cfi_signal_frame'");
3268 getStreamer().EmitCFISignalFrame();
3272 /// parseDirectiveCFIUndefined
3273 /// ::= .cfi_undefined register
3274 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3275 int64_t Register = 0;
3277 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3280 getStreamer().EmitCFIUndefined(Register);
3284 /// parseDirectiveMacrosOnOff
3287 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3288 if (getLexer().isNot(AsmToken::EndOfStatement))
3289 return Error(getLexer().getLoc(),
3290 "unexpected token in '" + Directive + "' directive");
3292 setMacrosEnabled(Directive == ".macros_on");
3296 /// parseDirectiveMacro
3297 /// ::= .macro name[,] [parameters]
3298 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3300 if (parseIdentifier(Name))
3301 return TokError("expected identifier in '.macro' directive");
3303 if (getLexer().is(AsmToken::Comma))
3306 MCAsmMacroParameters Parameters;
3307 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3309 if (!Parameters.empty() && Parameters.back().Vararg)
3310 return Error(Lexer.getLoc(),
3311 "Vararg parameter '" + Parameters.back().Name +
3312 "' should be last one in the list of parameters.");
3314 MCAsmMacroParameter Parameter;
3315 if (parseIdentifier(Parameter.Name))
3316 return TokError("expected identifier in '.macro' directive");
3318 if (Lexer.is(AsmToken::Colon)) {
3319 Lex(); // consume ':'
3322 StringRef Qualifier;
3324 QualLoc = Lexer.getLoc();
3325 if (parseIdentifier(Qualifier))
3326 return Error(QualLoc, "missing parameter qualifier for "
3327 "'" + Parameter.Name + "' in macro '" + Name + "'");
3329 if (Qualifier == "req")
3330 Parameter.Required = true;
3331 else if (Qualifier == "vararg")
3332 Parameter.Vararg = true;
3334 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3335 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3338 if (getLexer().is(AsmToken::Equal)) {
3343 ParamLoc = Lexer.getLoc();
3344 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3347 if (Parameter.Required)
3348 Warning(ParamLoc, "pointless default value for required parameter "
3349 "'" + Parameter.Name + "' in macro '" + Name + "'");
3352 Parameters.push_back(std::move(Parameter));
3354 if (getLexer().is(AsmToken::Comma))
3358 // Eat the end of statement.
3361 AsmToken EndToken, StartToken = getTok();
3362 unsigned MacroDepth = 0;
3364 // Lex the macro definition.
3366 // Check whether we have reached the end of the file.
3367 if (getLexer().is(AsmToken::Eof))
3368 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3370 // Otherwise, check whether we have reach the .endmacro.
3371 if (getLexer().is(AsmToken::Identifier)) {
3372 if (getTok().getIdentifier() == ".endm" ||
3373 getTok().getIdentifier() == ".endmacro") {
3374 if (MacroDepth == 0) { // Outermost macro.
3375 EndToken = getTok();
3377 if (getLexer().isNot(AsmToken::EndOfStatement))
3378 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3382 // Otherwise we just found the end of an inner macro.
3385 } else if (getTok().getIdentifier() == ".macro") {
3386 // We allow nested macros. Those aren't instantiated until the outermost
3387 // macro is expanded so just ignore them for now.
3392 // Otherwise, scan til the end of the statement.
3393 eatToEndOfStatement();
3396 if (lookupMacro(Name)) {
3397 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3400 const char *BodyStart = StartToken.getLoc().getPointer();
3401 const char *BodyEnd = EndToken.getLoc().getPointer();
3402 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3403 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3404 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
3408 /// checkForBadMacro
3410 /// With the support added for named parameters there may be code out there that
3411 /// is transitioning from positional parameters. In versions of gas that did
3412 /// not support named parameters they would be ignored on the macro definition.
3413 /// But to support both styles of parameters this is not possible so if a macro
3414 /// definition has named parameters but does not use them and has what appears
3415 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3416 /// warning that the positional parameter found in body which have no effect.
3417 /// Hoping the developer will either remove the named parameters from the macro
3418 /// definition so the positional parameters get used if that was what was
3419 /// intended or change the macro to use the named parameters. It is possible
3420 /// this warning will trigger when the none of the named parameters are used
3421 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3422 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3424 ArrayRef<MCAsmMacroParameter> Parameters) {
3425 // If this macro is not defined with named parameters the warning we are
3426 // checking for here doesn't apply.
3427 unsigned NParameters = Parameters.size();
3428 if (NParameters == 0)
3431 bool NamedParametersFound = false;
3432 bool PositionalParametersFound = false;
3434 // Look at the body of the macro for use of both the named parameters and what
3435 // are likely to be positional parameters. This is what expandMacro() is
3436 // doing when it finds the parameters in the body.
3437 while (!Body.empty()) {
3438 // Scan for the next possible parameter.
3439 std::size_t End = Body.size(), Pos = 0;
3440 for (; Pos != End; ++Pos) {
3441 // Check for a substitution or escape.
3442 // This macro is defined with parameters, look for \foo, \bar, etc.
3443 if (Body[Pos] == '\\' && Pos + 1 != End)
3446 // This macro should have parameters, but look for $0, $1, ..., $n too.
3447 if (Body[Pos] != '$' || Pos + 1 == End)
3449 char Next = Body[Pos + 1];
3450 if (Next == '$' || Next == 'n' ||
3451 isdigit(static_cast<unsigned char>(Next)))
3455 // Check if we reached the end.
3459 if (Body[Pos] == '$') {
3460 switch (Body[Pos + 1]) {
3465 // $n => number of arguments
3467 PositionalParametersFound = true;
3470 // $[0-9] => argument
3472 PositionalParametersFound = true;
3478 unsigned I = Pos + 1;
3479 while (isIdentifierChar(Body[I]) && I + 1 != End)
3482 const char *Begin = Body.data() + Pos + 1;
3483 StringRef Argument(Begin, I - (Pos + 1));
3485 for (; Index < NParameters; ++Index)
3486 if (Parameters[Index].Name == Argument)
3489 if (Index == NParameters) {
3490 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3496 NamedParametersFound = true;
3497 Pos += 1 + Argument.size();
3500 // Update the scan point.
3501 Body = Body.substr(Pos);
3504 if (!NamedParametersFound && PositionalParametersFound)
3505 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3506 "used in macro body, possible positional parameter "
3507 "found in body which will have no effect");
3510 /// parseDirectiveExitMacro
3512 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3513 if (getLexer().isNot(AsmToken::EndOfStatement))
3514 return TokError("unexpected token in '" + Directive + "' directive");
3516 if (!isInsideMacroInstantiation())
3517 return TokError("unexpected '" + Directive + "' in file, "
3518 "no current macro definition");
3520 // Exit all conditionals that are active in the current macro.
3521 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3522 TheCondState = TheCondStack.back();
3523 TheCondStack.pop_back();
3530 /// parseDirectiveEndMacro
3533 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3534 if (getLexer().isNot(AsmToken::EndOfStatement))
3535 return TokError("unexpected token in '" + Directive + "' directive");
3537 // If we are inside a macro instantiation, terminate the current
3539 if (isInsideMacroInstantiation()) {
3544 // Otherwise, this .endmacro is a stray entry in the file; well formed
3545 // .endmacro directives are handled during the macro definition parsing.
3546 return TokError("unexpected '" + Directive + "' in file, "
3547 "no current macro definition");
3550 /// parseDirectivePurgeMacro
3552 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3554 if (parseIdentifier(Name))
3555 return TokError("expected identifier in '.purgem' directive");
3557 if (getLexer().isNot(AsmToken::EndOfStatement))
3558 return TokError("unexpected token in '.purgem' directive");
3560 if (!lookupMacro(Name))
3561 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3563 undefineMacro(Name);
3567 /// parseDirectiveBundleAlignMode
3568 /// ::= {.bundle_align_mode} expression
3569 bool AsmParser::parseDirectiveBundleAlignMode() {
3570 checkForValidSection();
3572 // Expect a single argument: an expression that evaluates to a constant
3573 // in the inclusive range 0-30.
3574 SMLoc ExprLoc = getLexer().getLoc();
3575 int64_t AlignSizePow2;
3576 if (parseAbsoluteExpression(AlignSizePow2))
3578 else if (getLexer().isNot(AsmToken::EndOfStatement))
3579 return TokError("unexpected token after expression in"
3580 " '.bundle_align_mode' directive");
3581 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3582 return Error(ExprLoc,
3583 "invalid bundle alignment size (expected between 0 and 30)");
3587 // Because of AlignSizePow2's verified range we can safely truncate it to
3589 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3593 /// parseDirectiveBundleLock
3594 /// ::= {.bundle_lock} [align_to_end]
3595 bool AsmParser::parseDirectiveBundleLock() {
3596 checkForValidSection();
3597 bool AlignToEnd = false;
3599 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3601 SMLoc Loc = getTok().getLoc();
3602 const char *kInvalidOptionError =
3603 "invalid option for '.bundle_lock' directive";
3605 if (parseIdentifier(Option))
3606 return Error(Loc, kInvalidOptionError);
3608 if (Option != "align_to_end")
3609 return Error(Loc, kInvalidOptionError);
3610 else if (getLexer().isNot(AsmToken::EndOfStatement))
3612 "unexpected token after '.bundle_lock' directive option");
3618 getStreamer().EmitBundleLock(AlignToEnd);
3622 /// parseDirectiveBundleLock
3623 /// ::= {.bundle_lock}
3624 bool AsmParser::parseDirectiveBundleUnlock() {
3625 checkForValidSection();
3627 if (getLexer().isNot(AsmToken::EndOfStatement))
3628 return TokError("unexpected token in '.bundle_unlock' directive");
3631 getStreamer().EmitBundleUnlock();
3635 /// parseDirectiveSpace
3636 /// ::= (.skip | .space) expression [ , expression ]
3637 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3638 checkForValidSection();
3641 if (parseAbsoluteExpression(NumBytes))
3644 int64_t FillExpr = 0;
3645 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3646 if (getLexer().isNot(AsmToken::Comma))
3647 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3650 if (parseAbsoluteExpression(FillExpr))
3653 if (getLexer().isNot(AsmToken::EndOfStatement))
3654 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3660 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3663 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3664 getStreamer().EmitFill(NumBytes, FillExpr);
3669 /// parseDirectiveLEB128
3670 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
3671 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3672 checkForValidSection();
3673 const MCExpr *Value;
3676 if (parseExpression(Value))
3680 getStreamer().EmitSLEB128Value(Value);
3682 getStreamer().EmitULEB128Value(Value);
3684 if (getLexer().is(AsmToken::EndOfStatement))
3687 if (getLexer().isNot(AsmToken::Comma))
3688 return TokError("unexpected token in directive");
3695 /// parseDirectiveSymbolAttribute
3696 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3697 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3698 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3701 SMLoc Loc = getTok().getLoc();
3703 if (parseIdentifier(Name))
3704 return Error(Loc, "expected identifier in directive");
3706 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3708 // Assembler local symbols don't make any sense here. Complain loudly.
3709 if (Sym->isTemporary())
3710 return Error(Loc, "non-local symbol required in directive");
3712 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3713 return Error(Loc, "unable to emit symbol attribute");
3715 if (getLexer().is(AsmToken::EndOfStatement))
3718 if (getLexer().isNot(AsmToken::Comma))
3719 return TokError("unexpected token in directive");
3728 /// parseDirectiveComm
3729 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3730 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3731 checkForValidSection();
3733 SMLoc IDLoc = getLexer().getLoc();
3735 if (parseIdentifier(Name))
3736 return TokError("expected identifier in directive");
3738 // Handle the identifier as the key symbol.
3739 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3741 if (getLexer().isNot(AsmToken::Comma))
3742 return TokError("unexpected token in directive");
3746 SMLoc SizeLoc = getLexer().getLoc();
3747 if (parseAbsoluteExpression(Size))
3750 int64_t Pow2Alignment = 0;
3751 SMLoc Pow2AlignmentLoc;
3752 if (getLexer().is(AsmToken::Comma)) {
3754 Pow2AlignmentLoc = getLexer().getLoc();
3755 if (parseAbsoluteExpression(Pow2Alignment))
3758 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3759 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3760 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3762 // If this target takes alignments in bytes (not log) validate and convert.
3763 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3764 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3765 if (!isPowerOf2_64(Pow2Alignment))
3766 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3767 Pow2Alignment = Log2_64(Pow2Alignment);
3771 if (getLexer().isNot(AsmToken::EndOfStatement))
3772 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3776 // NOTE: a size of zero for a .comm should create a undefined symbol
3777 // but a size of .lcomm creates a bss symbol of size zero.
3779 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3780 "be less than zero");
3782 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3783 // may internally end up wanting an alignment in bytes.
3784 // FIXME: Diagnose overflow.
3785 if (Pow2Alignment < 0)
3786 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3787 "alignment, can't be less than zero");
3789 if (!Sym->isUndefined())
3790 return Error(IDLoc, "invalid symbol redefinition");
3792 // Create the Symbol as a common or local common with Size and Pow2Alignment
3794 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3798 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3802 /// parseDirectiveAbort
3803 /// ::= .abort [... message ...]
3804 bool AsmParser::parseDirectiveAbort() {
3805 // FIXME: Use loc from directive.
3806 SMLoc Loc = getLexer().getLoc();
3808 StringRef Str = parseStringToEndOfStatement();
3809 if (getLexer().isNot(AsmToken::EndOfStatement))
3810 return TokError("unexpected token in '.abort' directive");
3815 Error(Loc, ".abort detected. Assembly stopping.");
3817 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3818 // FIXME: Actually abort assembly here.
3823 /// parseDirectiveInclude
3824 /// ::= .include "filename"
3825 bool AsmParser::parseDirectiveInclude() {
3826 if (getLexer().isNot(AsmToken::String))
3827 return TokError("expected string in '.include' directive");
3829 // Allow the strings to have escaped octal character sequence.
3830 std::string Filename;
3831 if (parseEscapedString(Filename))
3833 SMLoc IncludeLoc = getLexer().getLoc();
3836 if (getLexer().isNot(AsmToken::EndOfStatement))
3837 return TokError("unexpected token in '.include' directive");
3839 // Attempt to switch the lexer to the included file before consuming the end
3840 // of statement to avoid losing it when we switch.
3841 if (enterIncludeFile(Filename)) {
3842 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3849 /// parseDirectiveIncbin
3850 /// ::= .incbin "filename"
3851 bool AsmParser::parseDirectiveIncbin() {
3852 if (getLexer().isNot(AsmToken::String))
3853 return TokError("expected string in '.incbin' directive");
3855 // Allow the strings to have escaped octal character sequence.
3856 std::string Filename;
3857 if (parseEscapedString(Filename))
3859 SMLoc IncbinLoc = getLexer().getLoc();
3862 if (getLexer().isNot(AsmToken::EndOfStatement))
3863 return TokError("unexpected token in '.incbin' directive");
3865 // Attempt to process the included file.
3866 if (processIncbinFile(Filename)) {
3867 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3874 /// parseDirectiveIf
3875 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
3876 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
3877 TheCondStack.push_back(TheCondState);
3878 TheCondState.TheCond = AsmCond::IfCond;
3879 if (TheCondState.Ignore) {
3880 eatToEndOfStatement();
3883 if (parseAbsoluteExpression(ExprValue))
3886 if (getLexer().isNot(AsmToken::EndOfStatement))
3887 return TokError("unexpected token in '.if' directive");
3893 llvm_unreachable("unsupported directive");
3898 ExprValue = ExprValue == 0;
3901 ExprValue = ExprValue >= 0;
3904 ExprValue = ExprValue > 0;
3907 ExprValue = ExprValue <= 0;
3910 ExprValue = ExprValue < 0;
3914 TheCondState.CondMet = ExprValue;
3915 TheCondState.Ignore = !TheCondState.CondMet;
3921 /// parseDirectiveIfb
3923 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3924 TheCondStack.push_back(TheCondState);
3925 TheCondState.TheCond = AsmCond::IfCond;
3927 if (TheCondState.Ignore) {
3928 eatToEndOfStatement();
3930 StringRef Str = parseStringToEndOfStatement();
3932 if (getLexer().isNot(AsmToken::EndOfStatement))
3933 return TokError("unexpected token in '.ifb' directive");
3937 TheCondState.CondMet = ExpectBlank == Str.empty();
3938 TheCondState.Ignore = !TheCondState.CondMet;
3944 /// parseDirectiveIfc
3945 /// ::= .ifc string1, string2
3946 /// ::= .ifnc string1, string2
3947 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3948 TheCondStack.push_back(TheCondState);
3949 TheCondState.TheCond = AsmCond::IfCond;
3951 if (TheCondState.Ignore) {
3952 eatToEndOfStatement();
3954 StringRef Str1 = parseStringToComma();
3956 if (getLexer().isNot(AsmToken::Comma))
3957 return TokError("unexpected token in '.ifc' directive");
3961 StringRef Str2 = parseStringToEndOfStatement();
3963 if (getLexer().isNot(AsmToken::EndOfStatement))
3964 return TokError("unexpected token in '.ifc' directive");
3968 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3969 TheCondState.Ignore = !TheCondState.CondMet;
3975 /// parseDirectiveIfeqs
3976 /// ::= .ifeqs string1, string2
3977 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
3978 if (Lexer.isNot(AsmToken::String)) {
3980 TokError("expected string parameter for '.ifeqs' directive");
3982 TokError("expected string parameter for '.ifnes' directive");
3983 eatToEndOfStatement();
3987 StringRef String1 = getTok().getStringContents();
3990 if (Lexer.isNot(AsmToken::Comma)) {
3992 TokError("expected comma after first string for '.ifeqs' directive");
3994 TokError("expected comma after first string for '.ifnes' directive");
3995 eatToEndOfStatement();
4001 if (Lexer.isNot(AsmToken::String)) {
4003 TokError("expected string parameter for '.ifeqs' directive");
4005 TokError("expected string parameter for '.ifnes' directive");
4006 eatToEndOfStatement();
4010 StringRef String2 = getTok().getStringContents();
4013 TheCondStack.push_back(TheCondState);
4014 TheCondState.TheCond = AsmCond::IfCond;
4015 TheCondState.CondMet = ExpectEqual == (String1 == String2);
4016 TheCondState.Ignore = !TheCondState.CondMet;
4021 /// parseDirectiveIfdef
4022 /// ::= .ifdef symbol
4023 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
4025 TheCondStack.push_back(TheCondState);
4026 TheCondState.TheCond = AsmCond::IfCond;
4028 if (TheCondState.Ignore) {
4029 eatToEndOfStatement();
4031 if (parseIdentifier(Name))
4032 return TokError("expected identifier after '.ifdef'");
4036 MCSymbol *Sym = getContext().lookupSymbol(Name);
4039 TheCondState.CondMet = (Sym && !Sym->isUndefined());
4041 TheCondState.CondMet = (!Sym || Sym->isUndefined());
4042 TheCondState.Ignore = !TheCondState.CondMet;
4048 /// parseDirectiveElseIf
4049 /// ::= .elseif expression
4050 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4051 if (TheCondState.TheCond != AsmCond::IfCond &&
4052 TheCondState.TheCond != AsmCond::ElseIfCond)
4053 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4055 TheCondState.TheCond = AsmCond::ElseIfCond;
4057 bool LastIgnoreState = false;
4058 if (!TheCondStack.empty())
4059 LastIgnoreState = TheCondStack.back().Ignore;
4060 if (LastIgnoreState || TheCondState.CondMet) {
4061 TheCondState.Ignore = true;
4062 eatToEndOfStatement();
4065 if (parseAbsoluteExpression(ExprValue))
4068 if (getLexer().isNot(AsmToken::EndOfStatement))
4069 return TokError("unexpected token in '.elseif' directive");
4072 TheCondState.CondMet = ExprValue;
4073 TheCondState.Ignore = !TheCondState.CondMet;
4079 /// parseDirectiveElse
4081 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4082 if (getLexer().isNot(AsmToken::EndOfStatement))
4083 return TokError("unexpected token in '.else' directive");
4087 if (TheCondState.TheCond != AsmCond::IfCond &&
4088 TheCondState.TheCond != AsmCond::ElseIfCond)
4089 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4091 TheCondState.TheCond = AsmCond::ElseCond;
4092 bool LastIgnoreState = false;
4093 if (!TheCondStack.empty())
4094 LastIgnoreState = TheCondStack.back().Ignore;
4095 if (LastIgnoreState || TheCondState.CondMet)
4096 TheCondState.Ignore = true;
4098 TheCondState.Ignore = false;
4103 /// parseDirectiveEnd
4105 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4106 if (getLexer().isNot(AsmToken::EndOfStatement))
4107 return TokError("unexpected token in '.end' directive");
4111 while (Lexer.isNot(AsmToken::Eof))
4117 /// parseDirectiveError
4119 /// ::= .error [string]
4120 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4121 if (!TheCondStack.empty()) {
4122 if (TheCondStack.back().Ignore) {
4123 eatToEndOfStatement();
4129 return Error(L, ".err encountered");
4131 StringRef Message = ".error directive invoked in source file";
4132 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4133 if (Lexer.isNot(AsmToken::String)) {
4134 TokError(".error argument must be a string");
4135 eatToEndOfStatement();
4139 Message = getTok().getStringContents();
4147 /// parseDirectiveWarning
4148 /// ::= .warning [string]
4149 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4150 if (!TheCondStack.empty()) {
4151 if (TheCondStack.back().Ignore) {
4152 eatToEndOfStatement();
4157 StringRef Message = ".warning directive invoked in source file";
4158 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4159 if (Lexer.isNot(AsmToken::String)) {
4160 TokError(".warning argument must be a string");
4161 eatToEndOfStatement();
4165 Message = getTok().getStringContents();
4169 Warning(L, Message);
4173 /// parseDirectiveEndIf
4175 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4176 if (getLexer().isNot(AsmToken::EndOfStatement))
4177 return TokError("unexpected token in '.endif' directive");
4181 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4182 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4184 if (!TheCondStack.empty()) {
4185 TheCondState = TheCondStack.back();
4186 TheCondStack.pop_back();
4192 void AsmParser::initializeDirectiveKindMap() {
4193 DirectiveKindMap[".set"] = DK_SET;
4194 DirectiveKindMap[".equ"] = DK_EQU;
4195 DirectiveKindMap[".equiv"] = DK_EQUIV;
4196 DirectiveKindMap[".ascii"] = DK_ASCII;
4197 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4198 DirectiveKindMap[".string"] = DK_STRING;
4199 DirectiveKindMap[".byte"] = DK_BYTE;
4200 DirectiveKindMap[".short"] = DK_SHORT;
4201 DirectiveKindMap[".value"] = DK_VALUE;
4202 DirectiveKindMap[".2byte"] = DK_2BYTE;
4203 DirectiveKindMap[".long"] = DK_LONG;
4204 DirectiveKindMap[".int"] = DK_INT;
4205 DirectiveKindMap[".4byte"] = DK_4BYTE;
4206 DirectiveKindMap[".quad"] = DK_QUAD;
4207 DirectiveKindMap[".8byte"] = DK_8BYTE;
4208 DirectiveKindMap[".octa"] = DK_OCTA;
4209 DirectiveKindMap[".single"] = DK_SINGLE;
4210 DirectiveKindMap[".float"] = DK_FLOAT;
4211 DirectiveKindMap[".double"] = DK_DOUBLE;
4212 DirectiveKindMap[".align"] = DK_ALIGN;
4213 DirectiveKindMap[".align32"] = DK_ALIGN32;
4214 DirectiveKindMap[".balign"] = DK_BALIGN;
4215 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4216 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4217 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4218 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4219 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4220 DirectiveKindMap[".org"] = DK_ORG;
4221 DirectiveKindMap[".fill"] = DK_FILL;
4222 DirectiveKindMap[".zero"] = DK_ZERO;
4223 DirectiveKindMap[".extern"] = DK_EXTERN;
4224 DirectiveKindMap[".globl"] = DK_GLOBL;
4225 DirectiveKindMap[".global"] = DK_GLOBAL;
4226 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4227 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4228 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4229 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4230 DirectiveKindMap[".reference"] = DK_REFERENCE;
4231 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4232 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4233 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4234 DirectiveKindMap[".comm"] = DK_COMM;
4235 DirectiveKindMap[".common"] = DK_COMMON;
4236 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4237 DirectiveKindMap[".abort"] = DK_ABORT;
4238 DirectiveKindMap[".include"] = DK_INCLUDE;
4239 DirectiveKindMap[".incbin"] = DK_INCBIN;
4240 DirectiveKindMap[".code16"] = DK_CODE16;
4241 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4242 DirectiveKindMap[".rept"] = DK_REPT;
4243 DirectiveKindMap[".rep"] = DK_REPT;
4244 DirectiveKindMap[".irp"] = DK_IRP;
4245 DirectiveKindMap[".irpc"] = DK_IRPC;
4246 DirectiveKindMap[".endr"] = DK_ENDR;
4247 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4248 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4249 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4250 DirectiveKindMap[".if"] = DK_IF;
4251 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4252 DirectiveKindMap[".ifge"] = DK_IFGE;
4253 DirectiveKindMap[".ifgt"] = DK_IFGT;
4254 DirectiveKindMap[".ifle"] = DK_IFLE;
4255 DirectiveKindMap[".iflt"] = DK_IFLT;
4256 DirectiveKindMap[".ifne"] = DK_IFNE;
4257 DirectiveKindMap[".ifb"] = DK_IFB;
4258 DirectiveKindMap[".ifnb"] = DK_IFNB;
4259 DirectiveKindMap[".ifc"] = DK_IFC;
4260 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4261 DirectiveKindMap[".ifnc"] = DK_IFNC;
4262 DirectiveKindMap[".ifnes"] = DK_IFNES;
4263 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4264 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4265 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4266 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4267 DirectiveKindMap[".else"] = DK_ELSE;
4268 DirectiveKindMap[".end"] = DK_END;
4269 DirectiveKindMap[".endif"] = DK_ENDIF;
4270 DirectiveKindMap[".skip"] = DK_SKIP;
4271 DirectiveKindMap[".space"] = DK_SPACE;
4272 DirectiveKindMap[".file"] = DK_FILE;
4273 DirectiveKindMap[".line"] = DK_LINE;
4274 DirectiveKindMap[".loc"] = DK_LOC;
4275 DirectiveKindMap[".stabs"] = DK_STABS;
4276 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4277 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4278 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4279 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4280 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4281 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4282 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4283 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4284 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4285 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4286 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4287 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4288 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4289 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4290 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4291 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4292 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4293 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4294 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4295 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4296 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4297 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4298 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4299 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4300 DirectiveKindMap[".macro"] = DK_MACRO;
4301 DirectiveKindMap[".exitm"] = DK_EXITM;
4302 DirectiveKindMap[".endm"] = DK_ENDM;
4303 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4304 DirectiveKindMap[".purgem"] = DK_PURGEM;
4305 DirectiveKindMap[".err"] = DK_ERR;
4306 DirectiveKindMap[".error"] = DK_ERROR;
4307 DirectiveKindMap[".warning"] = DK_WARNING;
4310 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4311 AsmToken EndToken, StartToken = getTok();
4313 unsigned NestLevel = 0;
4315 // Check whether we have reached the end of the file.
4316 if (getLexer().is(AsmToken::Eof)) {
4317 Error(DirectiveLoc, "no matching '.endr' in definition");
4321 if (Lexer.is(AsmToken::Identifier) &&
4322 (getTok().getIdentifier() == ".rept")) {
4326 // Otherwise, check whether we have reached the .endr.
4327 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4328 if (NestLevel == 0) {
4329 EndToken = getTok();
4331 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4332 TokError("unexpected token in '.endr' directive");
4340 // Otherwise, scan till the end of the statement.
4341 eatToEndOfStatement();
4344 const char *BodyStart = StartToken.getLoc().getPointer();
4345 const char *BodyEnd = EndToken.getLoc().getPointer();
4346 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4348 // We Are Anonymous.
4349 MacroLikeBodies.push_back(
4350 MCAsmMacro(StringRef(), Body, MCAsmMacroParameters()));
4351 return &MacroLikeBodies.back();
4354 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4355 raw_svector_ostream &OS) {
4358 std::unique_ptr<MemoryBuffer> Instantiation =
4359 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4361 // Create the macro instantiation object and add to the current macro
4362 // instantiation stack.
4363 MacroInstantiation *MI = new MacroInstantiation(
4364 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
4365 ActiveMacros.push_back(MI);
4367 // Jump to the macro instantiation and prime the lexer.
4368 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
4369 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
4373 /// parseDirectiveRept
4374 /// ::= .rep | .rept count
4375 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4376 const MCExpr *CountExpr;
4377 SMLoc CountLoc = getTok().getLoc();
4378 if (parseExpression(CountExpr))
4382 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4383 eatToEndOfStatement();
4384 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4388 return Error(CountLoc, "Count is negative");
4390 if (Lexer.isNot(AsmToken::EndOfStatement))
4391 return TokError("unexpected token in '" + Dir + "' directive");
4393 // Eat the end of statement.
4396 // Lex the rept definition.
4397 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4401 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4402 // to hold the macro body with substitutions.
4403 SmallString<256> Buf;
4404 raw_svector_ostream OS(Buf);
4406 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4407 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
4410 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4415 /// parseDirectiveIrp
4416 /// ::= .irp symbol,values
4417 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4418 MCAsmMacroParameter Parameter;
4420 if (parseIdentifier(Parameter.Name))
4421 return TokError("expected identifier in '.irp' directive");
4423 if (Lexer.isNot(AsmToken::Comma))
4424 return TokError("expected comma in '.irp' directive");
4428 MCAsmMacroArguments A;
4429 if (parseMacroArguments(nullptr, A))
4432 // Eat the end of statement.
4435 // Lex the irp definition.
4436 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4440 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4441 // to hold the macro body with substitutions.
4442 SmallString<256> Buf;
4443 raw_svector_ostream OS(Buf);
4445 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4446 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4447 // This is undocumented, but GAS seems to support it.
4448 if (expandMacro(OS, M->Body, Parameter, *i, true, getTok().getLoc()))
4452 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4457 /// parseDirectiveIrpc
4458 /// ::= .irpc symbol,values
4459 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4460 MCAsmMacroParameter Parameter;
4462 if (parseIdentifier(Parameter.Name))
4463 return TokError("expected identifier in '.irpc' directive");
4465 if (Lexer.isNot(AsmToken::Comma))
4466 return TokError("expected comma in '.irpc' directive");
4470 MCAsmMacroArguments A;
4471 if (parseMacroArguments(nullptr, A))
4474 if (A.size() != 1 || A.front().size() != 1)
4475 return TokError("unexpected token in '.irpc' directive");
4477 // Eat the end of statement.
4480 // Lex the irpc definition.
4481 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4485 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4486 // to hold the macro body with substitutions.
4487 SmallString<256> Buf;
4488 raw_svector_ostream OS(Buf);
4490 StringRef Values = A.front().front().getString();
4491 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4492 MCAsmMacroArgument Arg;
4493 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4495 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4496 // This is undocumented, but GAS seems to support it.
4497 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
4501 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4506 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4507 if (ActiveMacros.empty())
4508 return TokError("unmatched '.endr' directive");
4510 // The only .repl that should get here are the ones created by
4511 // instantiateMacroLikeBody.
4512 assert(getLexer().is(AsmToken::EndOfStatement));
4518 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4520 const MCExpr *Value;
4521 SMLoc ExprLoc = getLexer().getLoc();
4522 if (parseExpression(Value))
4524 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4526 return Error(ExprLoc, "unexpected expression in _emit");
4527 uint64_t IntValue = MCE->getValue();
4528 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4529 return Error(ExprLoc, "literal value out of range for directive");
4531 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4535 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4536 const MCExpr *Value;
4537 SMLoc ExprLoc = getLexer().getLoc();
4538 if (parseExpression(Value))
4540 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4542 return Error(ExprLoc, "unexpected expression in align");
4543 uint64_t IntValue = MCE->getValue();
4544 if (!isPowerOf2_64(IntValue))
4545 return Error(ExprLoc, "literal value not a power of two greater then zero");
4547 Info.AsmRewrites->push_back(
4548 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4552 // We are comparing pointers, but the pointers are relative to a single string.
4553 // Thus, this should always be deterministic.
4554 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4555 const AsmRewrite *AsmRewriteB) {
4556 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4558 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4561 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4562 // rewrite to the same location. Make sure the SizeDirective rewrite is
4563 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4564 // ensures the sort algorithm is stable.
4565 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4566 AsmRewritePrecedence[AsmRewriteB->Kind])
4569 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4570 AsmRewritePrecedence[AsmRewriteB->Kind])
4572 llvm_unreachable("Unstable rewrite sort.");
4575 bool AsmParser::parseMSInlineAsm(
4576 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4577 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4578 SmallVectorImpl<std::string> &Constraints,
4579 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4580 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4581 SmallVector<void *, 4> InputDecls;
4582 SmallVector<void *, 4> OutputDecls;
4583 SmallVector<bool, 4> InputDeclsAddressOf;
4584 SmallVector<bool, 4> OutputDeclsAddressOf;
4585 SmallVector<std::string, 4> InputConstraints;
4586 SmallVector<std::string, 4> OutputConstraints;
4587 SmallVector<unsigned, 4> ClobberRegs;
4589 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4594 // While we have input, parse each statement.
4595 unsigned InputIdx = 0;
4596 unsigned OutputIdx = 0;
4597 while (getLexer().isNot(AsmToken::Eof)) {
4598 ParseStatementInfo Info(&AsmStrRewrites);
4599 if (parseStatement(Info, &SI))
4602 if (Info.ParseError)
4605 if (Info.Opcode == ~0U)
4608 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4610 // Build the list of clobbers, outputs and inputs.
4611 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4612 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4615 if (Operand.isImm())
4618 // Register operand.
4619 if (Operand.isReg() && !Operand.needAddressOf() &&
4620 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
4621 unsigned NumDefs = Desc.getNumDefs();
4623 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4624 ClobberRegs.push_back(Operand.getReg());
4628 // Expr/Input or Output.
4629 StringRef SymName = Operand.getSymName();
4630 if (SymName.empty())
4633 void *OpDecl = Operand.getOpDecl();
4637 bool isOutput = (i == 1) && Desc.mayStore();
4638 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4641 OutputDecls.push_back(OpDecl);
4642 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4643 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
4644 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4646 InputDecls.push_back(OpDecl);
4647 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4648 InputConstraints.push_back(Operand.getConstraint().str());
4649 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4653 // Consider implicit defs to be clobbers. Think of cpuid and push.
4654 ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
4655 Desc.getNumImplicitDefs());
4656 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
4659 // Set the number of Outputs and Inputs.
4660 NumOutputs = OutputDecls.size();
4661 NumInputs = InputDecls.size();
4663 // Set the unique clobbers.
4664 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4665 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4667 Clobbers.assign(ClobberRegs.size(), std::string());
4668 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4669 raw_string_ostream OS(Clobbers[I]);
4670 IP->printRegName(OS, ClobberRegs[I]);
4673 // Merge the various outputs and inputs. Output are expected first.
4674 if (NumOutputs || NumInputs) {
4675 unsigned NumExprs = NumOutputs + NumInputs;
4676 OpDecls.resize(NumExprs);
4677 Constraints.resize(NumExprs);
4678 for (unsigned i = 0; i < NumOutputs; ++i) {
4679 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4680 Constraints[i] = OutputConstraints[i];
4682 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4683 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4684 Constraints[j] = InputConstraints[i];
4688 // Build the IR assembly string.
4689 std::string AsmStringIR;
4690 raw_string_ostream OS(AsmStringIR);
4691 StringRef ASMString =
4692 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4693 const char *AsmStart = ASMString.begin();
4694 const char *AsmEnd = ASMString.end();
4695 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4696 for (const AsmRewrite &AR : AsmStrRewrites) {
4697 AsmRewriteKind Kind = AR.Kind;
4698 if (Kind == AOK_Delete)
4701 const char *Loc = AR.Loc.getPointer();
4702 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4704 // Emit everything up to the immediate/expression.
4705 if (unsigned Len = Loc - AsmStart)
4706 OS << StringRef(AsmStart, Len);
4708 // Skip the original expression.
4709 if (Kind == AOK_Skip) {
4710 AsmStart = Loc + AR.Len;
4714 unsigned AdditionalSkip = 0;
4715 // Rewrite expressions in $N notation.
4720 OS << "$$" << AR.Val;
4726 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
4729 OS << '$' << InputIdx++;
4732 OS << '$' << OutputIdx++;
4734 case AOK_SizeDirective:
4737 case 8: OS << "byte ptr "; break;
4738 case 16: OS << "word ptr "; break;
4739 case 32: OS << "dword ptr "; break;
4740 case 64: OS << "qword ptr "; break;
4741 case 80: OS << "xword ptr "; break;
4742 case 128: OS << "xmmword ptr "; break;
4743 case 256: OS << "ymmword ptr "; break;
4750 unsigned Val = AR.Val;
4751 OS << ".align " << Val;
4753 // Skip the original immediate.
4754 assert(Val < 10 && "Expected alignment less then 2^10.");
4755 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4758 case AOK_DotOperator:
4759 // Insert the dot if the user omitted it.
4761 if (AsmStringIR.back() != '.')
4767 // Skip the original expression.
4768 AsmStart = Loc + AR.Len + AdditionalSkip;
4771 // Emit the remainder of the asm string.
4772 if (AsmStart != AsmEnd)
4773 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4775 AsmString = OS.str();
4779 /// \brief Create an MCAsmParser instance.
4780 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4781 MCStreamer &Out, const MCAsmInfo &MAI) {
4782 return new AsmParser(SM, C, Out, MAI);