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"
49 FatalAssemblerWarnings("fatal-assembler-warnings",
50 cl::desc("Consider warnings as error"));
52 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
55 /// \brief Helper types for tracking macro definitions.
56 typedef std::vector<AsmToken> MCAsmMacroArgument;
57 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
59 struct MCAsmMacroParameter {
61 MCAsmMacroArgument Value;
65 MCAsmMacroParameter() : Required(false), Vararg(false) {}
68 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
73 MCAsmMacroParameters Parameters;
76 MCAsmMacro(StringRef N, StringRef B, ArrayRef<MCAsmMacroParameter> P) :
77 Name(N), Body(B), Parameters(P) {}
80 /// \brief Helper class for storing information about an active macro
82 struct MacroInstantiation {
83 /// The macro being instantiated.
84 const MCAsmMacro *TheMacro;
86 /// The macro instantiation with substitutions.
87 MemoryBuffer *Instantiation;
89 /// The location of the instantiation.
90 SMLoc InstantiationLoc;
92 /// The buffer where parsing should resume upon instantiation completion.
95 /// The location where parsing should resume upon instantiation completion.
99 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
103 struct ParseStatementInfo {
104 /// \brief The parsed operands from the last parsed statement.
105 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
107 /// \brief The opcode from the last parsed instruction.
110 /// \brief Was there an error parsing the inline assembly?
113 SmallVectorImpl<AsmRewrite> *AsmRewrites;
115 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
116 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
117 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
119 ~ParseStatementInfo() {
120 // Free any parsed operands.
121 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
122 delete ParsedOperands[i];
123 ParsedOperands.clear();
127 /// \brief The concrete assembly parser instance.
128 class AsmParser : public MCAsmParser {
129 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
130 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
135 const MCAsmInfo &MAI;
137 SourceMgr::DiagHandlerTy SavedDiagHandler;
138 void *SavedDiagContext;
139 MCAsmParserExtension *PlatformParser;
141 /// This is the current buffer index we're lexing from as managed by the
142 /// SourceMgr object.
145 AsmCond TheCondState;
146 std::vector<AsmCond> TheCondStack;
148 /// \brief maps directive names to handler methods in parser
149 /// extensions. Extensions register themselves in this map by calling
150 /// addDirectiveHandler.
151 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
153 /// \brief Map of currently defined macros.
154 StringMap<MCAsmMacro*> MacroMap;
156 /// \brief Stack of active macro instantiations.
157 std::vector<MacroInstantiation*> ActiveMacros;
159 /// \brief List of bodies of anonymous macros.
160 std::deque<MCAsmMacro> MacroLikeBodies;
162 /// Boolean tracking whether macro substitution is enabled.
163 unsigned MacrosEnabledFlag : 1;
165 /// Flag tracking whether any errors have been encountered.
166 unsigned HadError : 1;
168 /// The values from the last parsed cpp hash file line comment if any.
169 StringRef CppHashFilename;
170 int64_t CppHashLineNumber;
173 /// When generating dwarf for assembly source files we need to calculate the
174 /// logical line number based on the last parsed cpp hash file line comment
175 /// and current line. Since this is slow and messes up the SourceMgr's
176 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
177 SMLoc LastQueryIDLoc;
179 unsigned LastQueryLine;
181 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
182 unsigned AssemblerDialect;
184 /// \brief is Darwin compatibility enabled?
187 /// \brief Are we parsing ms-style inline assembly?
188 bool ParsingInlineAsm;
191 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
192 const MCAsmInfo &MAI);
193 virtual ~AsmParser();
195 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
197 void addDirectiveHandler(StringRef Directive,
198 ExtensionDirectiveHandler Handler) override {
199 ExtensionDirectiveMap[Directive] = Handler;
203 /// @name MCAsmParser Interface
206 SourceMgr &getSourceManager() override { return SrcMgr; }
207 MCAsmLexer &getLexer() override { return Lexer; }
208 MCContext &getContext() override { return Ctx; }
209 MCStreamer &getStreamer() override { return Out; }
210 unsigned getAssemblerDialect() override {
211 if (AssemblerDialect == ~0U)
212 return MAI.getAssemblerDialect();
214 return AssemblerDialect;
216 void setAssemblerDialect(unsigned i) override {
217 AssemblerDialect = i;
220 void Note(SMLoc L, const Twine &Msg,
221 ArrayRef<SMRange> Ranges = None) override;
222 bool Warning(SMLoc L, const Twine &Msg,
223 ArrayRef<SMRange> Ranges = None) override;
224 bool Error(SMLoc L, const Twine &Msg,
225 ArrayRef<SMRange> Ranges = None) override;
227 const AsmToken &Lex() override;
229 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
230 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
232 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
233 unsigned &NumOutputs, unsigned &NumInputs,
234 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
235 SmallVectorImpl<std::string> &Constraints,
236 SmallVectorImpl<std::string> &Clobbers,
237 const MCInstrInfo *MII, const MCInstPrinter *IP,
238 MCAsmParserSemaCallback &SI) override;
240 bool parseExpression(const MCExpr *&Res);
241 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
242 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
243 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
244 bool parseAbsoluteExpression(int64_t &Res) override;
246 /// \brief Parse an identifier or string (as a quoted identifier)
247 /// and set \p Res to the identifier contents.
248 bool parseIdentifier(StringRef &Res) override;
249 void eatToEndOfStatement() override;
251 void checkForValidSection() override;
256 bool parseStatement(ParseStatementInfo &Info);
257 void eatToEndOfLine();
258 bool parseCppHashLineFilenameComment(const SMLoc &L);
260 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
261 ArrayRef<MCAsmMacroParameter> Parameters);
262 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
263 ArrayRef<MCAsmMacroParameter> Parameters,
264 ArrayRef<MCAsmMacroArgument> A,
267 /// \brief Are macros enabled in the parser?
268 bool areMacrosEnabled() {return MacrosEnabledFlag;}
270 /// \brief Control a flag in the parser that enables or disables macros.
271 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
273 /// \brief Lookup a previously defined macro.
274 /// \param Name Macro name.
275 /// \returns Pointer to macro. NULL if no such macro was defined.
276 const MCAsmMacro* lookupMacro(StringRef Name);
278 /// \brief Define a new macro with the given name and information.
279 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
281 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
282 void undefineMacro(StringRef Name);
284 /// \brief Are we inside a macro instantiation?
285 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
287 /// \brief Handle entry to macro instantiation.
289 /// \param M The macro.
290 /// \param NameLoc Instantiation location.
291 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
293 /// \brief Handle exit from macro instantiation.
294 void handleMacroExit();
296 /// \brief Extract AsmTokens for a macro argument.
297 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
299 /// \brief Parse all macro arguments for a given macro.
300 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
302 void printMacroInstantiations();
303 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
304 ArrayRef<SMRange> Ranges = None) const {
305 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
307 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
309 /// \brief Enter the specified file. This returns true on failure.
310 bool enterIncludeFile(const std::string &Filename);
312 /// \brief Process the specified file for the .incbin directive.
313 /// This returns true on failure.
314 bool processIncbinFile(const std::string &Filename);
316 /// \brief Reset the current lexer position to that given by \p Loc. The
317 /// current token is not set; clients should ensure Lex() is called
320 /// \param InBuffer If not -1, should be the known buffer id that contains the
322 void jumpToLoc(SMLoc Loc, int InBuffer=-1);
324 /// \brief Parse up to the end of statement and a return the contents from the
325 /// current token until the end of the statement; the current token on exit
326 /// will be either the EndOfStatement or EOF.
327 StringRef parseStringToEndOfStatement() override;
329 /// \brief Parse until the end of a statement or a comma is encountered,
330 /// return the contents from the current token up to the end or comma.
331 StringRef parseStringToComma();
333 bool parseAssignment(StringRef Name, bool allow_redef,
334 bool NoDeadStrip = false);
336 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
337 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
338 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
340 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
342 // Generic (target and platform independent) directive parsing.
344 DK_NO_DIRECTIVE, // Placeholder
345 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
346 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
347 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
348 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
349 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
350 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
351 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
352 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
353 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
354 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
355 DK_IF, DK_IFNE, DK_IFB, DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFDEF,
356 DK_IFNDEF, DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
357 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
358 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
359 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
360 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
361 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
362 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
363 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
364 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
365 DK_SLEB128, DK_ULEB128,
370 /// \brief Maps directive name --> DirectiveKind enum, for
371 /// directives parsed by this class.
372 StringMap<DirectiveKind> DirectiveKindMap;
374 // ".ascii", ".asciz", ".string"
375 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
376 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
377 bool parseDirectiveOctaValue(); // ".octa"
378 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
379 bool parseDirectiveFill(); // ".fill"
380 bool parseDirectiveZero(); // ".zero"
381 // ".set", ".equ", ".equiv"
382 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
383 bool parseDirectiveOrg(); // ".org"
384 // ".align{,32}", ".p2align{,w,l}"
385 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
387 // ".file", ".line", ".loc", ".stabs"
388 bool parseDirectiveFile(SMLoc DirectiveLoc);
389 bool parseDirectiveLine();
390 bool parseDirectiveLoc();
391 bool parseDirectiveStabs();
394 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
395 bool parseDirectiveCFIWindowSave();
396 bool parseDirectiveCFISections();
397 bool parseDirectiveCFIStartProc();
398 bool parseDirectiveCFIEndProc();
399 bool parseDirectiveCFIDefCfaOffset();
400 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
401 bool parseDirectiveCFIAdjustCfaOffset();
402 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
403 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
404 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
405 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
406 bool parseDirectiveCFIRememberState();
407 bool parseDirectiveCFIRestoreState();
408 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
409 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
410 bool parseDirectiveCFIEscape();
411 bool parseDirectiveCFISignalFrame();
412 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
415 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
416 bool parseDirectiveEndMacro(StringRef Directive);
417 bool parseDirectiveMacro(SMLoc DirectiveLoc);
418 bool parseDirectiveMacrosOnOff(StringRef Directive);
420 // ".bundle_align_mode"
421 bool parseDirectiveBundleAlignMode();
423 bool parseDirectiveBundleLock();
425 bool parseDirectiveBundleUnlock();
428 bool parseDirectiveSpace(StringRef IDVal);
430 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
431 bool parseDirectiveLEB128(bool Signed);
433 /// \brief Parse a directive like ".globl" which
434 /// accepts a single symbol (which should be a label or an external).
435 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
437 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
439 bool parseDirectiveAbort(); // ".abort"
440 bool parseDirectiveInclude(); // ".include"
441 bool parseDirectiveIncbin(); // ".incbin"
444 bool parseDirectiveIf(SMLoc DirectiveLoc);
445 // ".ifb" or ".ifnb", depending on ExpectBlank.
446 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
447 // ".ifc" or ".ifnc", depending on ExpectEqual.
448 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
450 bool parseDirectiveIfeqs(SMLoc DirectiveLoc);
451 // ".ifdef" or ".ifndef", depending on expect_defined
452 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
453 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
454 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
455 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
456 bool parseEscapedString(std::string &Data) override;
458 const MCExpr *applyModifierToExpr(const MCExpr *E,
459 MCSymbolRefExpr::VariantKind Variant);
461 // Macro-like directives
462 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
463 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
464 raw_svector_ostream &OS);
465 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
466 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
467 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
468 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
470 // "_emit" or "__emit"
471 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
475 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
478 bool parseDirectiveEnd(SMLoc DirectiveLoc);
480 // ".err" or ".error"
481 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
483 void initializeDirectiveKindMap();
489 extern MCAsmParserExtension *createDarwinAsmParser();
490 extern MCAsmParserExtension *createELFAsmParser();
491 extern MCAsmParserExtension *createCOFFAsmParser();
495 enum { DEFAULT_ADDRSPACE = 0 };
497 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
498 const MCAsmInfo &_MAI)
499 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
500 PlatformParser(nullptr), CurBuffer(0), MacrosEnabledFlag(true),
501 CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false),
502 ParsingInlineAsm(false) {
503 // Save the old handler.
504 SavedDiagHandler = SrcMgr.getDiagHandler();
505 SavedDiagContext = SrcMgr.getDiagContext();
506 // Set our own handler which calls the saved handler.
507 SrcMgr.setDiagHandler(DiagHandler, this);
508 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
510 // Initialize the platform / file format parser.
511 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
512 case MCObjectFileInfo::IsCOFF:
513 PlatformParser = createCOFFAsmParser();
514 PlatformParser->Initialize(*this);
516 case MCObjectFileInfo::IsMachO:
517 PlatformParser = createDarwinAsmParser();
518 PlatformParser->Initialize(*this);
521 case MCObjectFileInfo::IsELF:
522 PlatformParser = createELFAsmParser();
523 PlatformParser->Initialize(*this);
527 initializeDirectiveKindMap();
530 AsmParser::~AsmParser() {
531 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
533 // Destroy any macros.
534 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
537 delete it->getValue();
539 delete PlatformParser;
542 void AsmParser::printMacroInstantiations() {
543 // Print the active macro instantiation stack.
544 for (std::vector<MacroInstantiation *>::const_reverse_iterator
545 it = ActiveMacros.rbegin(),
546 ie = ActiveMacros.rend();
548 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
549 "while in macro instantiation");
552 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
553 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
554 printMacroInstantiations();
557 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
558 if (FatalAssemblerWarnings)
559 return Error(L, Msg, Ranges);
560 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
561 printMacroInstantiations();
565 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
567 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
568 printMacroInstantiations();
572 bool AsmParser::enterIncludeFile(const std::string &Filename) {
573 std::string IncludedFile;
574 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
580 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
585 /// Process the specified .incbin file by searching for it in the include paths
586 /// then just emitting the byte contents of the file to the streamer. This
587 /// returns true on failure.
588 bool AsmParser::processIncbinFile(const std::string &Filename) {
589 std::string IncludedFile;
590 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
594 // Pick up the bytes from the file and emit them.
595 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
599 void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
600 if (InBuffer != -1) {
601 CurBuffer = InBuffer;
603 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
605 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
608 const AsmToken &AsmParser::Lex() {
609 const AsmToken *tok = &Lexer.Lex();
611 if (tok->is(AsmToken::Eof)) {
612 // If this is the end of an included file, pop the parent file off the
614 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
615 if (ParentIncludeLoc != SMLoc()) {
616 jumpToLoc(ParentIncludeLoc);
621 if (tok->is(AsmToken::Error))
622 Error(Lexer.getErrLoc(), Lexer.getErr());
627 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
628 // Create the initial section, if requested.
629 if (!NoInitialTextSection)
636 AsmCond StartingCondState = TheCondState;
638 // If we are generating dwarf for assembly source files save the initial text
639 // section and generate a .file directive.
640 if (getContext().getGenDwarfForAssembly()) {
641 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
642 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
643 getStreamer().EmitLabel(SectionStartSym);
644 getContext().setGenDwarfSectionStartSym(SectionStartSym);
645 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
646 0, StringRef(), getContext().getMainFileName()));
649 // While we have input, parse each statement.
650 while (Lexer.isNot(AsmToken::Eof)) {
651 ParseStatementInfo Info;
652 if (!parseStatement(Info))
655 // We had an error, validate that one was emitted and recover by skipping to
657 assert(HadError && "Parse statement returned an error, but none emitted!");
658 eatToEndOfStatement();
661 if (TheCondState.TheCond != StartingCondState.TheCond ||
662 TheCondState.Ignore != StartingCondState.Ignore)
663 return TokError("unmatched .ifs or .elses");
665 // Check to see there are no empty DwarfFile slots.
666 const auto &LineTables = getContext().getMCDwarfLineTables();
667 if (!LineTables.empty()) {
669 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
670 if (File.Name.empty() && Index != 0)
671 TokError("unassigned file number: " + Twine(Index) +
672 " for .file directives");
677 // Check to see that all assembler local symbols were actually defined.
678 // Targets that don't do subsections via symbols may not want this, though,
679 // so conservatively exclude them. Only do this if we're finalizing, though,
680 // as otherwise we won't necessarilly have seen everything yet.
681 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
682 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
683 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
686 MCSymbol *Sym = i->getValue();
687 // Variable symbols may not be marked as defined, so check those
688 // explicitly. If we know it's a variable, we have a definition for
689 // the purposes of this check.
690 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
691 // FIXME: We would really like to refer back to where the symbol was
692 // first referenced for a source location. We need to add something
693 // to track that. Currently, we just point to the end of the file.
695 getLexer().getLoc(), SourceMgr::DK_Error,
696 "assembler local symbol '" + Sym->getName() + "' not defined");
700 // Finalize the output stream if there are no errors and if the client wants
702 if (!HadError && !NoFinalize)
708 void AsmParser::checkForValidSection() {
709 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
710 TokError("expected section directive before assembly directive");
715 /// \brief Throw away the rest of the line for testing purposes.
716 void AsmParser::eatToEndOfStatement() {
717 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
721 if (Lexer.is(AsmToken::EndOfStatement))
725 StringRef AsmParser::parseStringToEndOfStatement() {
726 const char *Start = getTok().getLoc().getPointer();
728 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
731 const char *End = getTok().getLoc().getPointer();
732 return StringRef(Start, End - Start);
735 StringRef AsmParser::parseStringToComma() {
736 const char *Start = getTok().getLoc().getPointer();
738 while (Lexer.isNot(AsmToken::EndOfStatement) &&
739 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
742 const char *End = getTok().getLoc().getPointer();
743 return StringRef(Start, End - Start);
746 /// \brief Parse a paren expression and return it.
747 /// NOTE: This assumes the leading '(' has already been consumed.
749 /// parenexpr ::= expr)
751 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
752 if (parseExpression(Res))
754 if (Lexer.isNot(AsmToken::RParen))
755 return TokError("expected ')' in parentheses expression");
756 EndLoc = Lexer.getTok().getEndLoc();
761 /// \brief Parse a bracket expression and return it.
762 /// NOTE: This assumes the leading '[' has already been consumed.
764 /// bracketexpr ::= expr]
766 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
767 if (parseExpression(Res))
769 if (Lexer.isNot(AsmToken::RBrac))
770 return TokError("expected ']' in brackets expression");
771 EndLoc = Lexer.getTok().getEndLoc();
776 /// \brief Parse a primary expression and return it.
777 /// primaryexpr ::= (parenexpr
778 /// primaryexpr ::= symbol
779 /// primaryexpr ::= number
780 /// primaryexpr ::= '.'
781 /// primaryexpr ::= ~,+,- primaryexpr
782 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
783 SMLoc FirstTokenLoc = getLexer().getLoc();
784 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
785 switch (FirstTokenKind) {
787 return TokError("unknown token in expression");
788 // If we have an error assume that we've already handled it.
789 case AsmToken::Error:
791 case AsmToken::Exclaim:
792 Lex(); // Eat the operator.
793 if (parsePrimaryExpr(Res, EndLoc))
795 Res = MCUnaryExpr::CreateLNot(Res, getContext());
797 case AsmToken::Dollar:
799 case AsmToken::String:
800 case AsmToken::Identifier: {
801 StringRef Identifier;
802 if (parseIdentifier(Identifier)) {
803 if (FirstTokenKind == AsmToken::Dollar) {
804 if (Lexer.getMAI().getDollarIsPC()) {
805 // This is a '$' reference, which references the current PC. Emit a
806 // temporary label to the streamer and refer to it.
807 MCSymbol *Sym = Ctx.CreateTempSymbol();
809 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
811 EndLoc = FirstTokenLoc;
814 return Error(FirstTokenLoc, "invalid token in expression");
817 // Parse symbol variant
818 std::pair<StringRef, StringRef> Split;
819 if (!MAI.useParensForSymbolVariant()) {
820 Split = Identifier.split('@');
821 } else if (Lexer.is(AsmToken::LParen)) {
822 Lexer.Lex(); // eat (
824 parseIdentifier(VName);
825 if (Lexer.isNot(AsmToken::RParen)) {
826 return Error(Lexer.getTok().getLoc(),
827 "unexpected token in variant, expected ')'");
829 Lexer.Lex(); // eat )
830 Split = std::make_pair(Identifier, VName);
833 EndLoc = SMLoc::getFromPointer(Identifier.end());
835 // This is a symbol reference.
836 StringRef SymbolName = Identifier;
837 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
839 // Lookup the symbol variant if used.
840 if (Split.second.size()) {
841 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
842 if (Variant != MCSymbolRefExpr::VK_Invalid) {
843 SymbolName = Split.first;
844 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
845 Variant = MCSymbolRefExpr::VK_None;
847 return Error(SMLoc::getFromPointer(Split.second.begin()),
848 "invalid variant '" + Split.second + "'");
852 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
854 // If this is an absolute variable reference, substitute it now to preserve
855 // semantics in the face of reassignment.
856 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
858 return Error(EndLoc, "unexpected modifier on variable reference");
860 Res = Sym->getVariableValue();
864 // Otherwise create a symbol ref.
865 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
868 case AsmToken::BigNum:
869 return TokError("literal value out of range for directive");
870 case AsmToken::Integer: {
871 SMLoc Loc = getTok().getLoc();
872 int64_t IntVal = getTok().getIntVal();
873 Res = MCConstantExpr::Create(IntVal, getContext());
874 EndLoc = Lexer.getTok().getEndLoc();
876 // Look for 'b' or 'f' following an Integer as a directional label
877 if (Lexer.getKind() == AsmToken::Identifier) {
878 StringRef IDVal = getTok().getString();
879 // Lookup the symbol variant if used.
880 std::pair<StringRef, StringRef> Split = IDVal.split('@');
881 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
882 if (Split.first.size() != IDVal.size()) {
883 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
884 if (Variant == MCSymbolRefExpr::VK_Invalid)
885 return TokError("invalid variant '" + Split.second + "'");
888 if (IDVal == "f" || IDVal == "b") {
890 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "b");
891 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
892 if (IDVal == "b" && Sym->isUndefined())
893 return Error(Loc, "invalid reference to undefined symbol");
894 EndLoc = Lexer.getTok().getEndLoc();
895 Lex(); // Eat identifier.
900 case AsmToken::Real: {
901 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
902 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
903 Res = MCConstantExpr::Create(IntVal, getContext());
904 EndLoc = Lexer.getTok().getEndLoc();
908 case AsmToken::Dot: {
909 // This is a '.' reference, which references the current PC. Emit a
910 // temporary label to the streamer and refer to it.
911 MCSymbol *Sym = Ctx.CreateTempSymbol();
913 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
914 EndLoc = Lexer.getTok().getEndLoc();
915 Lex(); // Eat identifier.
918 case AsmToken::LParen:
919 Lex(); // Eat the '('.
920 return parseParenExpr(Res, EndLoc);
921 case AsmToken::LBrac:
922 if (!PlatformParser->HasBracketExpressions())
923 return TokError("brackets expression not supported on this target");
924 Lex(); // Eat the '['.
925 return parseBracketExpr(Res, EndLoc);
926 case AsmToken::Minus:
927 Lex(); // Eat the operator.
928 if (parsePrimaryExpr(Res, EndLoc))
930 Res = MCUnaryExpr::CreateMinus(Res, getContext());
933 Lex(); // Eat the operator.
934 if (parsePrimaryExpr(Res, EndLoc))
936 Res = MCUnaryExpr::CreatePlus(Res, getContext());
938 case AsmToken::Tilde:
939 Lex(); // Eat the operator.
940 if (parsePrimaryExpr(Res, EndLoc))
942 Res = MCUnaryExpr::CreateNot(Res, getContext());
947 bool AsmParser::parseExpression(const MCExpr *&Res) {
949 return parseExpression(Res, EndLoc);
953 AsmParser::applyModifierToExpr(const MCExpr *E,
954 MCSymbolRefExpr::VariantKind Variant) {
955 // Ask the target implementation about this expression first.
956 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
959 // Recurse over the given expression, rebuilding it to apply the given variant
960 // if there is exactly one symbol.
961 switch (E->getKind()) {
963 case MCExpr::Constant:
966 case MCExpr::SymbolRef: {
967 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
969 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
970 TokError("invalid variant on expression '" + getTok().getIdentifier() +
971 "' (already modified)");
975 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
978 case MCExpr::Unary: {
979 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
980 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
983 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
986 case MCExpr::Binary: {
987 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
988 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
989 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
999 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
1003 llvm_unreachable("Invalid expression kind!");
1006 /// \brief Parse an expression and return it.
1008 /// expr ::= expr &&,|| expr -> lowest.
1009 /// expr ::= expr |,^,&,! expr
1010 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1011 /// expr ::= expr <<,>> expr
1012 /// expr ::= expr +,- expr
1013 /// expr ::= expr *,/,% expr -> highest.
1014 /// expr ::= primaryexpr
1016 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1017 // Parse the expression.
1019 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1022 // As a special case, we support 'a op b @ modifier' by rewriting the
1023 // expression to include the modifier. This is inefficient, but in general we
1024 // expect users to use 'a@modifier op b'.
1025 if (Lexer.getKind() == AsmToken::At) {
1028 if (Lexer.isNot(AsmToken::Identifier))
1029 return TokError("unexpected symbol modifier following '@'");
1031 MCSymbolRefExpr::VariantKind Variant =
1032 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1033 if (Variant == MCSymbolRefExpr::VK_Invalid)
1034 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1036 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1038 return TokError("invalid modifier '" + getTok().getIdentifier() +
1039 "' (no symbols present)");
1046 // Try to constant fold it up front, if possible.
1048 if (Res->EvaluateAsAbsolute(Value))
1049 Res = MCConstantExpr::Create(Value, getContext());
1054 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1056 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1059 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1062 SMLoc StartLoc = Lexer.getLoc();
1063 if (parseExpression(Expr))
1066 if (!Expr->EvaluateAsAbsolute(Res))
1067 return Error(StartLoc, "expected absolute expression");
1072 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1073 MCBinaryExpr::Opcode &Kind) {
1076 return 0; // not a binop.
1078 // Lowest Precedence: &&, ||
1079 case AsmToken::AmpAmp:
1080 Kind = MCBinaryExpr::LAnd;
1082 case AsmToken::PipePipe:
1083 Kind = MCBinaryExpr::LOr;
1086 // Low Precedence: |, &, ^
1088 // FIXME: gas seems to support '!' as an infix operator?
1089 case AsmToken::Pipe:
1090 Kind = MCBinaryExpr::Or;
1092 case AsmToken::Caret:
1093 Kind = MCBinaryExpr::Xor;
1096 Kind = MCBinaryExpr::And;
1099 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1100 case AsmToken::EqualEqual:
1101 Kind = MCBinaryExpr::EQ;
1103 case AsmToken::ExclaimEqual:
1104 case AsmToken::LessGreater:
1105 Kind = MCBinaryExpr::NE;
1107 case AsmToken::Less:
1108 Kind = MCBinaryExpr::LT;
1110 case AsmToken::LessEqual:
1111 Kind = MCBinaryExpr::LTE;
1113 case AsmToken::Greater:
1114 Kind = MCBinaryExpr::GT;
1116 case AsmToken::GreaterEqual:
1117 Kind = MCBinaryExpr::GTE;
1120 // Intermediate Precedence: <<, >>
1121 case AsmToken::LessLess:
1122 Kind = MCBinaryExpr::Shl;
1124 case AsmToken::GreaterGreater:
1125 Kind = MCBinaryExpr::Shr;
1128 // High Intermediate Precedence: +, -
1129 case AsmToken::Plus:
1130 Kind = MCBinaryExpr::Add;
1132 case AsmToken::Minus:
1133 Kind = MCBinaryExpr::Sub;
1136 // Highest Precedence: *, /, %
1137 case AsmToken::Star:
1138 Kind = MCBinaryExpr::Mul;
1140 case AsmToken::Slash:
1141 Kind = MCBinaryExpr::Div;
1143 case AsmToken::Percent:
1144 Kind = MCBinaryExpr::Mod;
1149 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1150 /// Res contains the LHS of the expression on input.
1151 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1154 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1155 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1157 // If the next token is lower precedence than we are allowed to eat, return
1158 // successfully with what we ate already.
1159 if (TokPrec < Precedence)
1164 // Eat the next primary expression.
1166 if (parsePrimaryExpr(RHS, EndLoc))
1169 // If BinOp binds less tightly with RHS than the operator after RHS, let
1170 // the pending operator take RHS as its LHS.
1171 MCBinaryExpr::Opcode Dummy;
1172 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1173 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1176 // Merge LHS and RHS according to operator.
1177 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1182 /// ::= EndOfStatement
1183 /// ::= Label* Directive ...Operands... EndOfStatement
1184 /// ::= Label* Identifier OperandList* EndOfStatement
1185 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1186 if (Lexer.is(AsmToken::EndOfStatement)) {
1192 // Statements always start with an identifier or are a full line comment.
1193 AsmToken ID = getTok();
1194 SMLoc IDLoc = ID.getLoc();
1196 int64_t LocalLabelVal = -1;
1197 // A full line comment is a '#' as the first token.
1198 if (Lexer.is(AsmToken::Hash))
1199 return parseCppHashLineFilenameComment(IDLoc);
1201 // Allow an integer followed by a ':' as a directional local label.
1202 if (Lexer.is(AsmToken::Integer)) {
1203 LocalLabelVal = getTok().getIntVal();
1204 if (LocalLabelVal < 0) {
1205 if (!TheCondState.Ignore)
1206 return TokError("unexpected token at start of statement");
1209 IDVal = getTok().getString();
1210 Lex(); // Consume the integer token to be used as an identifier token.
1211 if (Lexer.getKind() != AsmToken::Colon) {
1212 if (!TheCondState.Ignore)
1213 return TokError("unexpected token at start of statement");
1216 } else if (Lexer.is(AsmToken::Dot)) {
1217 // Treat '.' as a valid identifier in this context.
1220 } else if (parseIdentifier(IDVal)) {
1221 if (!TheCondState.Ignore)
1222 return TokError("unexpected token at start of statement");
1226 // Handle conditional assembly here before checking for skipping. We
1227 // have to do this so that .endif isn't skipped in a ".if 0" block for
1229 StringMap<DirectiveKind>::const_iterator DirKindIt =
1230 DirectiveKindMap.find(IDVal);
1231 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1233 : DirKindIt->getValue();
1239 return parseDirectiveIf(IDLoc);
1241 return parseDirectiveIfb(IDLoc, true);
1243 return parseDirectiveIfb(IDLoc, false);
1245 return parseDirectiveIfc(IDLoc, true);
1247 return parseDirectiveIfeqs(IDLoc);
1249 return parseDirectiveIfc(IDLoc, false);
1251 return parseDirectiveIfdef(IDLoc, true);
1254 return parseDirectiveIfdef(IDLoc, false);
1256 return parseDirectiveElseIf(IDLoc);
1258 return parseDirectiveElse(IDLoc);
1260 return parseDirectiveEndIf(IDLoc);
1263 // Ignore the statement if in the middle of inactive conditional
1265 if (TheCondState.Ignore) {
1266 eatToEndOfStatement();
1270 // FIXME: Recurse on local labels?
1272 // See what kind of statement we have.
1273 switch (Lexer.getKind()) {
1274 case AsmToken::Colon: {
1275 checkForValidSection();
1277 // identifier ':' -> Label.
1280 // Diagnose attempt to use '.' as a label.
1282 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1284 // Diagnose attempt to use a variable as a label.
1286 // FIXME: Diagnostics. Note the location of the definition as a label.
1287 // FIXME: This doesn't diagnose assignment to a symbol which has been
1288 // implicitly marked as external.
1290 if (LocalLabelVal == -1)
1291 Sym = getContext().GetOrCreateSymbol(IDVal);
1293 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1294 if (!Sym->isUndefined() || Sym->isVariable())
1295 return Error(IDLoc, "invalid symbol redefinition");
1298 if (!ParsingInlineAsm)
1301 // If we are generating dwarf for assembly source files then gather the
1302 // info to make a dwarf label entry for this label if needed.
1303 if (getContext().getGenDwarfForAssembly())
1304 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1307 getTargetParser().onLabelParsed(Sym);
1309 // Consume any end of statement token, if present, to avoid spurious
1310 // AddBlankLine calls().
1311 if (Lexer.is(AsmToken::EndOfStatement)) {
1313 if (Lexer.is(AsmToken::Eof))
1320 case AsmToken::Equal:
1321 // identifier '=' ... -> assignment statement
1324 return parseAssignment(IDVal, true);
1326 default: // Normal instruction or directive.
1330 // If macros are enabled, check to see if this is a macro instantiation.
1331 if (areMacrosEnabled())
1332 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1333 return handleMacroEntry(M, IDLoc);
1336 // Otherwise, we have a normal instruction or directive.
1338 // Directives start with "."
1339 if (IDVal[0] == '.' && IDVal != ".") {
1340 // There are several entities interested in parsing directives:
1342 // 1. The target-specific assembly parser. Some directives are target
1343 // specific or may potentially behave differently on certain targets.
1344 // 2. Asm parser extensions. For example, platform-specific parsers
1345 // (like the ELF parser) register themselves as extensions.
1346 // 3. The generic directive parser implemented by this class. These are
1347 // all the directives that behave in a target and platform independent
1348 // manner, or at least have a default behavior that's shared between
1349 // all targets and platforms.
1351 // First query the target-specific parser. It will return 'true' if it
1352 // isn't interested in this directive.
1353 if (!getTargetParser().ParseDirective(ID))
1356 // Next, check the extension directive map to see if any extension has
1357 // registered itself to parse this directive.
1358 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1359 ExtensionDirectiveMap.lookup(IDVal);
1361 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1363 // Finally, if no one else is interested in this directive, it must be
1364 // generic and familiar to this class.
1370 return parseDirectiveSet(IDVal, true);
1372 return parseDirectiveSet(IDVal, false);
1374 return parseDirectiveAscii(IDVal, false);
1377 return parseDirectiveAscii(IDVal, true);
1379 return parseDirectiveValue(1);
1383 return parseDirectiveValue(2);
1387 return parseDirectiveValue(4);
1390 return parseDirectiveValue(8);
1392 return parseDirectiveOctaValue();
1395 return parseDirectiveRealValue(APFloat::IEEEsingle);
1397 return parseDirectiveRealValue(APFloat::IEEEdouble);
1399 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1400 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1403 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1404 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1407 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1409 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1411 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1413 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1415 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1417 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1419 return parseDirectiveOrg();
1421 return parseDirectiveFill();
1423 return parseDirectiveZero();
1425 eatToEndOfStatement(); // .extern is the default, ignore it.
1429 return parseDirectiveSymbolAttribute(MCSA_Global);
1430 case DK_LAZY_REFERENCE:
1431 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1432 case DK_NO_DEAD_STRIP:
1433 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1434 case DK_SYMBOL_RESOLVER:
1435 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1436 case DK_PRIVATE_EXTERN:
1437 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1439 return parseDirectiveSymbolAttribute(MCSA_Reference);
1440 case DK_WEAK_DEFINITION:
1441 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1442 case DK_WEAK_REFERENCE:
1443 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1444 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1445 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1448 return parseDirectiveComm(/*IsLocal=*/false);
1450 return parseDirectiveComm(/*IsLocal=*/true);
1452 return parseDirectiveAbort();
1454 return parseDirectiveInclude();
1456 return parseDirectiveIncbin();
1459 return TokError(Twine(IDVal) + " not supported yet");
1461 return parseDirectiveRept(IDLoc, IDVal);
1463 return parseDirectiveIrp(IDLoc);
1465 return parseDirectiveIrpc(IDLoc);
1467 return parseDirectiveEndr(IDLoc);
1468 case DK_BUNDLE_ALIGN_MODE:
1469 return parseDirectiveBundleAlignMode();
1470 case DK_BUNDLE_LOCK:
1471 return parseDirectiveBundleLock();
1472 case DK_BUNDLE_UNLOCK:
1473 return parseDirectiveBundleUnlock();
1475 return parseDirectiveLEB128(true);
1477 return parseDirectiveLEB128(false);
1480 return parseDirectiveSpace(IDVal);
1482 return parseDirectiveFile(IDLoc);
1484 return parseDirectiveLine();
1486 return parseDirectiveLoc();
1488 return parseDirectiveStabs();
1489 case DK_CFI_SECTIONS:
1490 return parseDirectiveCFISections();
1491 case DK_CFI_STARTPROC:
1492 return parseDirectiveCFIStartProc();
1493 case DK_CFI_ENDPROC:
1494 return parseDirectiveCFIEndProc();
1495 case DK_CFI_DEF_CFA:
1496 return parseDirectiveCFIDefCfa(IDLoc);
1497 case DK_CFI_DEF_CFA_OFFSET:
1498 return parseDirectiveCFIDefCfaOffset();
1499 case DK_CFI_ADJUST_CFA_OFFSET:
1500 return parseDirectiveCFIAdjustCfaOffset();
1501 case DK_CFI_DEF_CFA_REGISTER:
1502 return parseDirectiveCFIDefCfaRegister(IDLoc);
1504 return parseDirectiveCFIOffset(IDLoc);
1505 case DK_CFI_REL_OFFSET:
1506 return parseDirectiveCFIRelOffset(IDLoc);
1507 case DK_CFI_PERSONALITY:
1508 return parseDirectiveCFIPersonalityOrLsda(true);
1510 return parseDirectiveCFIPersonalityOrLsda(false);
1511 case DK_CFI_REMEMBER_STATE:
1512 return parseDirectiveCFIRememberState();
1513 case DK_CFI_RESTORE_STATE:
1514 return parseDirectiveCFIRestoreState();
1515 case DK_CFI_SAME_VALUE:
1516 return parseDirectiveCFISameValue(IDLoc);
1517 case DK_CFI_RESTORE:
1518 return parseDirectiveCFIRestore(IDLoc);
1520 return parseDirectiveCFIEscape();
1521 case DK_CFI_SIGNAL_FRAME:
1522 return parseDirectiveCFISignalFrame();
1523 case DK_CFI_UNDEFINED:
1524 return parseDirectiveCFIUndefined(IDLoc);
1525 case DK_CFI_REGISTER:
1526 return parseDirectiveCFIRegister(IDLoc);
1527 case DK_CFI_WINDOW_SAVE:
1528 return parseDirectiveCFIWindowSave();
1531 return parseDirectiveMacrosOnOff(IDVal);
1533 return parseDirectiveMacro(IDLoc);
1536 return parseDirectiveEndMacro(IDVal);
1538 return parseDirectivePurgeMacro(IDLoc);
1540 return parseDirectiveEnd(IDLoc);
1542 return parseDirectiveError(IDLoc, false);
1544 return parseDirectiveError(IDLoc, true);
1547 return Error(IDLoc, "unknown directive");
1550 // __asm _emit or __asm __emit
1551 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1552 IDVal == "_EMIT" || IDVal == "__EMIT"))
1553 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1556 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1557 return parseDirectiveMSAlign(IDLoc, Info);
1559 checkForValidSection();
1561 // Canonicalize the opcode to lower case.
1562 std::string OpcodeStr = IDVal.lower();
1563 ParseInstructionInfo IInfo(Info.AsmRewrites);
1564 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1565 Info.ParsedOperands);
1566 Info.ParseError = HadError;
1568 // Dump the parsed representation, if requested.
1569 if (getShowParsedOperands()) {
1570 SmallString<256> Str;
1571 raw_svector_ostream OS(Str);
1572 OS << "parsed instruction: [";
1573 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1576 Info.ParsedOperands[i]->print(OS);
1580 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1583 // If we are generating dwarf for assembly source files and the current
1584 // section is the initial text section then generate a .loc directive for
1586 if (!HadError && getContext().getGenDwarfForAssembly() &&
1587 getContext().getGenDwarfSection() ==
1588 getStreamer().getCurrentSection().first) {
1590 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1592 // If we previously parsed a cpp hash file line comment then make sure the
1593 // current Dwarf File is for the CppHashFilename if not then emit the
1594 // Dwarf File table for it and adjust the line number for the .loc.
1595 if (CppHashFilename.size() != 0) {
1596 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1597 0, StringRef(), CppHashFilename);
1598 getContext().setGenDwarfFileNumber(FileNumber);
1600 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1601 // cache with the different Loc from the call above we save the last
1602 // info we queried here with SrcMgr.FindLineNumber().
1603 unsigned CppHashLocLineNo;
1604 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1605 CppHashLocLineNo = LastQueryLine;
1607 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1608 LastQueryLine = CppHashLocLineNo;
1609 LastQueryIDLoc = CppHashLoc;
1610 LastQueryBuffer = CppHashBuf;
1612 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1615 getStreamer().EmitDwarfLocDirective(
1616 getContext().getGenDwarfFileNumber(), Line, 0,
1617 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1621 // If parsing succeeded, match the instruction.
1624 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1625 Info.ParsedOperands, Out,
1626 ErrorInfo, ParsingInlineAsm);
1629 // Don't skip the rest of the line, the instruction parser is responsible for
1634 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1635 /// since they may not be able to be tokenized to get to the end of line token.
1636 void AsmParser::eatToEndOfLine() {
1637 if (!Lexer.is(AsmToken::EndOfStatement))
1638 Lexer.LexUntilEndOfLine();
1643 /// parseCppHashLineFilenameComment as this:
1644 /// ::= # number "filename"
1645 /// or just as a full line comment if it doesn't have a number and a string.
1646 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1647 Lex(); // Eat the hash token.
1649 if (getLexer().isNot(AsmToken::Integer)) {
1650 // Consume the line since in cases it is not a well-formed line directive,
1651 // as if were simply a full line comment.
1656 int64_t LineNumber = getTok().getIntVal();
1659 if (getLexer().isNot(AsmToken::String)) {
1664 StringRef Filename = getTok().getString();
1665 // Get rid of the enclosing quotes.
1666 Filename = Filename.substr(1, Filename.size() - 2);
1668 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1670 CppHashFilename = Filename;
1671 CppHashLineNumber = LineNumber;
1672 CppHashBuf = CurBuffer;
1674 // Ignore any trailing characters, they're just comment.
1679 /// \brief will use the last parsed cpp hash line filename comment
1680 /// for the Filename and LineNo if any in the diagnostic.
1681 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1682 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1683 raw_ostream &OS = errs();
1685 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1686 const SMLoc &DiagLoc = Diag.getLoc();
1687 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1688 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1690 // Like SourceMgr::printMessage() we need to print the include stack if any
1691 // before printing the message.
1692 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1693 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1694 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1695 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1698 // If we have not parsed a cpp hash line filename comment or the source
1699 // manager changed or buffer changed (like in a nested include) then just
1700 // print the normal diagnostic using its Filename and LineNo.
1701 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1702 DiagBuf != CppHashBuf) {
1703 if (Parser->SavedDiagHandler)
1704 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1706 Diag.print(nullptr, OS);
1710 // Use the CppHashFilename and calculate a line number based on the
1711 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1713 const std::string &Filename = Parser->CppHashFilename;
1715 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1716 int CppHashLocLineNo =
1717 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1719 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1721 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1722 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1723 Diag.getLineContents(), Diag.getRanges());
1725 if (Parser->SavedDiagHandler)
1726 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1728 NewDiag.print(nullptr, OS);
1731 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1732 // difference being that that function accepts '@' as part of identifiers and
1733 // we can't do that. AsmLexer.cpp should probably be changed to handle
1734 // '@' as a special case when needed.
1735 static bool isIdentifierChar(char c) {
1736 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1740 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1741 ArrayRef<MCAsmMacroParameter> Parameters,
1742 ArrayRef<MCAsmMacroArgument> A, const SMLoc &L) {
1743 unsigned NParameters = Parameters.size();
1744 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1745 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1746 return Error(L, "Wrong number of arguments");
1748 // A macro without parameters is handled differently on Darwin:
1749 // gas accepts no arguments and does no substitutions
1750 while (!Body.empty()) {
1751 // Scan for the next substitution.
1752 std::size_t End = Body.size(), Pos = 0;
1753 for (; Pos != End; ++Pos) {
1754 // Check for a substitution or escape.
1755 if (IsDarwin && !NParameters) {
1756 // This macro has no parameters, look for $0, $1, etc.
1757 if (Body[Pos] != '$' || Pos + 1 == End)
1760 char Next = Body[Pos + 1];
1761 if (Next == '$' || Next == 'n' ||
1762 isdigit(static_cast<unsigned char>(Next)))
1765 // This macro has parameters, look for \foo, \bar, etc.
1766 if (Body[Pos] == '\\' && Pos + 1 != End)
1772 OS << Body.slice(0, Pos);
1774 // Check if we reached the end.
1778 if (IsDarwin && !NParameters) {
1779 switch (Body[Pos + 1]) {
1785 // $n => number of arguments
1790 // $[0-9] => argument
1792 // Missing arguments are ignored.
1793 unsigned Index = Body[Pos + 1] - '0';
1794 if (Index >= A.size())
1797 // Otherwise substitute with the token values, with spaces eliminated.
1798 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1799 ie = A[Index].end();
1801 OS << it->getString();
1807 unsigned I = Pos + 1;
1808 while (isIdentifierChar(Body[I]) && I + 1 != End)
1811 const char *Begin = Body.data() + Pos + 1;
1812 StringRef Argument(Begin, I - (Pos + 1));
1814 for (; Index < NParameters; ++Index)
1815 if (Parameters[Index].Name == Argument)
1818 if (Index == NParameters) {
1819 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1822 OS << '\\' << Argument;
1826 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1827 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1828 ie = A[Index].end();
1830 // We expect no quotes around the string's contents when
1831 // parsing for varargs.
1832 if (it->getKind() != AsmToken::String || VarargParameter)
1833 OS << it->getString();
1835 OS << it->getStringContents();
1837 Pos += 1 + Argument.size();
1840 // Update the scan point.
1841 Body = Body.substr(Pos);
1847 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1848 SMLoc EL, MemoryBuffer *I)
1849 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1852 static bool isOperator(AsmToken::TokenKind kind) {
1856 case AsmToken::Plus:
1857 case AsmToken::Minus:
1858 case AsmToken::Tilde:
1859 case AsmToken::Slash:
1860 case AsmToken::Star:
1862 case AsmToken::Equal:
1863 case AsmToken::EqualEqual:
1864 case AsmToken::Pipe:
1865 case AsmToken::PipePipe:
1866 case AsmToken::Caret:
1868 case AsmToken::AmpAmp:
1869 case AsmToken::Exclaim:
1870 case AsmToken::ExclaimEqual:
1871 case AsmToken::Percent:
1872 case AsmToken::Less:
1873 case AsmToken::LessEqual:
1874 case AsmToken::LessLess:
1875 case AsmToken::LessGreater:
1876 case AsmToken::Greater:
1877 case AsmToken::GreaterEqual:
1878 case AsmToken::GreaterGreater:
1884 class AsmLexerSkipSpaceRAII {
1886 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1887 Lexer.setSkipSpace(SkipSpace);
1890 ~AsmLexerSkipSpaceRAII() {
1891 Lexer.setSkipSpace(true);
1899 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1902 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1903 StringRef Str = parseStringToEndOfStatement();
1904 MA.push_back(AsmToken(AsmToken::String, Str));
1909 unsigned ParenLevel = 0;
1910 unsigned AddTokens = 0;
1912 // Darwin doesn't use spaces to delmit arguments.
1913 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1916 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1917 return TokError("unexpected token in macro instantiation");
1919 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1922 if (Lexer.is(AsmToken::Space)) {
1923 Lex(); // Eat spaces
1925 // Spaces can delimit parameters, but could also be part an expression.
1926 // If the token after a space is an operator, add the token and the next
1927 // one into this argument
1929 if (isOperator(Lexer.getKind())) {
1930 // Check to see whether the token is used as an operator,
1931 // or part of an identifier
1932 const char *NextChar = getTok().getEndLoc().getPointer();
1933 if (*NextChar == ' ')
1937 if (!AddTokens && ParenLevel == 0) {
1943 // handleMacroEntry relies on not advancing the lexer here
1944 // to be able to fill in the remaining default parameter values
1945 if (Lexer.is(AsmToken::EndOfStatement))
1948 // Adjust the current parentheses level.
1949 if (Lexer.is(AsmToken::LParen))
1951 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1954 // Append the token to the current argument list.
1955 MA.push_back(getTok());
1961 if (ParenLevel != 0)
1962 return TokError("unbalanced parentheses in macro argument");
1966 // Parse the macro instantiation arguments.
1967 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1968 MCAsmMacroArguments &A) {
1969 const unsigned NParameters = M ? M->Parameters.size() : 0;
1970 bool NamedParametersFound = false;
1971 SmallVector<SMLoc, 4> FALocs;
1973 A.resize(NParameters);
1974 FALocs.resize(NParameters);
1976 // Parse two kinds of macro invocations:
1977 // - macros defined without any parameters accept an arbitrary number of them
1978 // - macros defined with parameters accept at most that many of them
1979 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
1980 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1982 SMLoc IDLoc = Lexer.getLoc();
1983 MCAsmMacroParameter FA;
1985 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
1986 if (parseIdentifier(FA.Name)) {
1987 Error(IDLoc, "invalid argument identifier for formal argument");
1988 eatToEndOfStatement();
1992 if (!Lexer.is(AsmToken::Equal)) {
1993 TokError("expected '=' after formal parameter identifier");
1994 eatToEndOfStatement();
1999 NamedParametersFound = true;
2002 if (NamedParametersFound && FA.Name.empty()) {
2003 Error(IDLoc, "cannot mix positional and keyword arguments");
2004 eatToEndOfStatement();
2008 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2009 if (parseMacroArgument(FA.Value, Vararg))
2012 unsigned PI = Parameter;
2013 if (!FA.Name.empty()) {
2015 for (FAI = 0; FAI < NParameters; ++FAI)
2016 if (M->Parameters[FAI].Name == FA.Name)
2019 if (FAI >= NParameters) {
2020 assert(M && "expected macro to be defined");
2022 "parameter named '" + FA.Name + "' does not exist for macro '" +
2029 if (!FA.Value.empty()) {
2034 if (FALocs.size() <= PI)
2035 FALocs.resize(PI + 1);
2037 FALocs[PI] = Lexer.getLoc();
2040 // At the end of the statement, fill in remaining arguments that have
2041 // default values. If there aren't any, then the next argument is
2042 // required but missing
2043 if (Lexer.is(AsmToken::EndOfStatement)) {
2044 bool Failure = false;
2045 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2046 if (A[FAI].empty()) {
2047 if (M->Parameters[FAI].Required) {
2048 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2049 "missing value for required parameter "
2050 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2054 if (!M->Parameters[FAI].Value.empty())
2055 A[FAI] = M->Parameters[FAI].Value;
2061 if (Lexer.is(AsmToken::Comma))
2065 return TokError("too many positional arguments");
2068 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2069 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2070 return (I == MacroMap.end()) ? nullptr : I->getValue();
2073 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
2074 MacroMap[Name] = new MCAsmMacro(Macro);
2077 void AsmParser::undefineMacro(StringRef Name) {
2078 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2079 if (I != MacroMap.end()) {
2080 delete I->getValue();
2085 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2086 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2087 // this, although we should protect against infinite loops.
2088 if (ActiveMacros.size() == 20)
2089 return TokError("macros cannot be nested more than 20 levels deep");
2091 MCAsmMacroArguments A;
2092 if (parseMacroArguments(M, A))
2095 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2096 // to hold the macro body with substitutions.
2097 SmallString<256> Buf;
2098 StringRef Body = M->Body;
2099 raw_svector_ostream OS(Buf);
2101 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2104 // We include the .endmacro in the buffer as our cue to exit the macro
2106 OS << ".endmacro\n";
2108 MemoryBuffer *Instantiation =
2109 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2111 // Create the macro instantiation object and add to the current macro
2112 // instantiation stack.
2113 MacroInstantiation *MI = new MacroInstantiation(
2114 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
2115 ActiveMacros.push_back(MI);
2117 // Jump to the macro instantiation and prime the lexer.
2118 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2119 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2125 void AsmParser::handleMacroExit() {
2126 // Jump to the EndOfStatement we should return to, and consume it.
2127 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2130 // Pop the instantiation entry.
2131 delete ActiveMacros.back();
2132 ActiveMacros.pop_back();
2135 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2136 switch (Value->getKind()) {
2137 case MCExpr::Binary: {
2138 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2139 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2141 case MCExpr::Target:
2142 case MCExpr::Constant:
2144 case MCExpr::SymbolRef: {
2146 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2148 return isUsedIn(Sym, S.getVariableValue());
2152 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2155 llvm_unreachable("Unknown expr kind!");
2158 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2160 // FIXME: Use better location, we should use proper tokens.
2161 SMLoc EqualLoc = Lexer.getLoc();
2163 const MCExpr *Value;
2164 if (parseExpression(Value))
2167 // Note: we don't count b as used in "a = b". This is to allow
2171 if (Lexer.isNot(AsmToken::EndOfStatement))
2172 return TokError("unexpected token in assignment");
2174 // Eat the end of statement marker.
2177 // Validate that the LHS is allowed to be a variable (either it has not been
2178 // used as a symbol, or it is an absolute symbol).
2179 MCSymbol *Sym = getContext().LookupSymbol(Name);
2181 // Diagnose assignment to a label.
2183 // FIXME: Diagnostics. Note the location of the definition as a label.
2184 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2185 if (isUsedIn(Sym, Value))
2186 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2187 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2188 ; // Allow redefinitions of undefined symbols only used in directives.
2189 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2190 ; // Allow redefinitions of variables that haven't yet been used.
2191 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2192 return Error(EqualLoc, "redefinition of '" + Name + "'");
2193 else if (!Sym->isVariable())
2194 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2195 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2196 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2199 // Don't count these checks as uses.
2200 Sym->setUsed(false);
2201 } else if (Name == ".") {
2202 if (Out.EmitValueToOffset(Value, 0)) {
2203 Error(EqualLoc, "expected absolute expression");
2204 eatToEndOfStatement();
2208 Sym = getContext().GetOrCreateSymbol(Name);
2210 // Do the assignment.
2211 Out.EmitAssignment(Sym, Value);
2213 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2218 /// parseIdentifier:
2221 bool AsmParser::parseIdentifier(StringRef &Res) {
2222 // The assembler has relaxed rules for accepting identifiers, in particular we
2223 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2224 // separate tokens. At this level, we have already lexed so we cannot (currently)
2225 // handle this as a context dependent token, instead we detect adjacent tokens
2226 // and return the combined identifier.
2227 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2228 SMLoc PrefixLoc = getLexer().getLoc();
2230 // Consume the prefix character, and check for a following identifier.
2232 if (Lexer.isNot(AsmToken::Identifier))
2235 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2236 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2239 // Construct the joined identifier and consume the token.
2241 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2246 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2249 Res = getTok().getIdentifier();
2251 Lex(); // Consume the identifier token.
2256 /// parseDirectiveSet:
2257 /// ::= .equ identifier ',' expression
2258 /// ::= .equiv identifier ',' expression
2259 /// ::= .set identifier ',' expression
2260 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2263 if (parseIdentifier(Name))
2264 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2266 if (getLexer().isNot(AsmToken::Comma))
2267 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2270 return parseAssignment(Name, allow_redef, true);
2273 bool AsmParser::parseEscapedString(std::string &Data) {
2274 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2277 StringRef Str = getTok().getStringContents();
2278 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2279 if (Str[i] != '\\') {
2284 // Recognize escaped characters. Note that this escape semantics currently
2285 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2288 return TokError("unexpected backslash at end of string");
2290 // Recognize octal sequences.
2291 if ((unsigned)(Str[i] - '0') <= 7) {
2292 // Consume up to three octal characters.
2293 unsigned Value = Str[i] - '0';
2295 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2297 Value = Value * 8 + (Str[i] - '0');
2299 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2301 Value = Value * 8 + (Str[i] - '0');
2306 return TokError("invalid octal escape sequence (out of range)");
2308 Data += (unsigned char)Value;
2312 // Otherwise recognize individual escapes.
2315 // Just reject invalid escape sequences for now.
2316 return TokError("invalid escape sequence (unrecognized character)");
2318 case 'b': Data += '\b'; break;
2319 case 'f': Data += '\f'; break;
2320 case 'n': Data += '\n'; break;
2321 case 'r': Data += '\r'; break;
2322 case 't': Data += '\t'; break;
2323 case '"': Data += '"'; break;
2324 case '\\': Data += '\\'; break;
2331 /// parseDirectiveAscii:
2332 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2333 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2334 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2335 checkForValidSection();
2338 if (getLexer().isNot(AsmToken::String))
2339 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2342 if (parseEscapedString(Data))
2345 getStreamer().EmitBytes(Data);
2347 getStreamer().EmitBytes(StringRef("\0", 1));
2351 if (getLexer().is(AsmToken::EndOfStatement))
2354 if (getLexer().isNot(AsmToken::Comma))
2355 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2364 /// parseDirectiveValue
2365 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2366 bool AsmParser::parseDirectiveValue(unsigned Size) {
2367 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2368 checkForValidSection();
2371 const MCExpr *Value;
2372 SMLoc ExprLoc = getLexer().getLoc();
2373 if (parseExpression(Value))
2376 // Special case constant expressions to match code generator.
2377 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2378 assert(Size <= 8 && "Invalid size");
2379 uint64_t IntValue = MCE->getValue();
2380 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2381 return Error(ExprLoc, "literal value out of range for directive");
2382 getStreamer().EmitIntValue(IntValue, Size);
2384 getStreamer().EmitValue(Value, Size, ExprLoc);
2386 if (getLexer().is(AsmToken::EndOfStatement))
2389 // FIXME: Improve diagnostic.
2390 if (getLexer().isNot(AsmToken::Comma))
2391 return TokError("unexpected token in directive");
2400 /// ParseDirectiveOctaValue
2401 /// ::= .octa [ hexconstant (, hexconstant)* ]
2402 bool AsmParser::parseDirectiveOctaValue() {
2403 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2404 checkForValidSection();
2407 if (Lexer.getKind() == AsmToken::Error)
2409 if (Lexer.getKind() != AsmToken::Integer &&
2410 Lexer.getKind() != AsmToken::BigNum)
2411 return TokError("unknown token in expression");
2413 SMLoc ExprLoc = getLexer().getLoc();
2414 APInt IntValue = getTok().getAPIntVal();
2418 if (IntValue.isIntN(64)) {
2420 lo = IntValue.getZExtValue();
2421 } else if (IntValue.isIntN(128)) {
2422 // It might actually have more than 128 bits, but the top ones are zero.
2423 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2424 lo = IntValue.getLoBits(64).getZExtValue();
2426 return Error(ExprLoc, "literal value out of range for directive");
2428 if (MAI.isLittleEndian()) {
2429 getStreamer().EmitIntValue(lo, 8);
2430 getStreamer().EmitIntValue(hi, 8);
2432 getStreamer().EmitIntValue(hi, 8);
2433 getStreamer().EmitIntValue(lo, 8);
2436 if (getLexer().is(AsmToken::EndOfStatement))
2439 // FIXME: Improve diagnostic.
2440 if (getLexer().isNot(AsmToken::Comma))
2441 return TokError("unexpected token in directive");
2450 /// parseDirectiveRealValue
2451 /// ::= (.single | .double) [ expression (, expression)* ]
2452 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2453 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2454 checkForValidSection();
2457 // We don't truly support arithmetic on floating point expressions, so we
2458 // have to manually parse unary prefixes.
2460 if (getLexer().is(AsmToken::Minus)) {
2463 } else if (getLexer().is(AsmToken::Plus))
2466 if (getLexer().isNot(AsmToken::Integer) &&
2467 getLexer().isNot(AsmToken::Real) &&
2468 getLexer().isNot(AsmToken::Identifier))
2469 return TokError("unexpected token in directive");
2471 // Convert to an APFloat.
2472 APFloat Value(Semantics);
2473 StringRef IDVal = getTok().getString();
2474 if (getLexer().is(AsmToken::Identifier)) {
2475 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2476 Value = APFloat::getInf(Semantics);
2477 else if (!IDVal.compare_lower("nan"))
2478 Value = APFloat::getNaN(Semantics, false, ~0);
2480 return TokError("invalid floating point literal");
2481 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2482 APFloat::opInvalidOp)
2483 return TokError("invalid floating point literal");
2487 // Consume the numeric token.
2490 // Emit the value as an integer.
2491 APInt AsInt = Value.bitcastToAPInt();
2492 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2493 AsInt.getBitWidth() / 8);
2495 if (getLexer().is(AsmToken::EndOfStatement))
2498 if (getLexer().isNot(AsmToken::Comma))
2499 return TokError("unexpected token in directive");
2508 /// parseDirectiveZero
2509 /// ::= .zero expression
2510 bool AsmParser::parseDirectiveZero() {
2511 checkForValidSection();
2514 if (parseAbsoluteExpression(NumBytes))
2518 if (getLexer().is(AsmToken::Comma)) {
2520 if (parseAbsoluteExpression(Val))
2524 if (getLexer().isNot(AsmToken::EndOfStatement))
2525 return TokError("unexpected token in '.zero' directive");
2529 getStreamer().EmitFill(NumBytes, Val);
2534 /// parseDirectiveFill
2535 /// ::= .fill expression [ , expression [ , expression ] ]
2536 bool AsmParser::parseDirectiveFill() {
2537 checkForValidSection();
2539 SMLoc RepeatLoc = getLexer().getLoc();
2541 if (parseAbsoluteExpression(NumValues))
2544 if (NumValues < 0) {
2546 "'.fill' directive with negative repeat count has no effect");
2550 int64_t FillSize = 1;
2551 int64_t FillExpr = 0;
2553 SMLoc SizeLoc, ExprLoc;
2554 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2555 if (getLexer().isNot(AsmToken::Comma))
2556 return TokError("unexpected token in '.fill' directive");
2559 SizeLoc = getLexer().getLoc();
2560 if (parseAbsoluteExpression(FillSize))
2563 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2564 if (getLexer().isNot(AsmToken::Comma))
2565 return TokError("unexpected token in '.fill' directive");
2568 ExprLoc = getLexer().getLoc();
2569 if (parseAbsoluteExpression(FillExpr))
2572 if (getLexer().isNot(AsmToken::EndOfStatement))
2573 return TokError("unexpected token in '.fill' directive");
2580 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2584 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2588 if (!isUInt<32>(FillExpr) && FillSize > 4)
2589 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2591 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2592 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2594 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2595 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2596 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2602 /// parseDirectiveOrg
2603 /// ::= .org expression [ , expression ]
2604 bool AsmParser::parseDirectiveOrg() {
2605 checkForValidSection();
2607 const MCExpr *Offset;
2608 SMLoc Loc = getTok().getLoc();
2609 if (parseExpression(Offset))
2612 // Parse optional fill expression.
2613 int64_t FillExpr = 0;
2614 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2615 if (getLexer().isNot(AsmToken::Comma))
2616 return TokError("unexpected token in '.org' directive");
2619 if (parseAbsoluteExpression(FillExpr))
2622 if (getLexer().isNot(AsmToken::EndOfStatement))
2623 return TokError("unexpected token in '.org' directive");
2628 // Only limited forms of relocatable expressions are accepted here, it
2629 // has to be relative to the current section. The streamer will return
2630 // 'true' if the expression wasn't evaluatable.
2631 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2632 return Error(Loc, "expected assembly-time absolute expression");
2637 /// parseDirectiveAlign
2638 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2639 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2640 checkForValidSection();
2642 SMLoc AlignmentLoc = getLexer().getLoc();
2644 if (parseAbsoluteExpression(Alignment))
2648 bool HasFillExpr = false;
2649 int64_t FillExpr = 0;
2650 int64_t MaxBytesToFill = 0;
2651 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2652 if (getLexer().isNot(AsmToken::Comma))
2653 return TokError("unexpected token in directive");
2656 // The fill expression can be omitted while specifying a maximum number of
2657 // alignment bytes, e.g:
2659 if (getLexer().isNot(AsmToken::Comma)) {
2661 if (parseAbsoluteExpression(FillExpr))
2665 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2666 if (getLexer().isNot(AsmToken::Comma))
2667 return TokError("unexpected token in directive");
2670 MaxBytesLoc = getLexer().getLoc();
2671 if (parseAbsoluteExpression(MaxBytesToFill))
2674 if (getLexer().isNot(AsmToken::EndOfStatement))
2675 return TokError("unexpected token in directive");
2684 // Compute alignment in bytes.
2686 // FIXME: Diagnose overflow.
2687 if (Alignment >= 32) {
2688 Error(AlignmentLoc, "invalid alignment value");
2692 Alignment = 1ULL << Alignment;
2694 // Reject alignments that aren't a power of two, for gas compatibility.
2695 if (!isPowerOf2_64(Alignment))
2696 Error(AlignmentLoc, "alignment must be a power of 2");
2699 // Diagnose non-sensical max bytes to align.
2700 if (MaxBytesLoc.isValid()) {
2701 if (MaxBytesToFill < 1) {
2702 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2703 "many bytes, ignoring maximum bytes expression");
2707 if (MaxBytesToFill >= Alignment) {
2708 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2714 // Check whether we should use optimal code alignment for this .align
2716 const MCSection *Section = getStreamer().getCurrentSection().first;
2717 assert(Section && "must have section to emit alignment");
2718 bool UseCodeAlign = Section->UseCodeAlign();
2719 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2720 ValueSize == 1 && UseCodeAlign) {
2721 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2723 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2724 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2731 /// parseDirectiveFile
2732 /// ::= .file [number] filename
2733 /// ::= .file number directory filename
2734 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2735 // FIXME: I'm not sure what this is.
2736 int64_t FileNumber = -1;
2737 SMLoc FileNumberLoc = getLexer().getLoc();
2738 if (getLexer().is(AsmToken::Integer)) {
2739 FileNumber = getTok().getIntVal();
2743 return TokError("file number less than one");
2746 if (getLexer().isNot(AsmToken::String))
2747 return TokError("unexpected token in '.file' directive");
2749 // Usually the directory and filename together, otherwise just the directory.
2750 // Allow the strings to have escaped octal character sequence.
2751 std::string Path = getTok().getString();
2752 if (parseEscapedString(Path))
2756 StringRef Directory;
2758 std::string FilenameData;
2759 if (getLexer().is(AsmToken::String)) {
2760 if (FileNumber == -1)
2761 return TokError("explicit path specified, but no file number");
2762 if (parseEscapedString(FilenameData))
2764 Filename = FilenameData;
2771 if (getLexer().isNot(AsmToken::EndOfStatement))
2772 return TokError("unexpected token in '.file' directive");
2774 if (FileNumber == -1)
2775 getStreamer().EmitFileDirective(Filename);
2777 if (getContext().getGenDwarfForAssembly() == true)
2779 "input can't have .file dwarf directives when -g is "
2780 "used to generate dwarf debug info for assembly code");
2782 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2784 Error(FileNumberLoc, "file number already allocated");
2790 /// parseDirectiveLine
2791 /// ::= .line [number]
2792 bool AsmParser::parseDirectiveLine() {
2793 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2794 if (getLexer().isNot(AsmToken::Integer))
2795 return TokError("unexpected token in '.line' directive");
2797 int64_t LineNumber = getTok().getIntVal();
2801 // FIXME: Do something with the .line.
2804 if (getLexer().isNot(AsmToken::EndOfStatement))
2805 return TokError("unexpected token in '.line' directive");
2810 /// parseDirectiveLoc
2811 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2812 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2813 /// The first number is a file number, must have been previously assigned with
2814 /// a .file directive, the second number is the line number and optionally the
2815 /// third number is a column position (zero if not specified). The remaining
2816 /// optional items are .loc sub-directives.
2817 bool AsmParser::parseDirectiveLoc() {
2818 if (getLexer().isNot(AsmToken::Integer))
2819 return TokError("unexpected token in '.loc' directive");
2820 int64_t FileNumber = getTok().getIntVal();
2822 return TokError("file number less than one in '.loc' directive");
2823 if (!getContext().isValidDwarfFileNumber(FileNumber))
2824 return TokError("unassigned file number in '.loc' directive");
2827 int64_t LineNumber = 0;
2828 if (getLexer().is(AsmToken::Integer)) {
2829 LineNumber = getTok().getIntVal();
2831 return TokError("line number less than zero in '.loc' directive");
2835 int64_t ColumnPos = 0;
2836 if (getLexer().is(AsmToken::Integer)) {
2837 ColumnPos = getTok().getIntVal();
2839 return TokError("column position less than zero in '.loc' directive");
2843 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2845 int64_t Discriminator = 0;
2846 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2848 if (getLexer().is(AsmToken::EndOfStatement))
2852 SMLoc Loc = getTok().getLoc();
2853 if (parseIdentifier(Name))
2854 return TokError("unexpected token in '.loc' directive");
2856 if (Name == "basic_block")
2857 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2858 else if (Name == "prologue_end")
2859 Flags |= DWARF2_FLAG_PROLOGUE_END;
2860 else if (Name == "epilogue_begin")
2861 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2862 else if (Name == "is_stmt") {
2863 Loc = getTok().getLoc();
2864 const MCExpr *Value;
2865 if (parseExpression(Value))
2867 // The expression must be the constant 0 or 1.
2868 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2869 int Value = MCE->getValue();
2871 Flags &= ~DWARF2_FLAG_IS_STMT;
2872 else if (Value == 1)
2873 Flags |= DWARF2_FLAG_IS_STMT;
2875 return Error(Loc, "is_stmt value not 0 or 1");
2877 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2879 } else if (Name == "isa") {
2880 Loc = getTok().getLoc();
2881 const MCExpr *Value;
2882 if (parseExpression(Value))
2884 // The expression must be a constant greater or equal to 0.
2885 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2886 int Value = MCE->getValue();
2888 return Error(Loc, "isa number less than zero");
2891 return Error(Loc, "isa number not a constant value");
2893 } else if (Name == "discriminator") {
2894 if (parseAbsoluteExpression(Discriminator))
2897 return Error(Loc, "unknown sub-directive in '.loc' directive");
2900 if (getLexer().is(AsmToken::EndOfStatement))
2905 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2906 Isa, Discriminator, StringRef());
2911 /// parseDirectiveStabs
2912 /// ::= .stabs string, number, number, number
2913 bool AsmParser::parseDirectiveStabs() {
2914 return TokError("unsupported directive '.stabs'");
2917 /// parseDirectiveCFISections
2918 /// ::= .cfi_sections section [, section]
2919 bool AsmParser::parseDirectiveCFISections() {
2924 if (parseIdentifier(Name))
2925 return TokError("Expected an identifier");
2927 if (Name == ".eh_frame")
2929 else if (Name == ".debug_frame")
2932 if (getLexer().is(AsmToken::Comma)) {
2935 if (parseIdentifier(Name))
2936 return TokError("Expected an identifier");
2938 if (Name == ".eh_frame")
2940 else if (Name == ".debug_frame")
2944 getStreamer().EmitCFISections(EH, Debug);
2948 /// parseDirectiveCFIStartProc
2949 /// ::= .cfi_startproc [simple]
2950 bool AsmParser::parseDirectiveCFIStartProc() {
2952 if (getLexer().isNot(AsmToken::EndOfStatement))
2953 if (parseIdentifier(Simple) || Simple != "simple")
2954 return TokError("unexpected token in .cfi_startproc directive");
2956 getStreamer().EmitCFIStartProc(!Simple.empty());
2960 /// parseDirectiveCFIEndProc
2961 /// ::= .cfi_endproc
2962 bool AsmParser::parseDirectiveCFIEndProc() {
2963 getStreamer().EmitCFIEndProc();
2967 /// \brief parse register name or number.
2968 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2969 SMLoc DirectiveLoc) {
2972 if (getLexer().isNot(AsmToken::Integer)) {
2973 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2975 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2977 return parseAbsoluteExpression(Register);
2982 /// parseDirectiveCFIDefCfa
2983 /// ::= .cfi_def_cfa register, offset
2984 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2985 int64_t Register = 0;
2986 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2989 if (getLexer().isNot(AsmToken::Comma))
2990 return TokError("unexpected token in directive");
2994 if (parseAbsoluteExpression(Offset))
2997 getStreamer().EmitCFIDefCfa(Register, Offset);
3001 /// parseDirectiveCFIDefCfaOffset
3002 /// ::= .cfi_def_cfa_offset offset
3003 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3005 if (parseAbsoluteExpression(Offset))
3008 getStreamer().EmitCFIDefCfaOffset(Offset);
3012 /// parseDirectiveCFIRegister
3013 /// ::= .cfi_register register, register
3014 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3015 int64_t Register1 = 0;
3016 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3019 if (getLexer().isNot(AsmToken::Comma))
3020 return TokError("unexpected token in directive");
3023 int64_t Register2 = 0;
3024 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3027 getStreamer().EmitCFIRegister(Register1, Register2);
3031 /// parseDirectiveCFIWindowSave
3032 /// ::= .cfi_window_save
3033 bool AsmParser::parseDirectiveCFIWindowSave() {
3034 getStreamer().EmitCFIWindowSave();
3038 /// parseDirectiveCFIAdjustCfaOffset
3039 /// ::= .cfi_adjust_cfa_offset adjustment
3040 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3041 int64_t Adjustment = 0;
3042 if (parseAbsoluteExpression(Adjustment))
3045 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3049 /// parseDirectiveCFIDefCfaRegister
3050 /// ::= .cfi_def_cfa_register register
3051 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3052 int64_t Register = 0;
3053 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3056 getStreamer().EmitCFIDefCfaRegister(Register);
3060 /// parseDirectiveCFIOffset
3061 /// ::= .cfi_offset register, offset
3062 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3063 int64_t Register = 0;
3066 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3069 if (getLexer().isNot(AsmToken::Comma))
3070 return TokError("unexpected token in directive");
3073 if (parseAbsoluteExpression(Offset))
3076 getStreamer().EmitCFIOffset(Register, Offset);
3080 /// parseDirectiveCFIRelOffset
3081 /// ::= .cfi_rel_offset register, offset
3082 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3083 int64_t Register = 0;
3085 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3088 if (getLexer().isNot(AsmToken::Comma))
3089 return TokError("unexpected token in directive");
3093 if (parseAbsoluteExpression(Offset))
3096 getStreamer().EmitCFIRelOffset(Register, Offset);
3100 static bool isValidEncoding(int64_t Encoding) {
3101 if (Encoding & ~0xff)
3104 if (Encoding == dwarf::DW_EH_PE_omit)
3107 const unsigned Format = Encoding & 0xf;
3108 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3109 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3110 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3111 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3114 const unsigned Application = Encoding & 0x70;
3115 if (Application != dwarf::DW_EH_PE_absptr &&
3116 Application != dwarf::DW_EH_PE_pcrel)
3122 /// parseDirectiveCFIPersonalityOrLsda
3123 /// IsPersonality true for cfi_personality, false for cfi_lsda
3124 /// ::= .cfi_personality encoding, [symbol_name]
3125 /// ::= .cfi_lsda encoding, [symbol_name]
3126 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3127 int64_t Encoding = 0;
3128 if (parseAbsoluteExpression(Encoding))
3130 if (Encoding == dwarf::DW_EH_PE_omit)
3133 if (!isValidEncoding(Encoding))
3134 return TokError("unsupported encoding.");
3136 if (getLexer().isNot(AsmToken::Comma))
3137 return TokError("unexpected token in directive");
3141 if (parseIdentifier(Name))
3142 return TokError("expected identifier in directive");
3144 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3147 getStreamer().EmitCFIPersonality(Sym, Encoding);
3149 getStreamer().EmitCFILsda(Sym, Encoding);
3153 /// parseDirectiveCFIRememberState
3154 /// ::= .cfi_remember_state
3155 bool AsmParser::parseDirectiveCFIRememberState() {
3156 getStreamer().EmitCFIRememberState();
3160 /// parseDirectiveCFIRestoreState
3161 /// ::= .cfi_remember_state
3162 bool AsmParser::parseDirectiveCFIRestoreState() {
3163 getStreamer().EmitCFIRestoreState();
3167 /// parseDirectiveCFISameValue
3168 /// ::= .cfi_same_value register
3169 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3170 int64_t Register = 0;
3172 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3175 getStreamer().EmitCFISameValue(Register);
3179 /// parseDirectiveCFIRestore
3180 /// ::= .cfi_restore register
3181 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3182 int64_t Register = 0;
3183 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3186 getStreamer().EmitCFIRestore(Register);
3190 /// parseDirectiveCFIEscape
3191 /// ::= .cfi_escape expression[,...]
3192 bool AsmParser::parseDirectiveCFIEscape() {
3195 if (parseAbsoluteExpression(CurrValue))
3198 Values.push_back((uint8_t)CurrValue);
3200 while (getLexer().is(AsmToken::Comma)) {
3203 if (parseAbsoluteExpression(CurrValue))
3206 Values.push_back((uint8_t)CurrValue);
3209 getStreamer().EmitCFIEscape(Values);
3213 /// parseDirectiveCFISignalFrame
3214 /// ::= .cfi_signal_frame
3215 bool AsmParser::parseDirectiveCFISignalFrame() {
3216 if (getLexer().isNot(AsmToken::EndOfStatement))
3217 return Error(getLexer().getLoc(),
3218 "unexpected token in '.cfi_signal_frame'");
3220 getStreamer().EmitCFISignalFrame();
3224 /// parseDirectiveCFIUndefined
3225 /// ::= .cfi_undefined register
3226 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3227 int64_t Register = 0;
3229 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3232 getStreamer().EmitCFIUndefined(Register);
3236 /// parseDirectiveMacrosOnOff
3239 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3240 if (getLexer().isNot(AsmToken::EndOfStatement))
3241 return Error(getLexer().getLoc(),
3242 "unexpected token in '" + Directive + "' directive");
3244 setMacrosEnabled(Directive == ".macros_on");
3248 /// parseDirectiveMacro
3249 /// ::= .macro name[,] [parameters]
3250 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3252 if (parseIdentifier(Name))
3253 return TokError("expected identifier in '.macro' directive");
3255 if (getLexer().is(AsmToken::Comma))
3258 MCAsmMacroParameters Parameters;
3259 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3261 if (Parameters.size() && Parameters.back().Vararg)
3262 return Error(Lexer.getLoc(),
3263 "Vararg parameter '" + Parameters.back().Name +
3264 "' should be last one in the list of parameters.");
3266 MCAsmMacroParameter Parameter;
3267 if (parseIdentifier(Parameter.Name))
3268 return TokError("expected identifier in '.macro' directive");
3270 if (Lexer.is(AsmToken::Colon)) {
3271 Lex(); // consume ':'
3274 StringRef Qualifier;
3276 QualLoc = Lexer.getLoc();
3277 if (parseIdentifier(Qualifier))
3278 return Error(QualLoc, "missing parameter qualifier for "
3279 "'" + Parameter.Name + "' in macro '" + Name + "'");
3281 if (Qualifier == "req")
3282 Parameter.Required = true;
3283 else if (Qualifier == "vararg" && !IsDarwin)
3284 Parameter.Vararg = true;
3286 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3287 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3290 if (getLexer().is(AsmToken::Equal)) {
3295 ParamLoc = Lexer.getLoc();
3296 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3299 if (Parameter.Required)
3300 Warning(ParamLoc, "pointless default value for required parameter "
3301 "'" + Parameter.Name + "' in macro '" + Name + "'");
3304 Parameters.push_back(Parameter);
3306 if (getLexer().is(AsmToken::Comma))
3310 // Eat the end of statement.
3313 AsmToken EndToken, StartToken = getTok();
3314 unsigned MacroDepth = 0;
3316 // Lex the macro definition.
3318 // Check whether we have reached the end of the file.
3319 if (getLexer().is(AsmToken::Eof))
3320 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3322 // Otherwise, check whether we have reach the .endmacro.
3323 if (getLexer().is(AsmToken::Identifier)) {
3324 if (getTok().getIdentifier() == ".endm" ||
3325 getTok().getIdentifier() == ".endmacro") {
3326 if (MacroDepth == 0) { // Outermost macro.
3327 EndToken = getTok();
3329 if (getLexer().isNot(AsmToken::EndOfStatement))
3330 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3334 // Otherwise we just found the end of an inner macro.
3337 } else if (getTok().getIdentifier() == ".macro") {
3338 // We allow nested macros. Those aren't instantiated until the outermost
3339 // macro is expanded so just ignore them for now.
3344 // Otherwise, scan til the end of the statement.
3345 eatToEndOfStatement();
3348 if (lookupMacro(Name)) {
3349 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3352 const char *BodyStart = StartToken.getLoc().getPointer();
3353 const char *BodyEnd = EndToken.getLoc().getPointer();
3354 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3355 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3356 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3360 /// checkForBadMacro
3362 /// With the support added for named parameters there may be code out there that
3363 /// is transitioning from positional parameters. In versions of gas that did
3364 /// not support named parameters they would be ignored on the macro definition.
3365 /// But to support both styles of parameters this is not possible so if a macro
3366 /// definition has named parameters but does not use them and has what appears
3367 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3368 /// warning that the positional parameter found in body which have no effect.
3369 /// Hoping the developer will either remove the named parameters from the macro
3370 /// definition so the positional parameters get used if that was what was
3371 /// intended or change the macro to use the named parameters. It is possible
3372 /// this warning will trigger when the none of the named parameters are used
3373 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3374 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3376 ArrayRef<MCAsmMacroParameter> Parameters) {
3377 // If this macro is not defined with named parameters the warning we are
3378 // checking for here doesn't apply.
3379 unsigned NParameters = Parameters.size();
3380 if (NParameters == 0)
3383 bool NamedParametersFound = false;
3384 bool PositionalParametersFound = false;
3386 // Look at the body of the macro for use of both the named parameters and what
3387 // are likely to be positional parameters. This is what expandMacro() is
3388 // doing when it finds the parameters in the body.
3389 while (!Body.empty()) {
3390 // Scan for the next possible parameter.
3391 std::size_t End = Body.size(), Pos = 0;
3392 for (; Pos != End; ++Pos) {
3393 // Check for a substitution or escape.
3394 // This macro is defined with parameters, look for \foo, \bar, etc.
3395 if (Body[Pos] == '\\' && Pos + 1 != End)
3398 // This macro should have parameters, but look for $0, $1, ..., $n too.
3399 if (Body[Pos] != '$' || Pos + 1 == End)
3401 char Next = Body[Pos + 1];
3402 if (Next == '$' || Next == 'n' ||
3403 isdigit(static_cast<unsigned char>(Next)))
3407 // Check if we reached the end.
3411 if (Body[Pos] == '$') {
3412 switch (Body[Pos + 1]) {
3417 // $n => number of arguments
3419 PositionalParametersFound = true;
3422 // $[0-9] => argument
3424 PositionalParametersFound = true;
3430 unsigned I = Pos + 1;
3431 while (isIdentifierChar(Body[I]) && I + 1 != End)
3434 const char *Begin = Body.data() + Pos + 1;
3435 StringRef Argument(Begin, I - (Pos + 1));
3437 for (; Index < NParameters; ++Index)
3438 if (Parameters[Index].Name == Argument)
3441 if (Index == NParameters) {
3442 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3448 NamedParametersFound = true;
3449 Pos += 1 + Argument.size();
3452 // Update the scan point.
3453 Body = Body.substr(Pos);
3456 if (!NamedParametersFound && PositionalParametersFound)
3457 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3458 "used in macro body, possible positional parameter "
3459 "found in body which will have no effect");
3462 /// parseDirectiveEndMacro
3465 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3466 if (getLexer().isNot(AsmToken::EndOfStatement))
3467 return TokError("unexpected token in '" + Directive + "' directive");
3469 // If we are inside a macro instantiation, terminate the current
3471 if (isInsideMacroInstantiation()) {
3476 // Otherwise, this .endmacro is a stray entry in the file; well formed
3477 // .endmacro directives are handled during the macro definition parsing.
3478 return TokError("unexpected '" + Directive + "' in file, "
3479 "no current macro definition");
3482 /// parseDirectivePurgeMacro
3484 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3486 if (parseIdentifier(Name))
3487 return TokError("expected identifier in '.purgem' directive");
3489 if (getLexer().isNot(AsmToken::EndOfStatement))
3490 return TokError("unexpected token in '.purgem' directive");
3492 if (!lookupMacro(Name))
3493 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3495 undefineMacro(Name);
3499 /// parseDirectiveBundleAlignMode
3500 /// ::= {.bundle_align_mode} expression
3501 bool AsmParser::parseDirectiveBundleAlignMode() {
3502 checkForValidSection();
3504 // Expect a single argument: an expression that evaluates to a constant
3505 // in the inclusive range 0-30.
3506 SMLoc ExprLoc = getLexer().getLoc();
3507 int64_t AlignSizePow2;
3508 if (parseAbsoluteExpression(AlignSizePow2))
3510 else if (getLexer().isNot(AsmToken::EndOfStatement))
3511 return TokError("unexpected token after expression in"
3512 " '.bundle_align_mode' directive");
3513 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3514 return Error(ExprLoc,
3515 "invalid bundle alignment size (expected between 0 and 30)");
3519 // Because of AlignSizePow2's verified range we can safely truncate it to
3521 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3525 /// parseDirectiveBundleLock
3526 /// ::= {.bundle_lock} [align_to_end]
3527 bool AsmParser::parseDirectiveBundleLock() {
3528 checkForValidSection();
3529 bool AlignToEnd = false;
3531 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3533 SMLoc Loc = getTok().getLoc();
3534 const char *kInvalidOptionError =
3535 "invalid option for '.bundle_lock' directive";
3537 if (parseIdentifier(Option))
3538 return Error(Loc, kInvalidOptionError);
3540 if (Option != "align_to_end")
3541 return Error(Loc, kInvalidOptionError);
3542 else if (getLexer().isNot(AsmToken::EndOfStatement))
3544 "unexpected token after '.bundle_lock' directive option");
3550 getStreamer().EmitBundleLock(AlignToEnd);
3554 /// parseDirectiveBundleLock
3555 /// ::= {.bundle_lock}
3556 bool AsmParser::parseDirectiveBundleUnlock() {
3557 checkForValidSection();
3559 if (getLexer().isNot(AsmToken::EndOfStatement))
3560 return TokError("unexpected token in '.bundle_unlock' directive");
3563 getStreamer().EmitBundleUnlock();
3567 /// parseDirectiveSpace
3568 /// ::= (.skip | .space) expression [ , expression ]
3569 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3570 checkForValidSection();
3573 if (parseAbsoluteExpression(NumBytes))
3576 int64_t FillExpr = 0;
3577 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3578 if (getLexer().isNot(AsmToken::Comma))
3579 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3582 if (parseAbsoluteExpression(FillExpr))
3585 if (getLexer().isNot(AsmToken::EndOfStatement))
3586 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3592 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3595 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3596 getStreamer().EmitFill(NumBytes, FillExpr);
3601 /// parseDirectiveLEB128
3602 /// ::= (.sleb128 | .uleb128) expression
3603 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3604 checkForValidSection();
3605 const MCExpr *Value;
3607 if (parseExpression(Value))
3610 if (getLexer().isNot(AsmToken::EndOfStatement))
3611 return TokError("unexpected token in directive");
3614 getStreamer().EmitSLEB128Value(Value);
3616 getStreamer().EmitULEB128Value(Value);
3621 /// parseDirectiveSymbolAttribute
3622 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3623 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3624 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3627 SMLoc Loc = getTok().getLoc();
3629 if (parseIdentifier(Name))
3630 return Error(Loc, "expected identifier in directive");
3632 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3634 // Assembler local symbols don't make any sense here. Complain loudly.
3635 if (Sym->isTemporary())
3636 return Error(Loc, "non-local symbol required in directive");
3638 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3639 return Error(Loc, "unable to emit symbol attribute");
3641 if (getLexer().is(AsmToken::EndOfStatement))
3644 if (getLexer().isNot(AsmToken::Comma))
3645 return TokError("unexpected token in directive");
3654 /// parseDirectiveComm
3655 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3656 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3657 checkForValidSection();
3659 SMLoc IDLoc = getLexer().getLoc();
3661 if (parseIdentifier(Name))
3662 return TokError("expected identifier in directive");
3664 // Handle the identifier as the key symbol.
3665 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3667 if (getLexer().isNot(AsmToken::Comma))
3668 return TokError("unexpected token in directive");
3672 SMLoc SizeLoc = getLexer().getLoc();
3673 if (parseAbsoluteExpression(Size))
3676 int64_t Pow2Alignment = 0;
3677 SMLoc Pow2AlignmentLoc;
3678 if (getLexer().is(AsmToken::Comma)) {
3680 Pow2AlignmentLoc = getLexer().getLoc();
3681 if (parseAbsoluteExpression(Pow2Alignment))
3684 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3685 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3686 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3688 // If this target takes alignments in bytes (not log) validate and convert.
3689 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3690 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3691 if (!isPowerOf2_64(Pow2Alignment))
3692 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3693 Pow2Alignment = Log2_64(Pow2Alignment);
3697 if (getLexer().isNot(AsmToken::EndOfStatement))
3698 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3702 // NOTE: a size of zero for a .comm should create a undefined symbol
3703 // but a size of .lcomm creates a bss symbol of size zero.
3705 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3706 "be less than zero");
3708 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3709 // may internally end up wanting an alignment in bytes.
3710 // FIXME: Diagnose overflow.
3711 if (Pow2Alignment < 0)
3712 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3713 "alignment, can't be less than zero");
3715 if (!Sym->isUndefined())
3716 return Error(IDLoc, "invalid symbol redefinition");
3718 // Create the Symbol as a common or local common with Size and Pow2Alignment
3720 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3724 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3728 /// parseDirectiveAbort
3729 /// ::= .abort [... message ...]
3730 bool AsmParser::parseDirectiveAbort() {
3731 // FIXME: Use loc from directive.
3732 SMLoc Loc = getLexer().getLoc();
3734 StringRef Str = parseStringToEndOfStatement();
3735 if (getLexer().isNot(AsmToken::EndOfStatement))
3736 return TokError("unexpected token in '.abort' directive");
3741 Error(Loc, ".abort detected. Assembly stopping.");
3743 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3744 // FIXME: Actually abort assembly here.
3749 /// parseDirectiveInclude
3750 /// ::= .include "filename"
3751 bool AsmParser::parseDirectiveInclude() {
3752 if (getLexer().isNot(AsmToken::String))
3753 return TokError("expected string in '.include' directive");
3755 // Allow the strings to have escaped octal character sequence.
3756 std::string Filename;
3757 if (parseEscapedString(Filename))
3759 SMLoc IncludeLoc = getLexer().getLoc();
3762 if (getLexer().isNot(AsmToken::EndOfStatement))
3763 return TokError("unexpected token in '.include' directive");
3765 // Attempt to switch the lexer to the included file before consuming the end
3766 // of statement to avoid losing it when we switch.
3767 if (enterIncludeFile(Filename)) {
3768 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3775 /// parseDirectiveIncbin
3776 /// ::= .incbin "filename"
3777 bool AsmParser::parseDirectiveIncbin() {
3778 if (getLexer().isNot(AsmToken::String))
3779 return TokError("expected string in '.incbin' directive");
3781 // Allow the strings to have escaped octal character sequence.
3782 std::string Filename;
3783 if (parseEscapedString(Filename))
3785 SMLoc IncbinLoc = getLexer().getLoc();
3788 if (getLexer().isNot(AsmToken::EndOfStatement))
3789 return TokError("unexpected token in '.incbin' directive");
3791 // Attempt to process the included file.
3792 if (processIncbinFile(Filename)) {
3793 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3800 /// parseDirectiveIf
3801 /// ::= .if expression
3802 /// ::= .ifne expression
3803 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3804 TheCondStack.push_back(TheCondState);
3805 TheCondState.TheCond = AsmCond::IfCond;
3806 if (TheCondState.Ignore) {
3807 eatToEndOfStatement();
3810 if (parseAbsoluteExpression(ExprValue))
3813 if (getLexer().isNot(AsmToken::EndOfStatement))
3814 return TokError("unexpected token in '.if' directive");
3818 TheCondState.CondMet = ExprValue;
3819 TheCondState.Ignore = !TheCondState.CondMet;
3825 /// parseDirectiveIfb
3827 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3828 TheCondStack.push_back(TheCondState);
3829 TheCondState.TheCond = AsmCond::IfCond;
3831 if (TheCondState.Ignore) {
3832 eatToEndOfStatement();
3834 StringRef Str = parseStringToEndOfStatement();
3836 if (getLexer().isNot(AsmToken::EndOfStatement))
3837 return TokError("unexpected token in '.ifb' directive");
3841 TheCondState.CondMet = ExpectBlank == Str.empty();
3842 TheCondState.Ignore = !TheCondState.CondMet;
3848 /// parseDirectiveIfc
3849 /// ::= .ifc string1, string2
3850 /// ::= .ifnc string1, string2
3851 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3852 TheCondStack.push_back(TheCondState);
3853 TheCondState.TheCond = AsmCond::IfCond;
3855 if (TheCondState.Ignore) {
3856 eatToEndOfStatement();
3858 StringRef Str1 = parseStringToComma();
3860 if (getLexer().isNot(AsmToken::Comma))
3861 return TokError("unexpected token in '.ifc' directive");
3865 StringRef Str2 = parseStringToEndOfStatement();
3867 if (getLexer().isNot(AsmToken::EndOfStatement))
3868 return TokError("unexpected token in '.ifc' directive");
3872 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3873 TheCondState.Ignore = !TheCondState.CondMet;
3879 /// parseDirectiveIfeqs
3880 /// ::= .ifeqs string1, string2
3881 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc) {
3882 if (Lexer.isNot(AsmToken::String)) {
3883 TokError("expected string parameter for '.ifeqs' directive");
3884 eatToEndOfStatement();
3888 StringRef String1 = getTok().getStringContents();
3891 if (Lexer.isNot(AsmToken::Comma)) {
3892 TokError("expected comma after first string for '.ifeqs' directive");
3893 eatToEndOfStatement();
3899 if (Lexer.isNot(AsmToken::String)) {
3900 TokError("expected string parameter for '.ifeqs' directive");
3901 eatToEndOfStatement();
3905 StringRef String2 = getTok().getStringContents();
3908 TheCondStack.push_back(TheCondState);
3909 TheCondState.TheCond = AsmCond::IfCond;
3910 TheCondState.CondMet = String1 == String2;
3911 TheCondState.Ignore = !TheCondState.CondMet;
3916 /// parseDirectiveIfdef
3917 /// ::= .ifdef symbol
3918 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3920 TheCondStack.push_back(TheCondState);
3921 TheCondState.TheCond = AsmCond::IfCond;
3923 if (TheCondState.Ignore) {
3924 eatToEndOfStatement();
3926 if (parseIdentifier(Name))
3927 return TokError("expected identifier after '.ifdef'");
3931 MCSymbol *Sym = getContext().LookupSymbol(Name);
3934 TheCondState.CondMet = (Sym && !Sym->isUndefined());
3936 TheCondState.CondMet = (!Sym || Sym->isUndefined());
3937 TheCondState.Ignore = !TheCondState.CondMet;
3943 /// parseDirectiveElseIf
3944 /// ::= .elseif expression
3945 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3946 if (TheCondState.TheCond != AsmCond::IfCond &&
3947 TheCondState.TheCond != AsmCond::ElseIfCond)
3948 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3950 TheCondState.TheCond = AsmCond::ElseIfCond;
3952 bool LastIgnoreState = false;
3953 if (!TheCondStack.empty())
3954 LastIgnoreState = TheCondStack.back().Ignore;
3955 if (LastIgnoreState || TheCondState.CondMet) {
3956 TheCondState.Ignore = true;
3957 eatToEndOfStatement();
3960 if (parseAbsoluteExpression(ExprValue))
3963 if (getLexer().isNot(AsmToken::EndOfStatement))
3964 return TokError("unexpected token in '.elseif' directive");
3967 TheCondState.CondMet = ExprValue;
3968 TheCondState.Ignore = !TheCondState.CondMet;
3974 /// parseDirectiveElse
3976 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3977 if (getLexer().isNot(AsmToken::EndOfStatement))
3978 return TokError("unexpected token in '.else' directive");
3982 if (TheCondState.TheCond != AsmCond::IfCond &&
3983 TheCondState.TheCond != AsmCond::ElseIfCond)
3984 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3986 TheCondState.TheCond = AsmCond::ElseCond;
3987 bool LastIgnoreState = false;
3988 if (!TheCondStack.empty())
3989 LastIgnoreState = TheCondStack.back().Ignore;
3990 if (LastIgnoreState || TheCondState.CondMet)
3991 TheCondState.Ignore = true;
3993 TheCondState.Ignore = false;
3998 /// parseDirectiveEnd
4000 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4001 if (getLexer().isNot(AsmToken::EndOfStatement))
4002 return TokError("unexpected token in '.end' directive");
4006 while (Lexer.isNot(AsmToken::Eof))
4012 /// parseDirectiveError
4014 /// ::= .error [string]
4015 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4016 if (!TheCondStack.empty()) {
4017 if (TheCondStack.back().Ignore) {
4018 eatToEndOfStatement();
4024 return Error(L, ".err encountered");
4026 StringRef Message = ".error directive invoked in source file";
4027 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4028 if (Lexer.isNot(AsmToken::String)) {
4029 TokError(".error argument must be a string");
4030 eatToEndOfStatement();
4034 Message = getTok().getStringContents();
4042 /// parseDirectiveEndIf
4044 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4045 if (getLexer().isNot(AsmToken::EndOfStatement))
4046 return TokError("unexpected token in '.endif' directive");
4050 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4051 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4053 if (!TheCondStack.empty()) {
4054 TheCondState = TheCondStack.back();
4055 TheCondStack.pop_back();
4061 void AsmParser::initializeDirectiveKindMap() {
4062 DirectiveKindMap[".set"] = DK_SET;
4063 DirectiveKindMap[".equ"] = DK_EQU;
4064 DirectiveKindMap[".equiv"] = DK_EQUIV;
4065 DirectiveKindMap[".ascii"] = DK_ASCII;
4066 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4067 DirectiveKindMap[".string"] = DK_STRING;
4068 DirectiveKindMap[".byte"] = DK_BYTE;
4069 DirectiveKindMap[".short"] = DK_SHORT;
4070 DirectiveKindMap[".value"] = DK_VALUE;
4071 DirectiveKindMap[".2byte"] = DK_2BYTE;
4072 DirectiveKindMap[".long"] = DK_LONG;
4073 DirectiveKindMap[".int"] = DK_INT;
4074 DirectiveKindMap[".4byte"] = DK_4BYTE;
4075 DirectiveKindMap[".quad"] = DK_QUAD;
4076 DirectiveKindMap[".8byte"] = DK_8BYTE;
4077 DirectiveKindMap[".octa"] = DK_OCTA;
4078 DirectiveKindMap[".single"] = DK_SINGLE;
4079 DirectiveKindMap[".float"] = DK_FLOAT;
4080 DirectiveKindMap[".double"] = DK_DOUBLE;
4081 DirectiveKindMap[".align"] = DK_ALIGN;
4082 DirectiveKindMap[".align32"] = DK_ALIGN32;
4083 DirectiveKindMap[".balign"] = DK_BALIGN;
4084 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4085 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4086 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4087 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4088 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4089 DirectiveKindMap[".org"] = DK_ORG;
4090 DirectiveKindMap[".fill"] = DK_FILL;
4091 DirectiveKindMap[".zero"] = DK_ZERO;
4092 DirectiveKindMap[".extern"] = DK_EXTERN;
4093 DirectiveKindMap[".globl"] = DK_GLOBL;
4094 DirectiveKindMap[".global"] = DK_GLOBAL;
4095 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4096 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4097 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4098 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4099 DirectiveKindMap[".reference"] = DK_REFERENCE;
4100 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4101 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4102 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4103 DirectiveKindMap[".comm"] = DK_COMM;
4104 DirectiveKindMap[".common"] = DK_COMMON;
4105 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4106 DirectiveKindMap[".abort"] = DK_ABORT;
4107 DirectiveKindMap[".include"] = DK_INCLUDE;
4108 DirectiveKindMap[".incbin"] = DK_INCBIN;
4109 DirectiveKindMap[".code16"] = DK_CODE16;
4110 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4111 DirectiveKindMap[".rept"] = DK_REPT;
4112 DirectiveKindMap[".rep"] = DK_REPT;
4113 DirectiveKindMap[".irp"] = DK_IRP;
4114 DirectiveKindMap[".irpc"] = DK_IRPC;
4115 DirectiveKindMap[".endr"] = DK_ENDR;
4116 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4117 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4118 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4119 DirectiveKindMap[".if"] = DK_IF;
4120 DirectiveKindMap[".ifne"] = DK_IFNE;
4121 DirectiveKindMap[".ifb"] = DK_IFB;
4122 DirectiveKindMap[".ifnb"] = DK_IFNB;
4123 DirectiveKindMap[".ifc"] = DK_IFC;
4124 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4125 DirectiveKindMap[".ifnc"] = DK_IFNC;
4126 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4127 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4128 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4129 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4130 DirectiveKindMap[".else"] = DK_ELSE;
4131 DirectiveKindMap[".end"] = DK_END;
4132 DirectiveKindMap[".endif"] = DK_ENDIF;
4133 DirectiveKindMap[".skip"] = DK_SKIP;
4134 DirectiveKindMap[".space"] = DK_SPACE;
4135 DirectiveKindMap[".file"] = DK_FILE;
4136 DirectiveKindMap[".line"] = DK_LINE;
4137 DirectiveKindMap[".loc"] = DK_LOC;
4138 DirectiveKindMap[".stabs"] = DK_STABS;
4139 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4140 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4141 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4142 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4143 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4144 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4145 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4146 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4147 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4148 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4149 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4150 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4151 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4152 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4153 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4154 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4155 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4156 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4157 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4158 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4159 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4160 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4161 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4162 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4163 DirectiveKindMap[".macro"] = DK_MACRO;
4164 DirectiveKindMap[".endm"] = DK_ENDM;
4165 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4166 DirectiveKindMap[".purgem"] = DK_PURGEM;
4167 DirectiveKindMap[".err"] = DK_ERR;
4168 DirectiveKindMap[".error"] = DK_ERROR;
4171 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4172 AsmToken EndToken, StartToken = getTok();
4174 unsigned NestLevel = 0;
4176 // Check whether we have reached the end of the file.
4177 if (getLexer().is(AsmToken::Eof)) {
4178 Error(DirectiveLoc, "no matching '.endr' in definition");
4182 if (Lexer.is(AsmToken::Identifier) &&
4183 (getTok().getIdentifier() == ".rept")) {
4187 // Otherwise, check whether we have reached the .endr.
4188 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4189 if (NestLevel == 0) {
4190 EndToken = getTok();
4192 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4193 TokError("unexpected token in '.endr' directive");
4201 // Otherwise, scan till the end of the statement.
4202 eatToEndOfStatement();
4205 const char *BodyStart = StartToken.getLoc().getPointer();
4206 const char *BodyEnd = EndToken.getLoc().getPointer();
4207 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4209 // We Are Anonymous.
4210 MacroLikeBodies.push_back(MCAsmMacro(StringRef(), Body, None));
4211 return &MacroLikeBodies.back();
4214 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4215 raw_svector_ostream &OS) {
4218 MemoryBuffer *Instantiation =
4219 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4221 // Create the macro instantiation object and add to the current macro
4222 // instantiation stack.
4223 MacroInstantiation *MI = new MacroInstantiation(
4224 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
4225 ActiveMacros.push_back(MI);
4227 // Jump to the macro instantiation and prime the lexer.
4228 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
4229 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
4233 /// parseDirectiveRept
4234 /// ::= .rep | .rept count
4235 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4236 const MCExpr *CountExpr;
4237 SMLoc CountLoc = getTok().getLoc();
4238 if (parseExpression(CountExpr))
4242 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4243 eatToEndOfStatement();
4244 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4248 return Error(CountLoc, "Count is negative");
4250 if (Lexer.isNot(AsmToken::EndOfStatement))
4251 return TokError("unexpected token in '" + Dir + "' directive");
4253 // Eat the end of statement.
4256 // Lex the rept definition.
4257 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4261 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4262 // to hold the macro body with substitutions.
4263 SmallString<256> Buf;
4264 raw_svector_ostream OS(Buf);
4266 if (expandMacro(OS, M->Body, None, None, getTok().getLoc()))
4269 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4274 /// parseDirectiveIrp
4275 /// ::= .irp symbol,values
4276 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4277 MCAsmMacroParameter Parameter;
4279 if (parseIdentifier(Parameter.Name))
4280 return TokError("expected identifier in '.irp' directive");
4282 if (Lexer.isNot(AsmToken::Comma))
4283 return TokError("expected comma in '.irp' directive");
4287 MCAsmMacroArguments A;
4288 if (parseMacroArguments(nullptr, A))
4291 // Eat the end of statement.
4294 // Lex the irp definition.
4295 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4299 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4300 // to hold the macro body with substitutions.
4301 SmallString<256> Buf;
4302 raw_svector_ostream OS(Buf);
4304 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4305 if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc()))
4309 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4314 /// parseDirectiveIrpc
4315 /// ::= .irpc symbol,values
4316 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4317 MCAsmMacroParameter Parameter;
4319 if (parseIdentifier(Parameter.Name))
4320 return TokError("expected identifier in '.irpc' directive");
4322 if (Lexer.isNot(AsmToken::Comma))
4323 return TokError("expected comma in '.irpc' directive");
4327 MCAsmMacroArguments A;
4328 if (parseMacroArguments(nullptr, A))
4331 if (A.size() != 1 || A.front().size() != 1)
4332 return TokError("unexpected token in '.irpc' directive");
4334 // Eat the end of statement.
4337 // Lex the irpc definition.
4338 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4342 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4343 // to hold the macro body with substitutions.
4344 SmallString<256> Buf;
4345 raw_svector_ostream OS(Buf);
4347 StringRef Values = A.front().front().getString();
4348 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4349 MCAsmMacroArgument Arg;
4350 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4352 if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc()))
4356 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4361 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4362 if (ActiveMacros.empty())
4363 return TokError("unmatched '.endr' directive");
4365 // The only .repl that should get here are the ones created by
4366 // instantiateMacroLikeBody.
4367 assert(getLexer().is(AsmToken::EndOfStatement));
4373 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4375 const MCExpr *Value;
4376 SMLoc ExprLoc = getLexer().getLoc();
4377 if (parseExpression(Value))
4379 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4381 return Error(ExprLoc, "unexpected expression in _emit");
4382 uint64_t IntValue = MCE->getValue();
4383 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4384 return Error(ExprLoc, "literal value out of range for directive");
4386 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4390 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4391 const MCExpr *Value;
4392 SMLoc ExprLoc = getLexer().getLoc();
4393 if (parseExpression(Value))
4395 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4397 return Error(ExprLoc, "unexpected expression in align");
4398 uint64_t IntValue = MCE->getValue();
4399 if (!isPowerOf2_64(IntValue))
4400 return Error(ExprLoc, "literal value not a power of two greater then zero");
4402 Info.AsmRewrites->push_back(
4403 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4407 // We are comparing pointers, but the pointers are relative to a single string.
4408 // Thus, this should always be deterministic.
4409 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4410 const AsmRewrite *AsmRewriteB) {
4411 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4413 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4416 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4417 // rewrite to the same location. Make sure the SizeDirective rewrite is
4418 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4419 // ensures the sort algorithm is stable.
4420 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4421 AsmRewritePrecedence[AsmRewriteB->Kind])
4424 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4425 AsmRewritePrecedence[AsmRewriteB->Kind])
4427 llvm_unreachable("Unstable rewrite sort.");
4430 bool AsmParser::parseMSInlineAsm(
4431 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4432 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4433 SmallVectorImpl<std::string> &Constraints,
4434 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4435 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4436 SmallVector<void *, 4> InputDecls;
4437 SmallVector<void *, 4> OutputDecls;
4438 SmallVector<bool, 4> InputDeclsAddressOf;
4439 SmallVector<bool, 4> OutputDeclsAddressOf;
4440 SmallVector<std::string, 4> InputConstraints;
4441 SmallVector<std::string, 4> OutputConstraints;
4442 SmallVector<unsigned, 4> ClobberRegs;
4444 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4449 // While we have input, parse each statement.
4450 unsigned InputIdx = 0;
4451 unsigned OutputIdx = 0;
4452 while (getLexer().isNot(AsmToken::Eof)) {
4453 ParseStatementInfo Info(&AsmStrRewrites);
4454 if (parseStatement(Info))
4457 if (Info.ParseError)
4460 if (Info.Opcode == ~0U)
4463 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4465 // Build the list of clobbers, outputs and inputs.
4466 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4467 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4470 if (Operand->isImm())
4473 // Register operand.
4474 if (Operand->isReg() && !Operand->needAddressOf()) {
4475 unsigned NumDefs = Desc.getNumDefs();
4477 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4478 ClobberRegs.push_back(Operand->getReg());
4482 // Expr/Input or Output.
4483 StringRef SymName = Operand->getSymName();
4484 if (SymName.empty())
4487 void *OpDecl = Operand->getOpDecl();
4491 bool isOutput = (i == 1) && Desc.mayStore();
4492 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4495 OutputDecls.push_back(OpDecl);
4496 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4497 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4498 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4500 InputDecls.push_back(OpDecl);
4501 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4502 InputConstraints.push_back(Operand->getConstraint().str());
4503 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4507 // Consider implicit defs to be clobbers. Think of cpuid and push.
4508 const uint16_t *ImpDefs = Desc.getImplicitDefs();
4509 for (unsigned I = 0, E = Desc.getNumImplicitDefs(); I != E; ++I)
4510 ClobberRegs.push_back(ImpDefs[I]);
4513 // Set the number of Outputs and Inputs.
4514 NumOutputs = OutputDecls.size();
4515 NumInputs = InputDecls.size();
4517 // Set the unique clobbers.
4518 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4519 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4521 Clobbers.assign(ClobberRegs.size(), std::string());
4522 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4523 raw_string_ostream OS(Clobbers[I]);
4524 IP->printRegName(OS, ClobberRegs[I]);
4527 // Merge the various outputs and inputs. Output are expected first.
4528 if (NumOutputs || NumInputs) {
4529 unsigned NumExprs = NumOutputs + NumInputs;
4530 OpDecls.resize(NumExprs);
4531 Constraints.resize(NumExprs);
4532 for (unsigned i = 0; i < NumOutputs; ++i) {
4533 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4534 Constraints[i] = OutputConstraints[i];
4536 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4537 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4538 Constraints[j] = InputConstraints[i];
4542 // Build the IR assembly string.
4543 std::string AsmStringIR;
4544 raw_string_ostream OS(AsmStringIR);
4545 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4546 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4547 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4548 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4549 E = AsmStrRewrites.end();
4551 AsmRewriteKind Kind = (*I).Kind;
4552 if (Kind == AOK_Delete)
4555 const char *Loc = (*I).Loc.getPointer();
4556 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4558 // Emit everything up to the immediate/expression.
4559 unsigned Len = Loc - AsmStart;
4561 OS << StringRef(AsmStart, Len);
4563 // Skip the original expression.
4564 if (Kind == AOK_Skip) {
4565 AsmStart = Loc + (*I).Len;
4569 unsigned AdditionalSkip = 0;
4570 // Rewrite expressions in $N notation.
4575 OS << "$$" << (*I).Val;
4581 OS << '$' << InputIdx++;
4584 OS << '$' << OutputIdx++;
4586 case AOK_SizeDirective:
4589 case 8: OS << "byte ptr "; break;
4590 case 16: OS << "word ptr "; break;
4591 case 32: OS << "dword ptr "; break;
4592 case 64: OS << "qword ptr "; break;
4593 case 80: OS << "xword ptr "; break;
4594 case 128: OS << "xmmword ptr "; break;
4595 case 256: OS << "ymmword ptr "; break;
4602 unsigned Val = (*I).Val;
4603 OS << ".align " << Val;
4605 // Skip the original immediate.
4606 assert(Val < 10 && "Expected alignment less then 2^10.");
4607 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4610 case AOK_DotOperator:
4611 // Insert the dot if the user omitted it.
4613 if (AsmStringIR.back() != '.')
4619 // Skip the original expression.
4620 AsmStart = Loc + (*I).Len + AdditionalSkip;
4623 // Emit the remainder of the asm string.
4624 if (AsmStart != AsmEnd)
4625 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4627 AsmString = OS.str();
4631 /// \brief Create an MCAsmParser instance.
4632 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4633 MCStreamer &Out, const MCAsmInfo &MAI) {
4634 return new AsmParser(SM, C, Out, MAI);