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<std::unique_ptr<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) {}
120 /// \brief The concrete assembly parser instance.
121 class AsmParser : public MCAsmParser {
122 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
123 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
128 const MCAsmInfo &MAI;
130 SourceMgr::DiagHandlerTy SavedDiagHandler;
131 void *SavedDiagContext;
132 MCAsmParserExtension *PlatformParser;
134 /// This is the current buffer index we're lexing from as managed by the
135 /// SourceMgr object.
138 AsmCond TheCondState;
139 std::vector<AsmCond> TheCondStack;
141 /// \brief maps directive names to handler methods in parser
142 /// extensions. Extensions register themselves in this map by calling
143 /// addDirectiveHandler.
144 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
146 /// \brief Map of currently defined macros.
147 StringMap<MCAsmMacro*> MacroMap;
149 /// \brief Stack of active macro instantiations.
150 std::vector<MacroInstantiation*> ActiveMacros;
152 /// \brief List of bodies of anonymous macros.
153 std::deque<MCAsmMacro> MacroLikeBodies;
155 /// Boolean tracking whether macro substitution is enabled.
156 unsigned MacrosEnabledFlag : 1;
158 /// Flag tracking whether any errors have been encountered.
159 unsigned HadError : 1;
161 /// The values from the last parsed cpp hash file line comment if any.
162 StringRef CppHashFilename;
163 int64_t CppHashLineNumber;
166 /// When generating dwarf for assembly source files we need to calculate the
167 /// logical line number based on the last parsed cpp hash file line comment
168 /// and current line. Since this is slow and messes up the SourceMgr's
169 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
170 SMLoc LastQueryIDLoc;
171 unsigned LastQueryBuffer;
172 unsigned LastQueryLine;
174 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
175 unsigned AssemblerDialect;
177 /// \brief is Darwin compatibility enabled?
180 /// \brief Are we parsing ms-style inline assembly?
181 bool ParsingInlineAsm;
184 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
185 const MCAsmInfo &MAI);
186 virtual ~AsmParser();
188 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
190 void addDirectiveHandler(StringRef Directive,
191 ExtensionDirectiveHandler Handler) override {
192 ExtensionDirectiveMap[Directive] = Handler;
196 /// @name MCAsmParser Interface
199 SourceMgr &getSourceManager() override { return SrcMgr; }
200 MCAsmLexer &getLexer() override { return Lexer; }
201 MCContext &getContext() override { return Ctx; }
202 MCStreamer &getStreamer() override { return Out; }
203 unsigned getAssemblerDialect() override {
204 if (AssemblerDialect == ~0U)
205 return MAI.getAssemblerDialect();
207 return AssemblerDialect;
209 void setAssemblerDialect(unsigned i) override {
210 AssemblerDialect = i;
213 void Note(SMLoc L, const Twine &Msg,
214 ArrayRef<SMRange> Ranges = None) override;
215 bool Warning(SMLoc L, const Twine &Msg,
216 ArrayRef<SMRange> Ranges = None) override;
217 bool Error(SMLoc L, const Twine &Msg,
218 ArrayRef<SMRange> Ranges = None) override;
220 const AsmToken &Lex() override;
222 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
223 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
225 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
226 unsigned &NumOutputs, unsigned &NumInputs,
227 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
228 SmallVectorImpl<std::string> &Constraints,
229 SmallVectorImpl<std::string> &Clobbers,
230 const MCInstrInfo *MII, const MCInstPrinter *IP,
231 MCAsmParserSemaCallback &SI) override;
233 bool parseExpression(const MCExpr *&Res);
234 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
235 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
236 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
237 bool parseAbsoluteExpression(int64_t &Res) override;
239 /// \brief Parse an identifier or string (as a quoted identifier)
240 /// and set \p Res to the identifier contents.
241 bool parseIdentifier(StringRef &Res) override;
242 void eatToEndOfStatement() override;
244 void checkForValidSection() override;
249 bool parseStatement(ParseStatementInfo &Info);
250 void eatToEndOfLine();
251 bool parseCppHashLineFilenameComment(const SMLoc &L);
253 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
254 ArrayRef<MCAsmMacroParameter> Parameters);
255 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
256 ArrayRef<MCAsmMacroParameter> Parameters,
257 ArrayRef<MCAsmMacroArgument> A,
260 /// \brief Are macros enabled in the parser?
261 bool areMacrosEnabled() {return MacrosEnabledFlag;}
263 /// \brief Control a flag in the parser that enables or disables macros.
264 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
266 /// \brief Lookup a previously defined macro.
267 /// \param Name Macro name.
268 /// \returns Pointer to macro. NULL if no such macro was defined.
269 const MCAsmMacro* lookupMacro(StringRef Name);
271 /// \brief Define a new macro with the given name and information.
272 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
274 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
275 void undefineMacro(StringRef Name);
277 /// \brief Are we inside a macro instantiation?
278 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
280 /// \brief Handle entry to macro instantiation.
282 /// \param M The macro.
283 /// \param NameLoc Instantiation location.
284 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
286 /// \brief Handle exit from macro instantiation.
287 void handleMacroExit();
289 /// \brief Extract AsmTokens for a macro argument.
290 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
292 /// \brief Parse all macro arguments for a given macro.
293 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
295 void printMacroInstantiations();
296 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
297 ArrayRef<SMRange> Ranges = None) const {
298 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
300 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
302 /// \brief Enter the specified file. This returns true on failure.
303 bool enterIncludeFile(const std::string &Filename);
305 /// \brief Process the specified file for the .incbin directive.
306 /// This returns true on failure.
307 bool processIncbinFile(const std::string &Filename);
309 /// \brief Reset the current lexer position to that given by \p Loc. The
310 /// current token is not set; clients should ensure Lex() is called
313 /// \param InBuffer If not 0, should be the known buffer id that contains the
315 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
317 /// \brief Parse up to the end of statement and a return the contents from the
318 /// current token until the end of the statement; the current token on exit
319 /// will be either the EndOfStatement or EOF.
320 StringRef parseStringToEndOfStatement() override;
322 /// \brief Parse until the end of a statement or a comma is encountered,
323 /// return the contents from the current token up to the end or comma.
324 StringRef parseStringToComma();
326 bool parseAssignment(StringRef Name, bool allow_redef,
327 bool NoDeadStrip = false);
329 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
330 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
331 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
333 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
335 // Generic (target and platform independent) directive parsing.
337 DK_NO_DIRECTIVE, // Placeholder
338 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
339 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
340 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
341 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
342 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
343 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
344 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
345 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
346 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
347 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
348 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
349 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
350 DK_ELSEIF, DK_ELSE, DK_ENDIF,
351 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
352 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
353 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
354 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
355 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
356 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
357 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
358 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
359 DK_SLEB128, DK_ULEB128,
364 /// \brief Maps directive name --> DirectiveKind enum, for
365 /// directives parsed by this class.
366 StringMap<DirectiveKind> DirectiveKindMap;
368 // ".ascii", ".asciz", ".string"
369 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
370 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
371 bool parseDirectiveOctaValue(); // ".octa"
372 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
373 bool parseDirectiveFill(); // ".fill"
374 bool parseDirectiveZero(); // ".zero"
375 // ".set", ".equ", ".equiv"
376 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
377 bool parseDirectiveOrg(); // ".org"
378 // ".align{,32}", ".p2align{,w,l}"
379 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
381 // ".file", ".line", ".loc", ".stabs"
382 bool parseDirectiveFile(SMLoc DirectiveLoc);
383 bool parseDirectiveLine();
384 bool parseDirectiveLoc();
385 bool parseDirectiveStabs();
388 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
389 bool parseDirectiveCFIWindowSave();
390 bool parseDirectiveCFISections();
391 bool parseDirectiveCFIStartProc();
392 bool parseDirectiveCFIEndProc();
393 bool parseDirectiveCFIDefCfaOffset();
394 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
395 bool parseDirectiveCFIAdjustCfaOffset();
396 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
397 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
398 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
399 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
400 bool parseDirectiveCFIRememberState();
401 bool parseDirectiveCFIRestoreState();
402 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
403 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
404 bool parseDirectiveCFIEscape();
405 bool parseDirectiveCFISignalFrame();
406 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
409 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
410 bool parseDirectiveEndMacro(StringRef Directive);
411 bool parseDirectiveMacro(SMLoc DirectiveLoc);
412 bool parseDirectiveMacrosOnOff(StringRef Directive);
414 // ".bundle_align_mode"
415 bool parseDirectiveBundleAlignMode();
417 bool parseDirectiveBundleLock();
419 bool parseDirectiveBundleUnlock();
422 bool parseDirectiveSpace(StringRef IDVal);
424 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
425 bool parseDirectiveLEB128(bool Signed);
427 /// \brief Parse a directive like ".globl" which
428 /// accepts a single symbol (which should be a label or an external).
429 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
431 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
433 bool parseDirectiveAbort(); // ".abort"
434 bool parseDirectiveInclude(); // ".include"
435 bool parseDirectiveIncbin(); // ".incbin"
437 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
438 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
439 // ".ifb" or ".ifnb", depending on ExpectBlank.
440 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
441 // ".ifc" or ".ifnc", depending on ExpectEqual.
442 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
444 bool parseDirectiveIfeqs(SMLoc DirectiveLoc);
445 // ".ifdef" or ".ifndef", depending on expect_defined
446 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
447 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
448 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
449 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
450 bool parseEscapedString(std::string &Data) override;
452 const MCExpr *applyModifierToExpr(const MCExpr *E,
453 MCSymbolRefExpr::VariantKind Variant);
455 // Macro-like directives
456 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
457 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
458 raw_svector_ostream &OS);
459 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
460 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
461 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
462 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
464 // "_emit" or "__emit"
465 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
469 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
472 bool parseDirectiveEnd(SMLoc DirectiveLoc);
474 // ".err" or ".error"
475 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
477 void initializeDirectiveKindMap();
483 extern MCAsmParserExtension *createDarwinAsmParser();
484 extern MCAsmParserExtension *createELFAsmParser();
485 extern MCAsmParserExtension *createCOFFAsmParser();
489 enum { DEFAULT_ADDRSPACE = 0 };
491 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
492 const MCAsmInfo &_MAI)
493 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
494 PlatformParser(nullptr), CurBuffer(_SM.getMainFileID()),
495 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
496 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
497 // Save the old handler.
498 SavedDiagHandler = SrcMgr.getDiagHandler();
499 SavedDiagContext = SrcMgr.getDiagContext();
500 // Set our own handler which calls the saved handler.
501 SrcMgr.setDiagHandler(DiagHandler, this);
502 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
504 // Initialize the platform / file format parser.
505 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
506 case MCObjectFileInfo::IsCOFF:
507 PlatformParser = createCOFFAsmParser();
508 PlatformParser->Initialize(*this);
510 case MCObjectFileInfo::IsMachO:
511 PlatformParser = createDarwinAsmParser();
512 PlatformParser->Initialize(*this);
515 case MCObjectFileInfo::IsELF:
516 PlatformParser = createELFAsmParser();
517 PlatformParser->Initialize(*this);
521 initializeDirectiveKindMap();
524 AsmParser::~AsmParser() {
525 assert((HadError || ActiveMacros.empty()) &&
526 "Unexpected active macro instantiation!");
528 // Destroy any macros.
529 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
532 delete it->getValue();
534 delete PlatformParser;
537 void AsmParser::printMacroInstantiations() {
538 // Print the active macro instantiation stack.
539 for (std::vector<MacroInstantiation *>::const_reverse_iterator
540 it = ActiveMacros.rbegin(),
541 ie = ActiveMacros.rend();
543 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
544 "while in macro instantiation");
547 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
548 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
549 printMacroInstantiations();
552 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
553 if (FatalAssemblerWarnings)
554 return Error(L, Msg, Ranges);
555 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
556 printMacroInstantiations();
560 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
562 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
563 printMacroInstantiations();
567 bool AsmParser::enterIncludeFile(const std::string &Filename) {
568 std::string IncludedFile;
570 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
575 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
579 /// Process the specified .incbin file by searching for it in the include paths
580 /// then just emitting the byte contents of the file to the streamer. This
581 /// returns true on failure.
582 bool AsmParser::processIncbinFile(const std::string &Filename) {
583 std::string IncludedFile;
585 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
589 // Pick up the bytes from the file and emit them.
590 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
594 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
595 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
596 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
599 const AsmToken &AsmParser::Lex() {
600 const AsmToken *tok = &Lexer.Lex();
602 if (tok->is(AsmToken::Eof)) {
603 // If this is the end of an included file, pop the parent file off the
605 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
606 if (ParentIncludeLoc != SMLoc()) {
607 jumpToLoc(ParentIncludeLoc);
612 if (tok->is(AsmToken::Error))
613 Error(Lexer.getErrLoc(), Lexer.getErr());
618 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
619 // Create the initial section, if requested.
620 if (!NoInitialTextSection)
627 AsmCond StartingCondState = TheCondState;
629 // If we are generating dwarf for assembly source files save the initial text
630 // section and generate a .file directive.
631 if (getContext().getGenDwarfForAssembly()) {
632 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
633 getStreamer().EmitLabel(SectionStartSym);
634 auto InsertResult = getContext().addGenDwarfSection(
635 getStreamer().getCurrentSection().first);
636 assert(InsertResult.second && ".text section should not have debug info yet");
637 InsertResult.first->second.first = SectionStartSym;
638 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
639 0, StringRef(), getContext().getMainFileName()));
642 // While we have input, parse each statement.
643 while (Lexer.isNot(AsmToken::Eof)) {
644 ParseStatementInfo Info;
645 if (!parseStatement(Info))
648 // We had an error, validate that one was emitted and recover by skipping to
650 assert(HadError && "Parse statement returned an error, but none emitted!");
651 eatToEndOfStatement();
654 if (TheCondState.TheCond != StartingCondState.TheCond ||
655 TheCondState.Ignore != StartingCondState.Ignore)
656 return TokError("unmatched .ifs or .elses");
658 // Check to see there are no empty DwarfFile slots.
659 const auto &LineTables = getContext().getMCDwarfLineTables();
660 if (!LineTables.empty()) {
662 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
663 if (File.Name.empty() && Index != 0)
664 TokError("unassigned file number: " + Twine(Index) +
665 " for .file directives");
670 // Check to see that all assembler local symbols were actually defined.
671 // Targets that don't do subsections via symbols may not want this, though,
672 // so conservatively exclude them. Only do this if we're finalizing, though,
673 // as otherwise we won't necessarilly have seen everything yet.
674 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
675 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
676 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
679 MCSymbol *Sym = i->getValue();
680 // Variable symbols may not be marked as defined, so check those
681 // explicitly. If we know it's a variable, we have a definition for
682 // the purposes of this check.
683 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
684 // FIXME: We would really like to refer back to where the symbol was
685 // first referenced for a source location. We need to add something
686 // to track that. Currently, we just point to the end of the file.
688 getLexer().getLoc(), SourceMgr::DK_Error,
689 "assembler local symbol '" + Sym->getName() + "' not defined");
693 // Finalize the output stream if there are no errors and if the client wants
695 if (!HadError && !NoFinalize)
701 void AsmParser::checkForValidSection() {
702 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
703 TokError("expected section directive before assembly directive");
708 /// \brief Throw away the rest of the line for testing purposes.
709 void AsmParser::eatToEndOfStatement() {
710 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
714 if (Lexer.is(AsmToken::EndOfStatement))
718 StringRef AsmParser::parseStringToEndOfStatement() {
719 const char *Start = getTok().getLoc().getPointer();
721 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
724 const char *End = getTok().getLoc().getPointer();
725 return StringRef(Start, End - Start);
728 StringRef AsmParser::parseStringToComma() {
729 const char *Start = getTok().getLoc().getPointer();
731 while (Lexer.isNot(AsmToken::EndOfStatement) &&
732 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
735 const char *End = getTok().getLoc().getPointer();
736 return StringRef(Start, End - Start);
739 /// \brief Parse a paren expression and return it.
740 /// NOTE: This assumes the leading '(' has already been consumed.
742 /// parenexpr ::= expr)
744 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
745 if (parseExpression(Res))
747 if (Lexer.isNot(AsmToken::RParen))
748 return TokError("expected ')' in parentheses expression");
749 EndLoc = Lexer.getTok().getEndLoc();
754 /// \brief Parse a bracket expression and return it.
755 /// NOTE: This assumes the leading '[' has already been consumed.
757 /// bracketexpr ::= expr]
759 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
760 if (parseExpression(Res))
762 if (Lexer.isNot(AsmToken::RBrac))
763 return TokError("expected ']' in brackets expression");
764 EndLoc = Lexer.getTok().getEndLoc();
769 /// \brief Parse a primary expression and return it.
770 /// primaryexpr ::= (parenexpr
771 /// primaryexpr ::= symbol
772 /// primaryexpr ::= number
773 /// primaryexpr ::= '.'
774 /// primaryexpr ::= ~,+,- primaryexpr
775 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
776 SMLoc FirstTokenLoc = getLexer().getLoc();
777 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
778 switch (FirstTokenKind) {
780 return TokError("unknown token in expression");
781 // If we have an error assume that we've already handled it.
782 case AsmToken::Error:
784 case AsmToken::Exclaim:
785 Lex(); // Eat the operator.
786 if (parsePrimaryExpr(Res, EndLoc))
788 Res = MCUnaryExpr::CreateLNot(Res, getContext());
790 case AsmToken::Dollar:
792 case AsmToken::String:
793 case AsmToken::Identifier: {
794 StringRef Identifier;
795 if (parseIdentifier(Identifier)) {
796 if (FirstTokenKind == AsmToken::Dollar) {
797 if (Lexer.getMAI().getDollarIsPC()) {
798 // This is a '$' reference, which references the current PC. Emit a
799 // temporary label to the streamer and refer to it.
800 MCSymbol *Sym = Ctx.CreateTempSymbol();
802 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
804 EndLoc = FirstTokenLoc;
807 return Error(FirstTokenLoc, "invalid token in expression");
810 // Parse symbol variant
811 std::pair<StringRef, StringRef> Split;
812 if (!MAI.useParensForSymbolVariant()) {
813 if (FirstTokenKind == AsmToken::String) {
814 if (Lexer.is(AsmToken::At)) {
815 Lexer.Lex(); // eat @
816 SMLoc AtLoc = getLexer().getLoc();
818 if (parseIdentifier(VName))
819 return Error(AtLoc, "expected symbol variant after '@'");
821 Split = std::make_pair(Identifier, VName);
824 Split = Identifier.split('@');
826 } else if (Lexer.is(AsmToken::LParen)) {
827 Lexer.Lex(); // eat (
829 parseIdentifier(VName);
830 if (Lexer.isNot(AsmToken::RParen)) {
831 return Error(Lexer.getTok().getLoc(),
832 "unexpected token in variant, expected ')'");
834 Lexer.Lex(); // eat )
835 Split = std::make_pair(Identifier, VName);
838 EndLoc = SMLoc::getFromPointer(Identifier.end());
840 // This is a symbol reference.
841 StringRef SymbolName = Identifier;
842 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
844 // Lookup the symbol variant if used.
845 if (Split.second.size()) {
846 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
847 if (Variant != MCSymbolRefExpr::VK_Invalid) {
848 SymbolName = Split.first;
849 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
850 Variant = MCSymbolRefExpr::VK_None;
852 return Error(SMLoc::getFromPointer(Split.second.begin()),
853 "invalid variant '" + Split.second + "'");
857 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
859 // If this is an absolute variable reference, substitute it now to preserve
860 // semantics in the face of reassignment.
861 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
863 return Error(EndLoc, "unexpected modifier on variable reference");
865 Res = Sym->getVariableValue();
869 // Otherwise create a symbol ref.
870 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
873 case AsmToken::BigNum:
874 return TokError("literal value out of range for directive");
875 case AsmToken::Integer: {
876 SMLoc Loc = getTok().getLoc();
877 int64_t IntVal = getTok().getIntVal();
878 Res = MCConstantExpr::Create(IntVal, getContext());
879 EndLoc = Lexer.getTok().getEndLoc();
881 // Look for 'b' or 'f' following an Integer as a directional label
882 if (Lexer.getKind() == AsmToken::Identifier) {
883 StringRef IDVal = getTok().getString();
884 // Lookup the symbol variant if used.
885 std::pair<StringRef, StringRef> Split = IDVal.split('@');
886 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
887 if (Split.first.size() != IDVal.size()) {
888 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
889 if (Variant == MCSymbolRefExpr::VK_Invalid)
890 return TokError("invalid variant '" + Split.second + "'");
893 if (IDVal == "f" || IDVal == "b") {
895 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "b");
896 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
897 if (IDVal == "b" && Sym->isUndefined())
898 return Error(Loc, "invalid reference to undefined symbol");
899 EndLoc = Lexer.getTok().getEndLoc();
900 Lex(); // Eat identifier.
905 case AsmToken::Real: {
906 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
907 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
908 Res = MCConstantExpr::Create(IntVal, getContext());
909 EndLoc = Lexer.getTok().getEndLoc();
913 case AsmToken::Dot: {
914 // This is a '.' reference, which references the current PC. Emit a
915 // temporary label to the streamer and refer to it.
916 MCSymbol *Sym = Ctx.CreateTempSymbol();
918 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
919 EndLoc = Lexer.getTok().getEndLoc();
920 Lex(); // Eat identifier.
923 case AsmToken::LParen:
924 Lex(); // Eat the '('.
925 return parseParenExpr(Res, EndLoc);
926 case AsmToken::LBrac:
927 if (!PlatformParser->HasBracketExpressions())
928 return TokError("brackets expression not supported on this target");
929 Lex(); // Eat the '['.
930 return parseBracketExpr(Res, EndLoc);
931 case AsmToken::Minus:
932 Lex(); // Eat the operator.
933 if (parsePrimaryExpr(Res, EndLoc))
935 Res = MCUnaryExpr::CreateMinus(Res, getContext());
938 Lex(); // Eat the operator.
939 if (parsePrimaryExpr(Res, EndLoc))
941 Res = MCUnaryExpr::CreatePlus(Res, getContext());
943 case AsmToken::Tilde:
944 Lex(); // Eat the operator.
945 if (parsePrimaryExpr(Res, EndLoc))
947 Res = MCUnaryExpr::CreateNot(Res, getContext());
952 bool AsmParser::parseExpression(const MCExpr *&Res) {
954 return parseExpression(Res, EndLoc);
958 AsmParser::applyModifierToExpr(const MCExpr *E,
959 MCSymbolRefExpr::VariantKind Variant) {
960 // Ask the target implementation about this expression first.
961 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
964 // Recurse over the given expression, rebuilding it to apply the given variant
965 // if there is exactly one symbol.
966 switch (E->getKind()) {
968 case MCExpr::Constant:
971 case MCExpr::SymbolRef: {
972 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
974 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
975 TokError("invalid variant on expression '" + getTok().getIdentifier() +
976 "' (already modified)");
980 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
983 case MCExpr::Unary: {
984 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
985 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
988 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
991 case MCExpr::Binary: {
992 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
993 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
994 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1004 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
1008 llvm_unreachable("Invalid expression kind!");
1011 /// \brief Parse an expression and return it.
1013 /// expr ::= expr &&,|| expr -> lowest.
1014 /// expr ::= expr |,^,&,! expr
1015 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1016 /// expr ::= expr <<,>> expr
1017 /// expr ::= expr +,- expr
1018 /// expr ::= expr *,/,% expr -> highest.
1019 /// expr ::= primaryexpr
1021 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1022 // Parse the expression.
1024 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1027 // As a special case, we support 'a op b @ modifier' by rewriting the
1028 // expression to include the modifier. This is inefficient, but in general we
1029 // expect users to use 'a@modifier op b'.
1030 if (Lexer.getKind() == AsmToken::At) {
1033 if (Lexer.isNot(AsmToken::Identifier))
1034 return TokError("unexpected symbol modifier following '@'");
1036 MCSymbolRefExpr::VariantKind Variant =
1037 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1038 if (Variant == MCSymbolRefExpr::VK_Invalid)
1039 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1041 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1043 return TokError("invalid modifier '" + getTok().getIdentifier() +
1044 "' (no symbols present)");
1051 // Try to constant fold it up front, if possible.
1053 if (Res->EvaluateAsAbsolute(Value))
1054 Res = MCConstantExpr::Create(Value, getContext());
1059 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1061 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1064 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1067 SMLoc StartLoc = Lexer.getLoc();
1068 if (parseExpression(Expr))
1071 if (!Expr->EvaluateAsAbsolute(Res))
1072 return Error(StartLoc, "expected absolute expression");
1077 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1078 MCBinaryExpr::Opcode &Kind) {
1081 return 0; // not a binop.
1083 // Lowest Precedence: &&, ||
1084 case AsmToken::AmpAmp:
1085 Kind = MCBinaryExpr::LAnd;
1087 case AsmToken::PipePipe:
1088 Kind = MCBinaryExpr::LOr;
1091 // Low Precedence: |, &, ^
1093 // FIXME: gas seems to support '!' as an infix operator?
1094 case AsmToken::Pipe:
1095 Kind = MCBinaryExpr::Or;
1097 case AsmToken::Caret:
1098 Kind = MCBinaryExpr::Xor;
1101 Kind = MCBinaryExpr::And;
1104 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1105 case AsmToken::EqualEqual:
1106 Kind = MCBinaryExpr::EQ;
1108 case AsmToken::ExclaimEqual:
1109 case AsmToken::LessGreater:
1110 Kind = MCBinaryExpr::NE;
1112 case AsmToken::Less:
1113 Kind = MCBinaryExpr::LT;
1115 case AsmToken::LessEqual:
1116 Kind = MCBinaryExpr::LTE;
1118 case AsmToken::Greater:
1119 Kind = MCBinaryExpr::GT;
1121 case AsmToken::GreaterEqual:
1122 Kind = MCBinaryExpr::GTE;
1125 // Intermediate Precedence: <<, >>
1126 case AsmToken::LessLess:
1127 Kind = MCBinaryExpr::Shl;
1129 case AsmToken::GreaterGreater:
1130 Kind = MCBinaryExpr::Shr;
1133 // High Intermediate Precedence: +, -
1134 case AsmToken::Plus:
1135 Kind = MCBinaryExpr::Add;
1137 case AsmToken::Minus:
1138 Kind = MCBinaryExpr::Sub;
1141 // Highest Precedence: *, /, %
1142 case AsmToken::Star:
1143 Kind = MCBinaryExpr::Mul;
1145 case AsmToken::Slash:
1146 Kind = MCBinaryExpr::Div;
1148 case AsmToken::Percent:
1149 Kind = MCBinaryExpr::Mod;
1154 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1155 /// Res contains the LHS of the expression on input.
1156 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1159 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1160 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1162 // If the next token is lower precedence than we are allowed to eat, return
1163 // successfully with what we ate already.
1164 if (TokPrec < Precedence)
1169 // Eat the next primary expression.
1171 if (parsePrimaryExpr(RHS, EndLoc))
1174 // If BinOp binds less tightly with RHS than the operator after RHS, let
1175 // the pending operator take RHS as its LHS.
1176 MCBinaryExpr::Opcode Dummy;
1177 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1178 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1181 // Merge LHS and RHS according to operator.
1182 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1187 /// ::= EndOfStatement
1188 /// ::= Label* Directive ...Operands... EndOfStatement
1189 /// ::= Label* Identifier OperandList* EndOfStatement
1190 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1191 if (Lexer.is(AsmToken::EndOfStatement)) {
1197 // Statements always start with an identifier or are a full line comment.
1198 AsmToken ID = getTok();
1199 SMLoc IDLoc = ID.getLoc();
1201 int64_t LocalLabelVal = -1;
1202 // A full line comment is a '#' as the first token.
1203 if (Lexer.is(AsmToken::Hash))
1204 return parseCppHashLineFilenameComment(IDLoc);
1206 // Allow an integer followed by a ':' as a directional local label.
1207 if (Lexer.is(AsmToken::Integer)) {
1208 LocalLabelVal = getTok().getIntVal();
1209 if (LocalLabelVal < 0) {
1210 if (!TheCondState.Ignore)
1211 return TokError("unexpected token at start of statement");
1214 IDVal = getTok().getString();
1215 Lex(); // Consume the integer token to be used as an identifier token.
1216 if (Lexer.getKind() != AsmToken::Colon) {
1217 if (!TheCondState.Ignore)
1218 return TokError("unexpected token at start of statement");
1221 } else if (Lexer.is(AsmToken::Dot)) {
1222 // Treat '.' as a valid identifier in this context.
1225 } else if (parseIdentifier(IDVal)) {
1226 if (!TheCondState.Ignore)
1227 return TokError("unexpected token at start of statement");
1231 // Handle conditional assembly here before checking for skipping. We
1232 // have to do this so that .endif isn't skipped in a ".if 0" block for
1234 StringMap<DirectiveKind>::const_iterator DirKindIt =
1235 DirectiveKindMap.find(IDVal);
1236 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1238 : DirKindIt->getValue();
1249 return parseDirectiveIf(IDLoc, DirKind);
1251 return parseDirectiveIfb(IDLoc, true);
1253 return parseDirectiveIfb(IDLoc, false);
1255 return parseDirectiveIfc(IDLoc, true);
1257 return parseDirectiveIfeqs(IDLoc);
1259 return parseDirectiveIfc(IDLoc, false);
1261 return parseDirectiveIfdef(IDLoc, true);
1264 return parseDirectiveIfdef(IDLoc, false);
1266 return parseDirectiveElseIf(IDLoc);
1268 return parseDirectiveElse(IDLoc);
1270 return parseDirectiveEndIf(IDLoc);
1273 // Ignore the statement if in the middle of inactive conditional
1275 if (TheCondState.Ignore) {
1276 eatToEndOfStatement();
1280 // FIXME: Recurse on local labels?
1282 // See what kind of statement we have.
1283 switch (Lexer.getKind()) {
1284 case AsmToken::Colon: {
1285 checkForValidSection();
1287 // identifier ':' -> Label.
1290 // Diagnose attempt to use '.' as a label.
1292 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1294 // Diagnose attempt to use a variable as a label.
1296 // FIXME: Diagnostics. Note the location of the definition as a label.
1297 // FIXME: This doesn't diagnose assignment to a symbol which has been
1298 // implicitly marked as external.
1300 if (LocalLabelVal == -1)
1301 Sym = getContext().GetOrCreateSymbol(IDVal);
1303 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1304 if (!Sym->isUndefined() || Sym->isVariable())
1305 return Error(IDLoc, "invalid symbol redefinition");
1308 if (!ParsingInlineAsm)
1311 // If we are generating dwarf for assembly source files then gather the
1312 // info to make a dwarf label entry for this label if needed.
1313 if (getContext().getGenDwarfForAssembly())
1314 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1317 getTargetParser().onLabelParsed(Sym);
1319 // Consume any end of statement token, if present, to avoid spurious
1320 // AddBlankLine calls().
1321 if (Lexer.is(AsmToken::EndOfStatement)) {
1323 if (Lexer.is(AsmToken::Eof))
1330 case AsmToken::Equal:
1331 // identifier '=' ... -> assignment statement
1334 return parseAssignment(IDVal, true);
1336 default: // Normal instruction or directive.
1340 // If macros are enabled, check to see if this is a macro instantiation.
1341 if (areMacrosEnabled())
1342 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1343 return handleMacroEntry(M, IDLoc);
1346 // Otherwise, we have a normal instruction or directive.
1348 // Directives start with "."
1349 if (IDVal[0] == '.' && IDVal != ".") {
1350 // There are several entities interested in parsing directives:
1352 // 1. The target-specific assembly parser. Some directives are target
1353 // specific or may potentially behave differently on certain targets.
1354 // 2. Asm parser extensions. For example, platform-specific parsers
1355 // (like the ELF parser) register themselves as extensions.
1356 // 3. The generic directive parser implemented by this class. These are
1357 // all the directives that behave in a target and platform independent
1358 // manner, or at least have a default behavior that's shared between
1359 // all targets and platforms.
1361 // First query the target-specific parser. It will return 'true' if it
1362 // isn't interested in this directive.
1363 if (!getTargetParser().ParseDirective(ID))
1366 // Next, check the extension directive map to see if any extension has
1367 // registered itself to parse this directive.
1368 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1369 ExtensionDirectiveMap.lookup(IDVal);
1371 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1373 // Finally, if no one else is interested in this directive, it must be
1374 // generic and familiar to this class.
1380 return parseDirectiveSet(IDVal, true);
1382 return parseDirectiveSet(IDVal, false);
1384 return parseDirectiveAscii(IDVal, false);
1387 return parseDirectiveAscii(IDVal, true);
1389 return parseDirectiveValue(1);
1393 return parseDirectiveValue(2);
1397 return parseDirectiveValue(4);
1400 return parseDirectiveValue(8);
1402 return parseDirectiveOctaValue();
1405 return parseDirectiveRealValue(APFloat::IEEEsingle);
1407 return parseDirectiveRealValue(APFloat::IEEEdouble);
1409 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1410 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1413 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1414 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1417 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1419 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1421 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1423 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1425 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1427 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1429 return parseDirectiveOrg();
1431 return parseDirectiveFill();
1433 return parseDirectiveZero();
1435 eatToEndOfStatement(); // .extern is the default, ignore it.
1439 return parseDirectiveSymbolAttribute(MCSA_Global);
1440 case DK_LAZY_REFERENCE:
1441 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1442 case DK_NO_DEAD_STRIP:
1443 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1444 case DK_SYMBOL_RESOLVER:
1445 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1446 case DK_PRIVATE_EXTERN:
1447 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1449 return parseDirectiveSymbolAttribute(MCSA_Reference);
1450 case DK_WEAK_DEFINITION:
1451 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1452 case DK_WEAK_REFERENCE:
1453 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1454 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1455 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1458 return parseDirectiveComm(/*IsLocal=*/false);
1460 return parseDirectiveComm(/*IsLocal=*/true);
1462 return parseDirectiveAbort();
1464 return parseDirectiveInclude();
1466 return parseDirectiveIncbin();
1469 return TokError(Twine(IDVal) + " not supported yet");
1471 return parseDirectiveRept(IDLoc, IDVal);
1473 return parseDirectiveIrp(IDLoc);
1475 return parseDirectiveIrpc(IDLoc);
1477 return parseDirectiveEndr(IDLoc);
1478 case DK_BUNDLE_ALIGN_MODE:
1479 return parseDirectiveBundleAlignMode();
1480 case DK_BUNDLE_LOCK:
1481 return parseDirectiveBundleLock();
1482 case DK_BUNDLE_UNLOCK:
1483 return parseDirectiveBundleUnlock();
1485 return parseDirectiveLEB128(true);
1487 return parseDirectiveLEB128(false);
1490 return parseDirectiveSpace(IDVal);
1492 return parseDirectiveFile(IDLoc);
1494 return parseDirectiveLine();
1496 return parseDirectiveLoc();
1498 return parseDirectiveStabs();
1499 case DK_CFI_SECTIONS:
1500 return parseDirectiveCFISections();
1501 case DK_CFI_STARTPROC:
1502 return parseDirectiveCFIStartProc();
1503 case DK_CFI_ENDPROC:
1504 return parseDirectiveCFIEndProc();
1505 case DK_CFI_DEF_CFA:
1506 return parseDirectiveCFIDefCfa(IDLoc);
1507 case DK_CFI_DEF_CFA_OFFSET:
1508 return parseDirectiveCFIDefCfaOffset();
1509 case DK_CFI_ADJUST_CFA_OFFSET:
1510 return parseDirectiveCFIAdjustCfaOffset();
1511 case DK_CFI_DEF_CFA_REGISTER:
1512 return parseDirectiveCFIDefCfaRegister(IDLoc);
1514 return parseDirectiveCFIOffset(IDLoc);
1515 case DK_CFI_REL_OFFSET:
1516 return parseDirectiveCFIRelOffset(IDLoc);
1517 case DK_CFI_PERSONALITY:
1518 return parseDirectiveCFIPersonalityOrLsda(true);
1520 return parseDirectiveCFIPersonalityOrLsda(false);
1521 case DK_CFI_REMEMBER_STATE:
1522 return parseDirectiveCFIRememberState();
1523 case DK_CFI_RESTORE_STATE:
1524 return parseDirectiveCFIRestoreState();
1525 case DK_CFI_SAME_VALUE:
1526 return parseDirectiveCFISameValue(IDLoc);
1527 case DK_CFI_RESTORE:
1528 return parseDirectiveCFIRestore(IDLoc);
1530 return parseDirectiveCFIEscape();
1531 case DK_CFI_SIGNAL_FRAME:
1532 return parseDirectiveCFISignalFrame();
1533 case DK_CFI_UNDEFINED:
1534 return parseDirectiveCFIUndefined(IDLoc);
1535 case DK_CFI_REGISTER:
1536 return parseDirectiveCFIRegister(IDLoc);
1537 case DK_CFI_WINDOW_SAVE:
1538 return parseDirectiveCFIWindowSave();
1541 return parseDirectiveMacrosOnOff(IDVal);
1543 return parseDirectiveMacro(IDLoc);
1546 return parseDirectiveEndMacro(IDVal);
1548 return parseDirectivePurgeMacro(IDLoc);
1550 return parseDirectiveEnd(IDLoc);
1552 return parseDirectiveError(IDLoc, false);
1554 return parseDirectiveError(IDLoc, true);
1557 return Error(IDLoc, "unknown directive");
1560 // __asm _emit or __asm __emit
1561 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1562 IDVal == "_EMIT" || IDVal == "__EMIT"))
1563 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1566 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1567 return parseDirectiveMSAlign(IDLoc, Info);
1569 checkForValidSection();
1571 // Canonicalize the opcode to lower case.
1572 std::string OpcodeStr = IDVal.lower();
1573 ParseInstructionInfo IInfo(Info.AsmRewrites);
1574 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1575 Info.ParsedOperands);
1576 Info.ParseError = HadError;
1578 // Dump the parsed representation, if requested.
1579 if (getShowParsedOperands()) {
1580 SmallString<256> Str;
1581 raw_svector_ostream OS(Str);
1582 OS << "parsed instruction: [";
1583 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1586 Info.ParsedOperands[i]->print(OS);
1590 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1593 // If we are generating dwarf for the current section then generate a .loc
1594 // directive for the instruction.
1595 if (!HadError && getContext().getGenDwarfForAssembly() &&
1596 getContext().getGenDwarfSectionSyms().count(
1597 getStreamer().getCurrentSection().first)) {
1599 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1601 // If we previously parsed a cpp hash file line comment then make sure the
1602 // current Dwarf File is for the CppHashFilename if not then emit the
1603 // Dwarf File table for it and adjust the line number for the .loc.
1604 if (CppHashFilename.size() != 0) {
1605 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1606 0, StringRef(), CppHashFilename);
1607 getContext().setGenDwarfFileNumber(FileNumber);
1609 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1610 // cache with the different Loc from the call above we save the last
1611 // info we queried here with SrcMgr.FindLineNumber().
1612 unsigned CppHashLocLineNo;
1613 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1614 CppHashLocLineNo = LastQueryLine;
1616 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1617 LastQueryLine = CppHashLocLineNo;
1618 LastQueryIDLoc = CppHashLoc;
1619 LastQueryBuffer = CppHashBuf;
1621 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1624 getStreamer().EmitDwarfLocDirective(
1625 getContext().getGenDwarfFileNumber(), Line, 0,
1626 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1630 // If parsing succeeded, match the instruction.
1633 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1634 Info.ParsedOperands, Out,
1635 ErrorInfo, ParsingInlineAsm);
1638 // Don't skip the rest of the line, the instruction parser is responsible for
1643 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1644 /// since they may not be able to be tokenized to get to the end of line token.
1645 void AsmParser::eatToEndOfLine() {
1646 if (!Lexer.is(AsmToken::EndOfStatement))
1647 Lexer.LexUntilEndOfLine();
1652 /// parseCppHashLineFilenameComment as this:
1653 /// ::= # number "filename"
1654 /// or just as a full line comment if it doesn't have a number and a string.
1655 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1656 Lex(); // Eat the hash token.
1658 if (getLexer().isNot(AsmToken::Integer)) {
1659 // Consume the line since in cases it is not a well-formed line directive,
1660 // as if were simply a full line comment.
1665 int64_t LineNumber = getTok().getIntVal();
1668 if (getLexer().isNot(AsmToken::String)) {
1673 StringRef Filename = getTok().getString();
1674 // Get rid of the enclosing quotes.
1675 Filename = Filename.substr(1, Filename.size() - 2);
1677 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1679 CppHashFilename = Filename;
1680 CppHashLineNumber = LineNumber;
1681 CppHashBuf = CurBuffer;
1683 // Ignore any trailing characters, they're just comment.
1688 /// \brief will use the last parsed cpp hash line filename comment
1689 /// for the Filename and LineNo if any in the diagnostic.
1690 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1691 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1692 raw_ostream &OS = errs();
1694 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1695 const SMLoc &DiagLoc = Diag.getLoc();
1696 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1697 unsigned CppHashBuf =
1698 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1700 // Like SourceMgr::printMessage() we need to print the include stack if any
1701 // before printing the message.
1702 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1703 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1704 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
1705 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1706 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1709 // If we have not parsed a cpp hash line filename comment or the source
1710 // manager changed or buffer changed (like in a nested include) then just
1711 // print the normal diagnostic using its Filename and LineNo.
1712 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1713 DiagBuf != CppHashBuf) {
1714 if (Parser->SavedDiagHandler)
1715 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1717 Diag.print(nullptr, OS);
1721 // Use the CppHashFilename and calculate a line number based on the
1722 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1724 const std::string &Filename = Parser->CppHashFilename;
1726 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1727 int CppHashLocLineNo =
1728 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1730 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1732 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1733 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1734 Diag.getLineContents(), Diag.getRanges());
1736 if (Parser->SavedDiagHandler)
1737 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1739 NewDiag.print(nullptr, OS);
1742 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1743 // difference being that that function accepts '@' as part of identifiers and
1744 // we can't do that. AsmLexer.cpp should probably be changed to handle
1745 // '@' as a special case when needed.
1746 static bool isIdentifierChar(char c) {
1747 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1751 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1752 ArrayRef<MCAsmMacroParameter> Parameters,
1753 ArrayRef<MCAsmMacroArgument> A, const SMLoc &L) {
1754 unsigned NParameters = Parameters.size();
1755 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1756 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1757 return Error(L, "Wrong number of arguments");
1759 // A macro without parameters is handled differently on Darwin:
1760 // gas accepts no arguments and does no substitutions
1761 while (!Body.empty()) {
1762 // Scan for the next substitution.
1763 std::size_t End = Body.size(), Pos = 0;
1764 for (; Pos != End; ++Pos) {
1765 // Check for a substitution or escape.
1766 if (IsDarwin && !NParameters) {
1767 // This macro has no parameters, look for $0, $1, etc.
1768 if (Body[Pos] != '$' || Pos + 1 == End)
1771 char Next = Body[Pos + 1];
1772 if (Next == '$' || Next == 'n' ||
1773 isdigit(static_cast<unsigned char>(Next)))
1776 // This macro has parameters, look for \foo, \bar, etc.
1777 if (Body[Pos] == '\\' && Pos + 1 != End)
1783 OS << Body.slice(0, Pos);
1785 // Check if we reached the end.
1789 if (IsDarwin && !NParameters) {
1790 switch (Body[Pos + 1]) {
1796 // $n => number of arguments
1801 // $[0-9] => argument
1803 // Missing arguments are ignored.
1804 unsigned Index = Body[Pos + 1] - '0';
1805 if (Index >= A.size())
1808 // Otherwise substitute with the token values, with spaces eliminated.
1809 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1810 ie = A[Index].end();
1812 OS << it->getString();
1818 unsigned I = Pos + 1;
1819 while (isIdentifierChar(Body[I]) && I + 1 != End)
1822 const char *Begin = Body.data() + Pos + 1;
1823 StringRef Argument(Begin, I - (Pos + 1));
1825 for (; Index < NParameters; ++Index)
1826 if (Parameters[Index].Name == Argument)
1829 if (Index == NParameters) {
1830 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1833 OS << '\\' << Argument;
1837 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1838 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1839 ie = A[Index].end();
1841 // We expect no quotes around the string's contents when
1842 // parsing for varargs.
1843 if (it->getKind() != AsmToken::String || VarargParameter)
1844 OS << it->getString();
1846 OS << it->getStringContents();
1848 Pos += 1 + Argument.size();
1851 // Update the scan point.
1852 Body = Body.substr(Pos);
1858 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1859 SMLoc EL, MemoryBuffer *I)
1860 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1863 static bool isOperator(AsmToken::TokenKind kind) {
1867 case AsmToken::Plus:
1868 case AsmToken::Minus:
1869 case AsmToken::Tilde:
1870 case AsmToken::Slash:
1871 case AsmToken::Star:
1873 case AsmToken::Equal:
1874 case AsmToken::EqualEqual:
1875 case AsmToken::Pipe:
1876 case AsmToken::PipePipe:
1877 case AsmToken::Caret:
1879 case AsmToken::AmpAmp:
1880 case AsmToken::Exclaim:
1881 case AsmToken::ExclaimEqual:
1882 case AsmToken::Percent:
1883 case AsmToken::Less:
1884 case AsmToken::LessEqual:
1885 case AsmToken::LessLess:
1886 case AsmToken::LessGreater:
1887 case AsmToken::Greater:
1888 case AsmToken::GreaterEqual:
1889 case AsmToken::GreaterGreater:
1895 class AsmLexerSkipSpaceRAII {
1897 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1898 Lexer.setSkipSpace(SkipSpace);
1901 ~AsmLexerSkipSpaceRAII() {
1902 Lexer.setSkipSpace(true);
1910 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1913 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1914 StringRef Str = parseStringToEndOfStatement();
1915 MA.push_back(AsmToken(AsmToken::String, Str));
1920 unsigned ParenLevel = 0;
1921 unsigned AddTokens = 0;
1923 // Darwin doesn't use spaces to delmit arguments.
1924 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1927 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1928 return TokError("unexpected token in macro instantiation");
1930 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1933 if (Lexer.is(AsmToken::Space)) {
1934 Lex(); // Eat spaces
1936 // Spaces can delimit parameters, but could also be part an expression.
1937 // If the token after a space is an operator, add the token and the next
1938 // one into this argument
1940 if (isOperator(Lexer.getKind())) {
1941 // Check to see whether the token is used as an operator,
1942 // or part of an identifier
1943 const char *NextChar = getTok().getEndLoc().getPointer();
1944 if (*NextChar == ' ')
1948 if (!AddTokens && ParenLevel == 0) {
1954 // handleMacroEntry relies on not advancing the lexer here
1955 // to be able to fill in the remaining default parameter values
1956 if (Lexer.is(AsmToken::EndOfStatement))
1959 // Adjust the current parentheses level.
1960 if (Lexer.is(AsmToken::LParen))
1962 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1965 // Append the token to the current argument list.
1966 MA.push_back(getTok());
1972 if (ParenLevel != 0)
1973 return TokError("unbalanced parentheses in macro argument");
1977 // Parse the macro instantiation arguments.
1978 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1979 MCAsmMacroArguments &A) {
1980 const unsigned NParameters = M ? M->Parameters.size() : 0;
1981 bool NamedParametersFound = false;
1982 SmallVector<SMLoc, 4> FALocs;
1984 A.resize(NParameters);
1985 FALocs.resize(NParameters);
1987 // Parse two kinds of macro invocations:
1988 // - macros defined without any parameters accept an arbitrary number of them
1989 // - macros defined with parameters accept at most that many of them
1990 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
1991 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1993 SMLoc IDLoc = Lexer.getLoc();
1994 MCAsmMacroParameter FA;
1996 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
1997 if (parseIdentifier(FA.Name)) {
1998 Error(IDLoc, "invalid argument identifier for formal argument");
1999 eatToEndOfStatement();
2003 if (!Lexer.is(AsmToken::Equal)) {
2004 TokError("expected '=' after formal parameter identifier");
2005 eatToEndOfStatement();
2010 NamedParametersFound = true;
2013 if (NamedParametersFound && FA.Name.empty()) {
2014 Error(IDLoc, "cannot mix positional and keyword arguments");
2015 eatToEndOfStatement();
2019 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2020 if (parseMacroArgument(FA.Value, Vararg))
2023 unsigned PI = Parameter;
2024 if (!FA.Name.empty()) {
2026 for (FAI = 0; FAI < NParameters; ++FAI)
2027 if (M->Parameters[FAI].Name == FA.Name)
2030 if (FAI >= NParameters) {
2031 assert(M && "expected macro to be defined");
2033 "parameter named '" + FA.Name + "' does not exist for macro '" +
2040 if (!FA.Value.empty()) {
2045 if (FALocs.size() <= PI)
2046 FALocs.resize(PI + 1);
2048 FALocs[PI] = Lexer.getLoc();
2051 // At the end of the statement, fill in remaining arguments that have
2052 // default values. If there aren't any, then the next argument is
2053 // required but missing
2054 if (Lexer.is(AsmToken::EndOfStatement)) {
2055 bool Failure = false;
2056 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2057 if (A[FAI].empty()) {
2058 if (M->Parameters[FAI].Required) {
2059 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2060 "missing value for required parameter "
2061 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2065 if (!M->Parameters[FAI].Value.empty())
2066 A[FAI] = M->Parameters[FAI].Value;
2072 if (Lexer.is(AsmToken::Comma))
2076 return TokError("too many positional arguments");
2079 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2080 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2081 return (I == MacroMap.end()) ? nullptr : I->getValue();
2084 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
2085 MacroMap[Name] = new MCAsmMacro(Macro);
2088 void AsmParser::undefineMacro(StringRef Name) {
2089 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2090 if (I != MacroMap.end()) {
2091 delete I->getValue();
2096 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2097 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2098 // this, although we should protect against infinite loops.
2099 if (ActiveMacros.size() == 20)
2100 return TokError("macros cannot be nested more than 20 levels deep");
2102 MCAsmMacroArguments A;
2103 if (parseMacroArguments(M, A))
2106 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2107 // to hold the macro body with substitutions.
2108 SmallString<256> Buf;
2109 StringRef Body = M->Body;
2110 raw_svector_ostream OS(Buf);
2112 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2115 // We include the .endmacro in the buffer as our cue to exit the macro
2117 OS << ".endmacro\n";
2119 MemoryBuffer *Instantiation =
2120 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2122 // Create the macro instantiation object and add to the current macro
2123 // instantiation stack.
2124 MacroInstantiation *MI = new MacroInstantiation(
2125 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
2126 ActiveMacros.push_back(MI);
2128 // Jump to the macro instantiation and prime the lexer.
2129 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2130 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2136 void AsmParser::handleMacroExit() {
2137 // Jump to the EndOfStatement we should return to, and consume it.
2138 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2141 // Pop the instantiation entry.
2142 delete ActiveMacros.back();
2143 ActiveMacros.pop_back();
2146 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2147 switch (Value->getKind()) {
2148 case MCExpr::Binary: {
2149 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2150 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2152 case MCExpr::Target:
2153 case MCExpr::Constant:
2155 case MCExpr::SymbolRef: {
2157 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2159 return isUsedIn(Sym, S.getVariableValue());
2163 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2166 llvm_unreachable("Unknown expr kind!");
2169 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2171 // FIXME: Use better location, we should use proper tokens.
2172 SMLoc EqualLoc = Lexer.getLoc();
2174 const MCExpr *Value;
2175 if (parseExpression(Value))
2178 // Note: we don't count b as used in "a = b". This is to allow
2182 if (Lexer.isNot(AsmToken::EndOfStatement))
2183 return TokError("unexpected token in assignment");
2185 // Eat the end of statement marker.
2188 // Validate that the LHS is allowed to be a variable (either it has not been
2189 // used as a symbol, or it is an absolute symbol).
2190 MCSymbol *Sym = getContext().LookupSymbol(Name);
2192 // Diagnose assignment to a label.
2194 // FIXME: Diagnostics. Note the location of the definition as a label.
2195 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2196 if (isUsedIn(Sym, Value))
2197 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2198 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2199 ; // Allow redefinitions of undefined symbols only used in directives.
2200 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2201 ; // Allow redefinitions of variables that haven't yet been used.
2202 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2203 return Error(EqualLoc, "redefinition of '" + Name + "'");
2204 else if (!Sym->isVariable())
2205 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2206 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2207 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2210 // Don't count these checks as uses.
2211 Sym->setUsed(false);
2212 } else if (Name == ".") {
2213 if (Out.EmitValueToOffset(Value, 0)) {
2214 Error(EqualLoc, "expected absolute expression");
2215 eatToEndOfStatement();
2219 Sym = getContext().GetOrCreateSymbol(Name);
2221 // Do the assignment.
2222 Out.EmitAssignment(Sym, Value);
2224 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2229 /// parseIdentifier:
2232 bool AsmParser::parseIdentifier(StringRef &Res) {
2233 // The assembler has relaxed rules for accepting identifiers, in particular we
2234 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2235 // separate tokens. At this level, we have already lexed so we cannot (currently)
2236 // handle this as a context dependent token, instead we detect adjacent tokens
2237 // and return the combined identifier.
2238 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2239 SMLoc PrefixLoc = getLexer().getLoc();
2241 // Consume the prefix character, and check for a following identifier.
2243 if (Lexer.isNot(AsmToken::Identifier))
2246 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2247 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2250 // Construct the joined identifier and consume the token.
2252 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2257 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2260 Res = getTok().getIdentifier();
2262 Lex(); // Consume the identifier token.
2267 /// parseDirectiveSet:
2268 /// ::= .equ identifier ',' expression
2269 /// ::= .equiv identifier ',' expression
2270 /// ::= .set identifier ',' expression
2271 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2274 if (parseIdentifier(Name))
2275 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2277 if (getLexer().isNot(AsmToken::Comma))
2278 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2281 return parseAssignment(Name, allow_redef, true);
2284 bool AsmParser::parseEscapedString(std::string &Data) {
2285 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2288 StringRef Str = getTok().getStringContents();
2289 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2290 if (Str[i] != '\\') {
2295 // Recognize escaped characters. Note that this escape semantics currently
2296 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2299 return TokError("unexpected backslash at end of string");
2301 // Recognize octal sequences.
2302 if ((unsigned)(Str[i] - '0') <= 7) {
2303 // Consume up to three octal characters.
2304 unsigned Value = Str[i] - '0';
2306 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2308 Value = Value * 8 + (Str[i] - '0');
2310 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2312 Value = Value * 8 + (Str[i] - '0');
2317 return TokError("invalid octal escape sequence (out of range)");
2319 Data += (unsigned char)Value;
2323 // Otherwise recognize individual escapes.
2326 // Just reject invalid escape sequences for now.
2327 return TokError("invalid escape sequence (unrecognized character)");
2329 case 'b': Data += '\b'; break;
2330 case 'f': Data += '\f'; break;
2331 case 'n': Data += '\n'; break;
2332 case 'r': Data += '\r'; break;
2333 case 't': Data += '\t'; break;
2334 case '"': Data += '"'; break;
2335 case '\\': Data += '\\'; break;
2342 /// parseDirectiveAscii:
2343 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2344 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2345 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2346 checkForValidSection();
2349 if (getLexer().isNot(AsmToken::String))
2350 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2353 if (parseEscapedString(Data))
2356 getStreamer().EmitBytes(Data);
2358 getStreamer().EmitBytes(StringRef("\0", 1));
2362 if (getLexer().is(AsmToken::EndOfStatement))
2365 if (getLexer().isNot(AsmToken::Comma))
2366 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2375 /// parseDirectiveValue
2376 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2377 bool AsmParser::parseDirectiveValue(unsigned Size) {
2378 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2379 checkForValidSection();
2382 const MCExpr *Value;
2383 SMLoc ExprLoc = getLexer().getLoc();
2384 if (parseExpression(Value))
2387 // Special case constant expressions to match code generator.
2388 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2389 assert(Size <= 8 && "Invalid size");
2390 uint64_t IntValue = MCE->getValue();
2391 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2392 return Error(ExprLoc, "literal value out of range for directive");
2393 getStreamer().EmitIntValue(IntValue, Size);
2395 getStreamer().EmitValue(Value, Size, ExprLoc);
2397 if (getLexer().is(AsmToken::EndOfStatement))
2400 // FIXME: Improve diagnostic.
2401 if (getLexer().isNot(AsmToken::Comma))
2402 return TokError("unexpected token in directive");
2411 /// ParseDirectiveOctaValue
2412 /// ::= .octa [ hexconstant (, hexconstant)* ]
2413 bool AsmParser::parseDirectiveOctaValue() {
2414 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2415 checkForValidSection();
2418 if (Lexer.getKind() == AsmToken::Error)
2420 if (Lexer.getKind() != AsmToken::Integer &&
2421 Lexer.getKind() != AsmToken::BigNum)
2422 return TokError("unknown token in expression");
2424 SMLoc ExprLoc = getLexer().getLoc();
2425 APInt IntValue = getTok().getAPIntVal();
2429 if (IntValue.isIntN(64)) {
2431 lo = IntValue.getZExtValue();
2432 } else if (IntValue.isIntN(128)) {
2433 // It might actually have more than 128 bits, but the top ones are zero.
2434 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2435 lo = IntValue.getLoBits(64).getZExtValue();
2437 return Error(ExprLoc, "literal value out of range for directive");
2439 if (MAI.isLittleEndian()) {
2440 getStreamer().EmitIntValue(lo, 8);
2441 getStreamer().EmitIntValue(hi, 8);
2443 getStreamer().EmitIntValue(hi, 8);
2444 getStreamer().EmitIntValue(lo, 8);
2447 if (getLexer().is(AsmToken::EndOfStatement))
2450 // FIXME: Improve diagnostic.
2451 if (getLexer().isNot(AsmToken::Comma))
2452 return TokError("unexpected token in directive");
2461 /// parseDirectiveRealValue
2462 /// ::= (.single | .double) [ expression (, expression)* ]
2463 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2464 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2465 checkForValidSection();
2468 // We don't truly support arithmetic on floating point expressions, so we
2469 // have to manually parse unary prefixes.
2471 if (getLexer().is(AsmToken::Minus)) {
2474 } else if (getLexer().is(AsmToken::Plus))
2477 if (getLexer().isNot(AsmToken::Integer) &&
2478 getLexer().isNot(AsmToken::Real) &&
2479 getLexer().isNot(AsmToken::Identifier))
2480 return TokError("unexpected token in directive");
2482 // Convert to an APFloat.
2483 APFloat Value(Semantics);
2484 StringRef IDVal = getTok().getString();
2485 if (getLexer().is(AsmToken::Identifier)) {
2486 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2487 Value = APFloat::getInf(Semantics);
2488 else if (!IDVal.compare_lower("nan"))
2489 Value = APFloat::getNaN(Semantics, false, ~0);
2491 return TokError("invalid floating point literal");
2492 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2493 APFloat::opInvalidOp)
2494 return TokError("invalid floating point literal");
2498 // Consume the numeric token.
2501 // Emit the value as an integer.
2502 APInt AsInt = Value.bitcastToAPInt();
2503 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2504 AsInt.getBitWidth() / 8);
2506 if (getLexer().is(AsmToken::EndOfStatement))
2509 if (getLexer().isNot(AsmToken::Comma))
2510 return TokError("unexpected token in directive");
2519 /// parseDirectiveZero
2520 /// ::= .zero expression
2521 bool AsmParser::parseDirectiveZero() {
2522 checkForValidSection();
2525 if (parseAbsoluteExpression(NumBytes))
2529 if (getLexer().is(AsmToken::Comma)) {
2531 if (parseAbsoluteExpression(Val))
2535 if (getLexer().isNot(AsmToken::EndOfStatement))
2536 return TokError("unexpected token in '.zero' directive");
2540 getStreamer().EmitFill(NumBytes, Val);
2545 /// parseDirectiveFill
2546 /// ::= .fill expression [ , expression [ , expression ] ]
2547 bool AsmParser::parseDirectiveFill() {
2548 checkForValidSection();
2550 SMLoc RepeatLoc = getLexer().getLoc();
2552 if (parseAbsoluteExpression(NumValues))
2555 if (NumValues < 0) {
2557 "'.fill' directive with negative repeat count has no effect");
2561 int64_t FillSize = 1;
2562 int64_t FillExpr = 0;
2564 SMLoc SizeLoc, ExprLoc;
2565 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2566 if (getLexer().isNot(AsmToken::Comma))
2567 return TokError("unexpected token in '.fill' directive");
2570 SizeLoc = getLexer().getLoc();
2571 if (parseAbsoluteExpression(FillSize))
2574 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2575 if (getLexer().isNot(AsmToken::Comma))
2576 return TokError("unexpected token in '.fill' directive");
2579 ExprLoc = getLexer().getLoc();
2580 if (parseAbsoluteExpression(FillExpr))
2583 if (getLexer().isNot(AsmToken::EndOfStatement))
2584 return TokError("unexpected token in '.fill' directive");
2591 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2595 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2599 if (!isUInt<32>(FillExpr) && FillSize > 4)
2600 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2602 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2603 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2605 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2606 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2607 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2613 /// parseDirectiveOrg
2614 /// ::= .org expression [ , expression ]
2615 bool AsmParser::parseDirectiveOrg() {
2616 checkForValidSection();
2618 const MCExpr *Offset;
2619 SMLoc Loc = getTok().getLoc();
2620 if (parseExpression(Offset))
2623 // Parse optional fill expression.
2624 int64_t FillExpr = 0;
2625 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2626 if (getLexer().isNot(AsmToken::Comma))
2627 return TokError("unexpected token in '.org' directive");
2630 if (parseAbsoluteExpression(FillExpr))
2633 if (getLexer().isNot(AsmToken::EndOfStatement))
2634 return TokError("unexpected token in '.org' directive");
2639 // Only limited forms of relocatable expressions are accepted here, it
2640 // has to be relative to the current section. The streamer will return
2641 // 'true' if the expression wasn't evaluatable.
2642 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2643 return Error(Loc, "expected assembly-time absolute expression");
2648 /// parseDirectiveAlign
2649 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2650 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2651 checkForValidSection();
2653 SMLoc AlignmentLoc = getLexer().getLoc();
2655 if (parseAbsoluteExpression(Alignment))
2659 bool HasFillExpr = false;
2660 int64_t FillExpr = 0;
2661 int64_t MaxBytesToFill = 0;
2662 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2663 if (getLexer().isNot(AsmToken::Comma))
2664 return TokError("unexpected token in directive");
2667 // The fill expression can be omitted while specifying a maximum number of
2668 // alignment bytes, e.g:
2670 if (getLexer().isNot(AsmToken::Comma)) {
2672 if (parseAbsoluteExpression(FillExpr))
2676 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2677 if (getLexer().isNot(AsmToken::Comma))
2678 return TokError("unexpected token in directive");
2681 MaxBytesLoc = getLexer().getLoc();
2682 if (parseAbsoluteExpression(MaxBytesToFill))
2685 if (getLexer().isNot(AsmToken::EndOfStatement))
2686 return TokError("unexpected token in directive");
2695 // Compute alignment in bytes.
2697 // FIXME: Diagnose overflow.
2698 if (Alignment >= 32) {
2699 Error(AlignmentLoc, "invalid alignment value");
2703 Alignment = 1ULL << Alignment;
2705 // Reject alignments that aren't a power of two, for gas compatibility.
2706 if (!isPowerOf2_64(Alignment))
2707 Error(AlignmentLoc, "alignment must be a power of 2");
2710 // Diagnose non-sensical max bytes to align.
2711 if (MaxBytesLoc.isValid()) {
2712 if (MaxBytesToFill < 1) {
2713 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2714 "many bytes, ignoring maximum bytes expression");
2718 if (MaxBytesToFill >= Alignment) {
2719 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2725 // Check whether we should use optimal code alignment for this .align
2727 const MCSection *Section = getStreamer().getCurrentSection().first;
2728 assert(Section && "must have section to emit alignment");
2729 bool UseCodeAlign = Section->UseCodeAlign();
2730 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2731 ValueSize == 1 && UseCodeAlign) {
2732 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2734 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2735 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2742 /// parseDirectiveFile
2743 /// ::= .file [number] filename
2744 /// ::= .file number directory filename
2745 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2746 // FIXME: I'm not sure what this is.
2747 int64_t FileNumber = -1;
2748 SMLoc FileNumberLoc = getLexer().getLoc();
2749 if (getLexer().is(AsmToken::Integer)) {
2750 FileNumber = getTok().getIntVal();
2754 return TokError("file number less than one");
2757 if (getLexer().isNot(AsmToken::String))
2758 return TokError("unexpected token in '.file' directive");
2760 // Usually the directory and filename together, otherwise just the directory.
2761 // Allow the strings to have escaped octal character sequence.
2762 std::string Path = getTok().getString();
2763 if (parseEscapedString(Path))
2767 StringRef Directory;
2769 std::string FilenameData;
2770 if (getLexer().is(AsmToken::String)) {
2771 if (FileNumber == -1)
2772 return TokError("explicit path specified, but no file number");
2773 if (parseEscapedString(FilenameData))
2775 Filename = FilenameData;
2782 if (getLexer().isNot(AsmToken::EndOfStatement))
2783 return TokError("unexpected token in '.file' directive");
2785 if (FileNumber == -1)
2786 getStreamer().EmitFileDirective(Filename);
2788 if (getContext().getGenDwarfForAssembly() == true)
2790 "input can't have .file dwarf directives when -g is "
2791 "used to generate dwarf debug info for assembly code");
2793 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2795 Error(FileNumberLoc, "file number already allocated");
2801 /// parseDirectiveLine
2802 /// ::= .line [number]
2803 bool AsmParser::parseDirectiveLine() {
2804 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2805 if (getLexer().isNot(AsmToken::Integer))
2806 return TokError("unexpected token in '.line' directive");
2808 int64_t LineNumber = getTok().getIntVal();
2812 // FIXME: Do something with the .line.
2815 if (getLexer().isNot(AsmToken::EndOfStatement))
2816 return TokError("unexpected token in '.line' directive");
2821 /// parseDirectiveLoc
2822 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2823 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2824 /// The first number is a file number, must have been previously assigned with
2825 /// a .file directive, the second number is the line number and optionally the
2826 /// third number is a column position (zero if not specified). The remaining
2827 /// optional items are .loc sub-directives.
2828 bool AsmParser::parseDirectiveLoc() {
2829 if (getLexer().isNot(AsmToken::Integer))
2830 return TokError("unexpected token in '.loc' directive");
2831 int64_t FileNumber = getTok().getIntVal();
2833 return TokError("file number less than one in '.loc' directive");
2834 if (!getContext().isValidDwarfFileNumber(FileNumber))
2835 return TokError("unassigned file number in '.loc' directive");
2838 int64_t LineNumber = 0;
2839 if (getLexer().is(AsmToken::Integer)) {
2840 LineNumber = getTok().getIntVal();
2842 return TokError("line number less than zero in '.loc' directive");
2846 int64_t ColumnPos = 0;
2847 if (getLexer().is(AsmToken::Integer)) {
2848 ColumnPos = getTok().getIntVal();
2850 return TokError("column position less than zero in '.loc' directive");
2854 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2856 int64_t Discriminator = 0;
2857 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2859 if (getLexer().is(AsmToken::EndOfStatement))
2863 SMLoc Loc = getTok().getLoc();
2864 if (parseIdentifier(Name))
2865 return TokError("unexpected token in '.loc' directive");
2867 if (Name == "basic_block")
2868 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2869 else if (Name == "prologue_end")
2870 Flags |= DWARF2_FLAG_PROLOGUE_END;
2871 else if (Name == "epilogue_begin")
2872 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2873 else if (Name == "is_stmt") {
2874 Loc = getTok().getLoc();
2875 const MCExpr *Value;
2876 if (parseExpression(Value))
2878 // The expression must be the constant 0 or 1.
2879 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2880 int Value = MCE->getValue();
2882 Flags &= ~DWARF2_FLAG_IS_STMT;
2883 else if (Value == 1)
2884 Flags |= DWARF2_FLAG_IS_STMT;
2886 return Error(Loc, "is_stmt value not 0 or 1");
2888 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2890 } else if (Name == "isa") {
2891 Loc = getTok().getLoc();
2892 const MCExpr *Value;
2893 if (parseExpression(Value))
2895 // The expression must be a constant greater or equal to 0.
2896 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2897 int Value = MCE->getValue();
2899 return Error(Loc, "isa number less than zero");
2902 return Error(Loc, "isa number not a constant value");
2904 } else if (Name == "discriminator") {
2905 if (parseAbsoluteExpression(Discriminator))
2908 return Error(Loc, "unknown sub-directive in '.loc' directive");
2911 if (getLexer().is(AsmToken::EndOfStatement))
2916 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2917 Isa, Discriminator, StringRef());
2922 /// parseDirectiveStabs
2923 /// ::= .stabs string, number, number, number
2924 bool AsmParser::parseDirectiveStabs() {
2925 return TokError("unsupported directive '.stabs'");
2928 /// parseDirectiveCFISections
2929 /// ::= .cfi_sections section [, section]
2930 bool AsmParser::parseDirectiveCFISections() {
2935 if (parseIdentifier(Name))
2936 return TokError("Expected an identifier");
2938 if (Name == ".eh_frame")
2940 else if (Name == ".debug_frame")
2943 if (getLexer().is(AsmToken::Comma)) {
2946 if (parseIdentifier(Name))
2947 return TokError("Expected an identifier");
2949 if (Name == ".eh_frame")
2951 else if (Name == ".debug_frame")
2955 getStreamer().EmitCFISections(EH, Debug);
2959 /// parseDirectiveCFIStartProc
2960 /// ::= .cfi_startproc [simple]
2961 bool AsmParser::parseDirectiveCFIStartProc() {
2963 if (getLexer().isNot(AsmToken::EndOfStatement))
2964 if (parseIdentifier(Simple) || Simple != "simple")
2965 return TokError("unexpected token in .cfi_startproc directive");
2967 getStreamer().EmitCFIStartProc(!Simple.empty());
2971 /// parseDirectiveCFIEndProc
2972 /// ::= .cfi_endproc
2973 bool AsmParser::parseDirectiveCFIEndProc() {
2974 getStreamer().EmitCFIEndProc();
2978 /// \brief parse register name or number.
2979 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2980 SMLoc DirectiveLoc) {
2983 if (getLexer().isNot(AsmToken::Integer)) {
2984 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2986 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2988 return parseAbsoluteExpression(Register);
2993 /// parseDirectiveCFIDefCfa
2994 /// ::= .cfi_def_cfa register, offset
2995 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2996 int64_t Register = 0;
2997 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3000 if (getLexer().isNot(AsmToken::Comma))
3001 return TokError("unexpected token in directive");
3005 if (parseAbsoluteExpression(Offset))
3008 getStreamer().EmitCFIDefCfa(Register, Offset);
3012 /// parseDirectiveCFIDefCfaOffset
3013 /// ::= .cfi_def_cfa_offset offset
3014 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3016 if (parseAbsoluteExpression(Offset))
3019 getStreamer().EmitCFIDefCfaOffset(Offset);
3023 /// parseDirectiveCFIRegister
3024 /// ::= .cfi_register register, register
3025 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3026 int64_t Register1 = 0;
3027 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3030 if (getLexer().isNot(AsmToken::Comma))
3031 return TokError("unexpected token in directive");
3034 int64_t Register2 = 0;
3035 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3038 getStreamer().EmitCFIRegister(Register1, Register2);
3042 /// parseDirectiveCFIWindowSave
3043 /// ::= .cfi_window_save
3044 bool AsmParser::parseDirectiveCFIWindowSave() {
3045 getStreamer().EmitCFIWindowSave();
3049 /// parseDirectiveCFIAdjustCfaOffset
3050 /// ::= .cfi_adjust_cfa_offset adjustment
3051 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3052 int64_t Adjustment = 0;
3053 if (parseAbsoluteExpression(Adjustment))
3056 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3060 /// parseDirectiveCFIDefCfaRegister
3061 /// ::= .cfi_def_cfa_register register
3062 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3063 int64_t Register = 0;
3064 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3067 getStreamer().EmitCFIDefCfaRegister(Register);
3071 /// parseDirectiveCFIOffset
3072 /// ::= .cfi_offset register, offset
3073 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3074 int64_t Register = 0;
3077 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3080 if (getLexer().isNot(AsmToken::Comma))
3081 return TokError("unexpected token in directive");
3084 if (parseAbsoluteExpression(Offset))
3087 getStreamer().EmitCFIOffset(Register, Offset);
3091 /// parseDirectiveCFIRelOffset
3092 /// ::= .cfi_rel_offset register, offset
3093 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3094 int64_t Register = 0;
3096 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3099 if (getLexer().isNot(AsmToken::Comma))
3100 return TokError("unexpected token in directive");
3104 if (parseAbsoluteExpression(Offset))
3107 getStreamer().EmitCFIRelOffset(Register, Offset);
3111 static bool isValidEncoding(int64_t Encoding) {
3112 if (Encoding & ~0xff)
3115 if (Encoding == dwarf::DW_EH_PE_omit)
3118 const unsigned Format = Encoding & 0xf;
3119 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3120 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3121 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3122 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3125 const unsigned Application = Encoding & 0x70;
3126 if (Application != dwarf::DW_EH_PE_absptr &&
3127 Application != dwarf::DW_EH_PE_pcrel)
3133 /// parseDirectiveCFIPersonalityOrLsda
3134 /// IsPersonality true for cfi_personality, false for cfi_lsda
3135 /// ::= .cfi_personality encoding, [symbol_name]
3136 /// ::= .cfi_lsda encoding, [symbol_name]
3137 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3138 int64_t Encoding = 0;
3139 if (parseAbsoluteExpression(Encoding))
3141 if (Encoding == dwarf::DW_EH_PE_omit)
3144 if (!isValidEncoding(Encoding))
3145 return TokError("unsupported encoding.");
3147 if (getLexer().isNot(AsmToken::Comma))
3148 return TokError("unexpected token in directive");
3152 if (parseIdentifier(Name))
3153 return TokError("expected identifier in directive");
3155 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3158 getStreamer().EmitCFIPersonality(Sym, Encoding);
3160 getStreamer().EmitCFILsda(Sym, Encoding);
3164 /// parseDirectiveCFIRememberState
3165 /// ::= .cfi_remember_state
3166 bool AsmParser::parseDirectiveCFIRememberState() {
3167 getStreamer().EmitCFIRememberState();
3171 /// parseDirectiveCFIRestoreState
3172 /// ::= .cfi_remember_state
3173 bool AsmParser::parseDirectiveCFIRestoreState() {
3174 getStreamer().EmitCFIRestoreState();
3178 /// parseDirectiveCFISameValue
3179 /// ::= .cfi_same_value register
3180 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3181 int64_t Register = 0;
3183 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3186 getStreamer().EmitCFISameValue(Register);
3190 /// parseDirectiveCFIRestore
3191 /// ::= .cfi_restore register
3192 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3193 int64_t Register = 0;
3194 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3197 getStreamer().EmitCFIRestore(Register);
3201 /// parseDirectiveCFIEscape
3202 /// ::= .cfi_escape expression[,...]
3203 bool AsmParser::parseDirectiveCFIEscape() {
3206 if (parseAbsoluteExpression(CurrValue))
3209 Values.push_back((uint8_t)CurrValue);
3211 while (getLexer().is(AsmToken::Comma)) {
3214 if (parseAbsoluteExpression(CurrValue))
3217 Values.push_back((uint8_t)CurrValue);
3220 getStreamer().EmitCFIEscape(Values);
3224 /// parseDirectiveCFISignalFrame
3225 /// ::= .cfi_signal_frame
3226 bool AsmParser::parseDirectiveCFISignalFrame() {
3227 if (getLexer().isNot(AsmToken::EndOfStatement))
3228 return Error(getLexer().getLoc(),
3229 "unexpected token in '.cfi_signal_frame'");
3231 getStreamer().EmitCFISignalFrame();
3235 /// parseDirectiveCFIUndefined
3236 /// ::= .cfi_undefined register
3237 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3238 int64_t Register = 0;
3240 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3243 getStreamer().EmitCFIUndefined(Register);
3247 /// parseDirectiveMacrosOnOff
3250 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3251 if (getLexer().isNot(AsmToken::EndOfStatement))
3252 return Error(getLexer().getLoc(),
3253 "unexpected token in '" + Directive + "' directive");
3255 setMacrosEnabled(Directive == ".macros_on");
3259 /// parseDirectiveMacro
3260 /// ::= .macro name[,] [parameters]
3261 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3263 if (parseIdentifier(Name))
3264 return TokError("expected identifier in '.macro' directive");
3266 if (getLexer().is(AsmToken::Comma))
3269 MCAsmMacroParameters Parameters;
3270 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3272 if (Parameters.size() && Parameters.back().Vararg)
3273 return Error(Lexer.getLoc(),
3274 "Vararg parameter '" + Parameters.back().Name +
3275 "' should be last one in the list of parameters.");
3277 MCAsmMacroParameter Parameter;
3278 if (parseIdentifier(Parameter.Name))
3279 return TokError("expected identifier in '.macro' directive");
3281 if (Lexer.is(AsmToken::Colon)) {
3282 Lex(); // consume ':'
3285 StringRef Qualifier;
3287 QualLoc = Lexer.getLoc();
3288 if (parseIdentifier(Qualifier))
3289 return Error(QualLoc, "missing parameter qualifier for "
3290 "'" + Parameter.Name + "' in macro '" + Name + "'");
3292 if (Qualifier == "req")
3293 Parameter.Required = true;
3294 else if (Qualifier == "vararg" && !IsDarwin)
3295 Parameter.Vararg = true;
3297 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3298 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3301 if (getLexer().is(AsmToken::Equal)) {
3306 ParamLoc = Lexer.getLoc();
3307 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3310 if (Parameter.Required)
3311 Warning(ParamLoc, "pointless default value for required parameter "
3312 "'" + Parameter.Name + "' in macro '" + Name + "'");
3315 Parameters.push_back(Parameter);
3317 if (getLexer().is(AsmToken::Comma))
3321 // Eat the end of statement.
3324 AsmToken EndToken, StartToken = getTok();
3325 unsigned MacroDepth = 0;
3327 // Lex the macro definition.
3329 // Check whether we have reached the end of the file.
3330 if (getLexer().is(AsmToken::Eof))
3331 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3333 // Otherwise, check whether we have reach the .endmacro.
3334 if (getLexer().is(AsmToken::Identifier)) {
3335 if (getTok().getIdentifier() == ".endm" ||
3336 getTok().getIdentifier() == ".endmacro") {
3337 if (MacroDepth == 0) { // Outermost macro.
3338 EndToken = getTok();
3340 if (getLexer().isNot(AsmToken::EndOfStatement))
3341 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3345 // Otherwise we just found the end of an inner macro.
3348 } else if (getTok().getIdentifier() == ".macro") {
3349 // We allow nested macros. Those aren't instantiated until the outermost
3350 // macro is expanded so just ignore them for now.
3355 // Otherwise, scan til the end of the statement.
3356 eatToEndOfStatement();
3359 if (lookupMacro(Name)) {
3360 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3363 const char *BodyStart = StartToken.getLoc().getPointer();
3364 const char *BodyEnd = EndToken.getLoc().getPointer();
3365 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3366 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3367 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3371 /// checkForBadMacro
3373 /// With the support added for named parameters there may be code out there that
3374 /// is transitioning from positional parameters. In versions of gas that did
3375 /// not support named parameters they would be ignored on the macro definition.
3376 /// But to support both styles of parameters this is not possible so if a macro
3377 /// definition has named parameters but does not use them and has what appears
3378 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3379 /// warning that the positional parameter found in body which have no effect.
3380 /// Hoping the developer will either remove the named parameters from the macro
3381 /// definition so the positional parameters get used if that was what was
3382 /// intended or change the macro to use the named parameters. It is possible
3383 /// this warning will trigger when the none of the named parameters are used
3384 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3385 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3387 ArrayRef<MCAsmMacroParameter> Parameters) {
3388 // If this macro is not defined with named parameters the warning we are
3389 // checking for here doesn't apply.
3390 unsigned NParameters = Parameters.size();
3391 if (NParameters == 0)
3394 bool NamedParametersFound = false;
3395 bool PositionalParametersFound = false;
3397 // Look at the body of the macro for use of both the named parameters and what
3398 // are likely to be positional parameters. This is what expandMacro() is
3399 // doing when it finds the parameters in the body.
3400 while (!Body.empty()) {
3401 // Scan for the next possible parameter.
3402 std::size_t End = Body.size(), Pos = 0;
3403 for (; Pos != End; ++Pos) {
3404 // Check for a substitution or escape.
3405 // This macro is defined with parameters, look for \foo, \bar, etc.
3406 if (Body[Pos] == '\\' && Pos + 1 != End)
3409 // This macro should have parameters, but look for $0, $1, ..., $n too.
3410 if (Body[Pos] != '$' || Pos + 1 == End)
3412 char Next = Body[Pos + 1];
3413 if (Next == '$' || Next == 'n' ||
3414 isdigit(static_cast<unsigned char>(Next)))
3418 // Check if we reached the end.
3422 if (Body[Pos] == '$') {
3423 switch (Body[Pos + 1]) {
3428 // $n => number of arguments
3430 PositionalParametersFound = true;
3433 // $[0-9] => argument
3435 PositionalParametersFound = true;
3441 unsigned I = Pos + 1;
3442 while (isIdentifierChar(Body[I]) && I + 1 != End)
3445 const char *Begin = Body.data() + Pos + 1;
3446 StringRef Argument(Begin, I - (Pos + 1));
3448 for (; Index < NParameters; ++Index)
3449 if (Parameters[Index].Name == Argument)
3452 if (Index == NParameters) {
3453 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3459 NamedParametersFound = true;
3460 Pos += 1 + Argument.size();
3463 // Update the scan point.
3464 Body = Body.substr(Pos);
3467 if (!NamedParametersFound && PositionalParametersFound)
3468 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3469 "used in macro body, possible positional parameter "
3470 "found in body which will have no effect");
3473 /// parseDirectiveEndMacro
3476 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3477 if (getLexer().isNot(AsmToken::EndOfStatement))
3478 return TokError("unexpected token in '" + Directive + "' directive");
3480 // If we are inside a macro instantiation, terminate the current
3482 if (isInsideMacroInstantiation()) {
3487 // Otherwise, this .endmacro is a stray entry in the file; well formed
3488 // .endmacro directives are handled during the macro definition parsing.
3489 return TokError("unexpected '" + Directive + "' in file, "
3490 "no current macro definition");
3493 /// parseDirectivePurgeMacro
3495 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3497 if (parseIdentifier(Name))
3498 return TokError("expected identifier in '.purgem' directive");
3500 if (getLexer().isNot(AsmToken::EndOfStatement))
3501 return TokError("unexpected token in '.purgem' directive");
3503 if (!lookupMacro(Name))
3504 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3506 undefineMacro(Name);
3510 /// parseDirectiveBundleAlignMode
3511 /// ::= {.bundle_align_mode} expression
3512 bool AsmParser::parseDirectiveBundleAlignMode() {
3513 checkForValidSection();
3515 // Expect a single argument: an expression that evaluates to a constant
3516 // in the inclusive range 0-30.
3517 SMLoc ExprLoc = getLexer().getLoc();
3518 int64_t AlignSizePow2;
3519 if (parseAbsoluteExpression(AlignSizePow2))
3521 else if (getLexer().isNot(AsmToken::EndOfStatement))
3522 return TokError("unexpected token after expression in"
3523 " '.bundle_align_mode' directive");
3524 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3525 return Error(ExprLoc,
3526 "invalid bundle alignment size (expected between 0 and 30)");
3530 // Because of AlignSizePow2's verified range we can safely truncate it to
3532 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3536 /// parseDirectiveBundleLock
3537 /// ::= {.bundle_lock} [align_to_end]
3538 bool AsmParser::parseDirectiveBundleLock() {
3539 checkForValidSection();
3540 bool AlignToEnd = false;
3542 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3544 SMLoc Loc = getTok().getLoc();
3545 const char *kInvalidOptionError =
3546 "invalid option for '.bundle_lock' directive";
3548 if (parseIdentifier(Option))
3549 return Error(Loc, kInvalidOptionError);
3551 if (Option != "align_to_end")
3552 return Error(Loc, kInvalidOptionError);
3553 else if (getLexer().isNot(AsmToken::EndOfStatement))
3555 "unexpected token after '.bundle_lock' directive option");
3561 getStreamer().EmitBundleLock(AlignToEnd);
3565 /// parseDirectiveBundleLock
3566 /// ::= {.bundle_lock}
3567 bool AsmParser::parseDirectiveBundleUnlock() {
3568 checkForValidSection();
3570 if (getLexer().isNot(AsmToken::EndOfStatement))
3571 return TokError("unexpected token in '.bundle_unlock' directive");
3574 getStreamer().EmitBundleUnlock();
3578 /// parseDirectiveSpace
3579 /// ::= (.skip | .space) expression [ , expression ]
3580 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3581 checkForValidSection();
3584 if (parseAbsoluteExpression(NumBytes))
3587 int64_t FillExpr = 0;
3588 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3589 if (getLexer().isNot(AsmToken::Comma))
3590 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3593 if (parseAbsoluteExpression(FillExpr))
3596 if (getLexer().isNot(AsmToken::EndOfStatement))
3597 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3603 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3606 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3607 getStreamer().EmitFill(NumBytes, FillExpr);
3612 /// parseDirectiveLEB128
3613 /// ::= (.sleb128 | .uleb128) expression
3614 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3615 checkForValidSection();
3616 const MCExpr *Value;
3618 if (parseExpression(Value))
3621 if (getLexer().isNot(AsmToken::EndOfStatement))
3622 return TokError("unexpected token in directive");
3625 getStreamer().EmitSLEB128Value(Value);
3627 getStreamer().EmitULEB128Value(Value);
3632 /// parseDirectiveSymbolAttribute
3633 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3634 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3635 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3638 SMLoc Loc = getTok().getLoc();
3640 if (parseIdentifier(Name))
3641 return Error(Loc, "expected identifier in directive");
3643 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3645 // Assembler local symbols don't make any sense here. Complain loudly.
3646 if (Sym->isTemporary())
3647 return Error(Loc, "non-local symbol required in directive");
3649 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3650 return Error(Loc, "unable to emit symbol attribute");
3652 if (getLexer().is(AsmToken::EndOfStatement))
3655 if (getLexer().isNot(AsmToken::Comma))
3656 return TokError("unexpected token in directive");
3665 /// parseDirectiveComm
3666 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3667 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3668 checkForValidSection();
3670 SMLoc IDLoc = getLexer().getLoc();
3672 if (parseIdentifier(Name))
3673 return TokError("expected identifier in directive");
3675 // Handle the identifier as the key symbol.
3676 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3678 if (getLexer().isNot(AsmToken::Comma))
3679 return TokError("unexpected token in directive");
3683 SMLoc SizeLoc = getLexer().getLoc();
3684 if (parseAbsoluteExpression(Size))
3687 int64_t Pow2Alignment = 0;
3688 SMLoc Pow2AlignmentLoc;
3689 if (getLexer().is(AsmToken::Comma)) {
3691 Pow2AlignmentLoc = getLexer().getLoc();
3692 if (parseAbsoluteExpression(Pow2Alignment))
3695 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3696 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3697 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3699 // If this target takes alignments in bytes (not log) validate and convert.
3700 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3701 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3702 if (!isPowerOf2_64(Pow2Alignment))
3703 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3704 Pow2Alignment = Log2_64(Pow2Alignment);
3708 if (getLexer().isNot(AsmToken::EndOfStatement))
3709 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3713 // NOTE: a size of zero for a .comm should create a undefined symbol
3714 // but a size of .lcomm creates a bss symbol of size zero.
3716 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3717 "be less than zero");
3719 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3720 // may internally end up wanting an alignment in bytes.
3721 // FIXME: Diagnose overflow.
3722 if (Pow2Alignment < 0)
3723 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3724 "alignment, can't be less than zero");
3726 if (!Sym->isUndefined())
3727 return Error(IDLoc, "invalid symbol redefinition");
3729 // Create the Symbol as a common or local common with Size and Pow2Alignment
3731 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3735 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3739 /// parseDirectiveAbort
3740 /// ::= .abort [... message ...]
3741 bool AsmParser::parseDirectiveAbort() {
3742 // FIXME: Use loc from directive.
3743 SMLoc Loc = getLexer().getLoc();
3745 StringRef Str = parseStringToEndOfStatement();
3746 if (getLexer().isNot(AsmToken::EndOfStatement))
3747 return TokError("unexpected token in '.abort' directive");
3752 Error(Loc, ".abort detected. Assembly stopping.");
3754 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3755 // FIXME: Actually abort assembly here.
3760 /// parseDirectiveInclude
3761 /// ::= .include "filename"
3762 bool AsmParser::parseDirectiveInclude() {
3763 if (getLexer().isNot(AsmToken::String))
3764 return TokError("expected string in '.include' directive");
3766 // Allow the strings to have escaped octal character sequence.
3767 std::string Filename;
3768 if (parseEscapedString(Filename))
3770 SMLoc IncludeLoc = getLexer().getLoc();
3773 if (getLexer().isNot(AsmToken::EndOfStatement))
3774 return TokError("unexpected token in '.include' directive");
3776 // Attempt to switch the lexer to the included file before consuming the end
3777 // of statement to avoid losing it when we switch.
3778 if (enterIncludeFile(Filename)) {
3779 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3786 /// parseDirectiveIncbin
3787 /// ::= .incbin "filename"
3788 bool AsmParser::parseDirectiveIncbin() {
3789 if (getLexer().isNot(AsmToken::String))
3790 return TokError("expected string in '.incbin' directive");
3792 // Allow the strings to have escaped octal character sequence.
3793 std::string Filename;
3794 if (parseEscapedString(Filename))
3796 SMLoc IncbinLoc = getLexer().getLoc();
3799 if (getLexer().isNot(AsmToken::EndOfStatement))
3800 return TokError("unexpected token in '.incbin' directive");
3802 // Attempt to process the included file.
3803 if (processIncbinFile(Filename)) {
3804 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3811 /// parseDirectiveIf
3812 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
3813 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
3814 TheCondStack.push_back(TheCondState);
3815 TheCondState.TheCond = AsmCond::IfCond;
3816 if (TheCondState.Ignore) {
3817 eatToEndOfStatement();
3820 if (parseAbsoluteExpression(ExprValue))
3823 if (getLexer().isNot(AsmToken::EndOfStatement))
3824 return TokError("unexpected token in '.if' directive");
3830 llvm_unreachable("unsupported directive");
3835 ExprValue = ExprValue == 0;
3838 ExprValue = ExprValue >= 0;
3841 ExprValue = ExprValue > 0;
3844 ExprValue = ExprValue <= 0;
3847 ExprValue = ExprValue < 0;
3851 TheCondState.CondMet = ExprValue;
3852 TheCondState.Ignore = !TheCondState.CondMet;
3858 /// parseDirectiveIfb
3860 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3861 TheCondStack.push_back(TheCondState);
3862 TheCondState.TheCond = AsmCond::IfCond;
3864 if (TheCondState.Ignore) {
3865 eatToEndOfStatement();
3867 StringRef Str = parseStringToEndOfStatement();
3869 if (getLexer().isNot(AsmToken::EndOfStatement))
3870 return TokError("unexpected token in '.ifb' directive");
3874 TheCondState.CondMet = ExpectBlank == Str.empty();
3875 TheCondState.Ignore = !TheCondState.CondMet;
3881 /// parseDirectiveIfc
3882 /// ::= .ifc string1, string2
3883 /// ::= .ifnc string1, string2
3884 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3885 TheCondStack.push_back(TheCondState);
3886 TheCondState.TheCond = AsmCond::IfCond;
3888 if (TheCondState.Ignore) {
3889 eatToEndOfStatement();
3891 StringRef Str1 = parseStringToComma();
3893 if (getLexer().isNot(AsmToken::Comma))
3894 return TokError("unexpected token in '.ifc' directive");
3898 StringRef Str2 = parseStringToEndOfStatement();
3900 if (getLexer().isNot(AsmToken::EndOfStatement))
3901 return TokError("unexpected token in '.ifc' directive");
3905 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3906 TheCondState.Ignore = !TheCondState.CondMet;
3912 /// parseDirectiveIfeqs
3913 /// ::= .ifeqs string1, string2
3914 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc) {
3915 if (Lexer.isNot(AsmToken::String)) {
3916 TokError("expected string parameter for '.ifeqs' directive");
3917 eatToEndOfStatement();
3921 StringRef String1 = getTok().getStringContents();
3924 if (Lexer.isNot(AsmToken::Comma)) {
3925 TokError("expected comma after first string for '.ifeqs' directive");
3926 eatToEndOfStatement();
3932 if (Lexer.isNot(AsmToken::String)) {
3933 TokError("expected string parameter for '.ifeqs' directive");
3934 eatToEndOfStatement();
3938 StringRef String2 = getTok().getStringContents();
3941 TheCondStack.push_back(TheCondState);
3942 TheCondState.TheCond = AsmCond::IfCond;
3943 TheCondState.CondMet = String1 == String2;
3944 TheCondState.Ignore = !TheCondState.CondMet;
3949 /// parseDirectiveIfdef
3950 /// ::= .ifdef symbol
3951 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3953 TheCondStack.push_back(TheCondState);
3954 TheCondState.TheCond = AsmCond::IfCond;
3956 if (TheCondState.Ignore) {
3957 eatToEndOfStatement();
3959 if (parseIdentifier(Name))
3960 return TokError("expected identifier after '.ifdef'");
3964 MCSymbol *Sym = getContext().LookupSymbol(Name);
3967 TheCondState.CondMet = (Sym && !Sym->isUndefined());
3969 TheCondState.CondMet = (!Sym || Sym->isUndefined());
3970 TheCondState.Ignore = !TheCondState.CondMet;
3976 /// parseDirectiveElseIf
3977 /// ::= .elseif expression
3978 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3979 if (TheCondState.TheCond != AsmCond::IfCond &&
3980 TheCondState.TheCond != AsmCond::ElseIfCond)
3981 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3983 TheCondState.TheCond = AsmCond::ElseIfCond;
3985 bool LastIgnoreState = false;
3986 if (!TheCondStack.empty())
3987 LastIgnoreState = TheCondStack.back().Ignore;
3988 if (LastIgnoreState || TheCondState.CondMet) {
3989 TheCondState.Ignore = true;
3990 eatToEndOfStatement();
3993 if (parseAbsoluteExpression(ExprValue))
3996 if (getLexer().isNot(AsmToken::EndOfStatement))
3997 return TokError("unexpected token in '.elseif' directive");
4000 TheCondState.CondMet = ExprValue;
4001 TheCondState.Ignore = !TheCondState.CondMet;
4007 /// parseDirectiveElse
4009 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4010 if (getLexer().isNot(AsmToken::EndOfStatement))
4011 return TokError("unexpected token in '.else' directive");
4015 if (TheCondState.TheCond != AsmCond::IfCond &&
4016 TheCondState.TheCond != AsmCond::ElseIfCond)
4017 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4019 TheCondState.TheCond = AsmCond::ElseCond;
4020 bool LastIgnoreState = false;
4021 if (!TheCondStack.empty())
4022 LastIgnoreState = TheCondStack.back().Ignore;
4023 if (LastIgnoreState || TheCondState.CondMet)
4024 TheCondState.Ignore = true;
4026 TheCondState.Ignore = false;
4031 /// parseDirectiveEnd
4033 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4034 if (getLexer().isNot(AsmToken::EndOfStatement))
4035 return TokError("unexpected token in '.end' directive");
4039 while (Lexer.isNot(AsmToken::Eof))
4045 /// parseDirectiveError
4047 /// ::= .error [string]
4048 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4049 if (!TheCondStack.empty()) {
4050 if (TheCondStack.back().Ignore) {
4051 eatToEndOfStatement();
4057 return Error(L, ".err encountered");
4059 StringRef Message = ".error directive invoked in source file";
4060 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4061 if (Lexer.isNot(AsmToken::String)) {
4062 TokError(".error argument must be a string");
4063 eatToEndOfStatement();
4067 Message = getTok().getStringContents();
4075 /// parseDirectiveEndIf
4077 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4078 if (getLexer().isNot(AsmToken::EndOfStatement))
4079 return TokError("unexpected token in '.endif' directive");
4083 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4084 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4086 if (!TheCondStack.empty()) {
4087 TheCondState = TheCondStack.back();
4088 TheCondStack.pop_back();
4094 void AsmParser::initializeDirectiveKindMap() {
4095 DirectiveKindMap[".set"] = DK_SET;
4096 DirectiveKindMap[".equ"] = DK_EQU;
4097 DirectiveKindMap[".equiv"] = DK_EQUIV;
4098 DirectiveKindMap[".ascii"] = DK_ASCII;
4099 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4100 DirectiveKindMap[".string"] = DK_STRING;
4101 DirectiveKindMap[".byte"] = DK_BYTE;
4102 DirectiveKindMap[".short"] = DK_SHORT;
4103 DirectiveKindMap[".value"] = DK_VALUE;
4104 DirectiveKindMap[".2byte"] = DK_2BYTE;
4105 DirectiveKindMap[".long"] = DK_LONG;
4106 DirectiveKindMap[".int"] = DK_INT;
4107 DirectiveKindMap[".4byte"] = DK_4BYTE;
4108 DirectiveKindMap[".quad"] = DK_QUAD;
4109 DirectiveKindMap[".8byte"] = DK_8BYTE;
4110 DirectiveKindMap[".octa"] = DK_OCTA;
4111 DirectiveKindMap[".single"] = DK_SINGLE;
4112 DirectiveKindMap[".float"] = DK_FLOAT;
4113 DirectiveKindMap[".double"] = DK_DOUBLE;
4114 DirectiveKindMap[".align"] = DK_ALIGN;
4115 DirectiveKindMap[".align32"] = DK_ALIGN32;
4116 DirectiveKindMap[".balign"] = DK_BALIGN;
4117 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4118 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4119 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4120 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4121 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4122 DirectiveKindMap[".org"] = DK_ORG;
4123 DirectiveKindMap[".fill"] = DK_FILL;
4124 DirectiveKindMap[".zero"] = DK_ZERO;
4125 DirectiveKindMap[".extern"] = DK_EXTERN;
4126 DirectiveKindMap[".globl"] = DK_GLOBL;
4127 DirectiveKindMap[".global"] = DK_GLOBAL;
4128 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4129 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4130 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4131 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4132 DirectiveKindMap[".reference"] = DK_REFERENCE;
4133 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4134 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4135 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4136 DirectiveKindMap[".comm"] = DK_COMM;
4137 DirectiveKindMap[".common"] = DK_COMMON;
4138 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4139 DirectiveKindMap[".abort"] = DK_ABORT;
4140 DirectiveKindMap[".include"] = DK_INCLUDE;
4141 DirectiveKindMap[".incbin"] = DK_INCBIN;
4142 DirectiveKindMap[".code16"] = DK_CODE16;
4143 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4144 DirectiveKindMap[".rept"] = DK_REPT;
4145 DirectiveKindMap[".rep"] = DK_REPT;
4146 DirectiveKindMap[".irp"] = DK_IRP;
4147 DirectiveKindMap[".irpc"] = DK_IRPC;
4148 DirectiveKindMap[".endr"] = DK_ENDR;
4149 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4150 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4151 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4152 DirectiveKindMap[".if"] = DK_IF;
4153 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4154 DirectiveKindMap[".ifge"] = DK_IFGE;
4155 DirectiveKindMap[".ifgt"] = DK_IFGT;
4156 DirectiveKindMap[".ifle"] = DK_IFLE;
4157 DirectiveKindMap[".iflt"] = DK_IFLT;
4158 DirectiveKindMap[".ifne"] = DK_IFNE;
4159 DirectiveKindMap[".ifb"] = DK_IFB;
4160 DirectiveKindMap[".ifnb"] = DK_IFNB;
4161 DirectiveKindMap[".ifc"] = DK_IFC;
4162 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4163 DirectiveKindMap[".ifnc"] = DK_IFNC;
4164 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4165 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4166 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4167 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4168 DirectiveKindMap[".else"] = DK_ELSE;
4169 DirectiveKindMap[".end"] = DK_END;
4170 DirectiveKindMap[".endif"] = DK_ENDIF;
4171 DirectiveKindMap[".skip"] = DK_SKIP;
4172 DirectiveKindMap[".space"] = DK_SPACE;
4173 DirectiveKindMap[".file"] = DK_FILE;
4174 DirectiveKindMap[".line"] = DK_LINE;
4175 DirectiveKindMap[".loc"] = DK_LOC;
4176 DirectiveKindMap[".stabs"] = DK_STABS;
4177 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4178 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4179 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4180 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4181 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4182 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4183 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4184 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4185 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4186 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4187 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4188 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4189 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4190 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4191 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4192 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4193 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4194 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4195 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4196 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4197 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4198 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4199 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4200 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4201 DirectiveKindMap[".macro"] = DK_MACRO;
4202 DirectiveKindMap[".endm"] = DK_ENDM;
4203 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4204 DirectiveKindMap[".purgem"] = DK_PURGEM;
4205 DirectiveKindMap[".err"] = DK_ERR;
4206 DirectiveKindMap[".error"] = DK_ERROR;
4209 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4210 AsmToken EndToken, StartToken = getTok();
4212 unsigned NestLevel = 0;
4214 // Check whether we have reached the end of the file.
4215 if (getLexer().is(AsmToken::Eof)) {
4216 Error(DirectiveLoc, "no matching '.endr' in definition");
4220 if (Lexer.is(AsmToken::Identifier) &&
4221 (getTok().getIdentifier() == ".rept")) {
4225 // Otherwise, check whether we have reached the .endr.
4226 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4227 if (NestLevel == 0) {
4228 EndToken = getTok();
4230 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4231 TokError("unexpected token in '.endr' directive");
4239 // Otherwise, scan till the end of the statement.
4240 eatToEndOfStatement();
4243 const char *BodyStart = StartToken.getLoc().getPointer();
4244 const char *BodyEnd = EndToken.getLoc().getPointer();
4245 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4247 // We Are Anonymous.
4248 MacroLikeBodies.push_back(MCAsmMacro(StringRef(), Body, None));
4249 return &MacroLikeBodies.back();
4252 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4253 raw_svector_ostream &OS) {
4256 MemoryBuffer *Instantiation =
4257 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4259 // Create the macro instantiation object and add to the current macro
4260 // instantiation stack.
4261 MacroInstantiation *MI = new MacroInstantiation(
4262 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
4263 ActiveMacros.push_back(MI);
4265 // Jump to the macro instantiation and prime the lexer.
4266 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
4267 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
4271 /// parseDirectiveRept
4272 /// ::= .rep | .rept count
4273 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4274 const MCExpr *CountExpr;
4275 SMLoc CountLoc = getTok().getLoc();
4276 if (parseExpression(CountExpr))
4280 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4281 eatToEndOfStatement();
4282 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4286 return Error(CountLoc, "Count is negative");
4288 if (Lexer.isNot(AsmToken::EndOfStatement))
4289 return TokError("unexpected token in '" + Dir + "' directive");
4291 // Eat the end of statement.
4294 // Lex the rept 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 if (expandMacro(OS, M->Body, None, None, getTok().getLoc()))
4307 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4312 /// parseDirectiveIrp
4313 /// ::= .irp symbol,values
4314 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4315 MCAsmMacroParameter Parameter;
4317 if (parseIdentifier(Parameter.Name))
4318 return TokError("expected identifier in '.irp' directive");
4320 if (Lexer.isNot(AsmToken::Comma))
4321 return TokError("expected comma in '.irp' directive");
4325 MCAsmMacroArguments A;
4326 if (parseMacroArguments(nullptr, A))
4329 // Eat the end of statement.
4332 // Lex the irp definition.
4333 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4337 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4338 // to hold the macro body with substitutions.
4339 SmallString<256> Buf;
4340 raw_svector_ostream OS(Buf);
4342 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4343 if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc()))
4347 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4352 /// parseDirectiveIrpc
4353 /// ::= .irpc symbol,values
4354 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4355 MCAsmMacroParameter Parameter;
4357 if (parseIdentifier(Parameter.Name))
4358 return TokError("expected identifier in '.irpc' directive");
4360 if (Lexer.isNot(AsmToken::Comma))
4361 return TokError("expected comma in '.irpc' directive");
4365 MCAsmMacroArguments A;
4366 if (parseMacroArguments(nullptr, A))
4369 if (A.size() != 1 || A.front().size() != 1)
4370 return TokError("unexpected token in '.irpc' directive");
4372 // Eat the end of statement.
4375 // Lex the irpc definition.
4376 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4380 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4381 // to hold the macro body with substitutions.
4382 SmallString<256> Buf;
4383 raw_svector_ostream OS(Buf);
4385 StringRef Values = A.front().front().getString();
4386 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4387 MCAsmMacroArgument Arg;
4388 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4390 if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc()))
4394 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4399 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4400 if (ActiveMacros.empty())
4401 return TokError("unmatched '.endr' directive");
4403 // The only .repl that should get here are the ones created by
4404 // instantiateMacroLikeBody.
4405 assert(getLexer().is(AsmToken::EndOfStatement));
4411 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4413 const MCExpr *Value;
4414 SMLoc ExprLoc = getLexer().getLoc();
4415 if (parseExpression(Value))
4417 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4419 return Error(ExprLoc, "unexpected expression in _emit");
4420 uint64_t IntValue = MCE->getValue();
4421 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4422 return Error(ExprLoc, "literal value out of range for directive");
4424 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4428 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4429 const MCExpr *Value;
4430 SMLoc ExprLoc = getLexer().getLoc();
4431 if (parseExpression(Value))
4433 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4435 return Error(ExprLoc, "unexpected expression in align");
4436 uint64_t IntValue = MCE->getValue();
4437 if (!isPowerOf2_64(IntValue))
4438 return Error(ExprLoc, "literal value not a power of two greater then zero");
4440 Info.AsmRewrites->push_back(
4441 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4445 // We are comparing pointers, but the pointers are relative to a single string.
4446 // Thus, this should always be deterministic.
4447 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4448 const AsmRewrite *AsmRewriteB) {
4449 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4451 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4454 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4455 // rewrite to the same location. Make sure the SizeDirective rewrite is
4456 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4457 // ensures the sort algorithm is stable.
4458 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4459 AsmRewritePrecedence[AsmRewriteB->Kind])
4462 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4463 AsmRewritePrecedence[AsmRewriteB->Kind])
4465 llvm_unreachable("Unstable rewrite sort.");
4468 bool AsmParser::parseMSInlineAsm(
4469 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4470 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4471 SmallVectorImpl<std::string> &Constraints,
4472 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4473 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4474 SmallVector<void *, 4> InputDecls;
4475 SmallVector<void *, 4> OutputDecls;
4476 SmallVector<bool, 4> InputDeclsAddressOf;
4477 SmallVector<bool, 4> OutputDeclsAddressOf;
4478 SmallVector<std::string, 4> InputConstraints;
4479 SmallVector<std::string, 4> OutputConstraints;
4480 SmallVector<unsigned, 4> ClobberRegs;
4482 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4487 // While we have input, parse each statement.
4488 unsigned InputIdx = 0;
4489 unsigned OutputIdx = 0;
4490 while (getLexer().isNot(AsmToken::Eof)) {
4491 ParseStatementInfo Info(&AsmStrRewrites);
4492 if (parseStatement(Info))
4495 if (Info.ParseError)
4498 if (Info.Opcode == ~0U)
4501 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4503 // Build the list of clobbers, outputs and inputs.
4504 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4505 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4508 if (Operand.isImm())
4511 // Register operand.
4512 if (Operand.isReg() && !Operand.needAddressOf()) {
4513 unsigned NumDefs = Desc.getNumDefs();
4515 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4516 ClobberRegs.push_back(Operand.getReg());
4520 // Expr/Input or Output.
4521 StringRef SymName = Operand.getSymName();
4522 if (SymName.empty())
4525 void *OpDecl = Operand.getOpDecl();
4529 bool isOutput = (i == 1) && Desc.mayStore();
4530 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4533 OutputDecls.push_back(OpDecl);
4534 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4535 OutputConstraints.push_back('=' + Operand.getConstraint().str());
4536 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4538 InputDecls.push_back(OpDecl);
4539 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4540 InputConstraints.push_back(Operand.getConstraint().str());
4541 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4545 // Consider implicit defs to be clobbers. Think of cpuid and push.
4546 ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
4547 Desc.getNumImplicitDefs());
4548 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
4551 // Set the number of Outputs and Inputs.
4552 NumOutputs = OutputDecls.size();
4553 NumInputs = InputDecls.size();
4555 // Set the unique clobbers.
4556 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4557 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4559 Clobbers.assign(ClobberRegs.size(), std::string());
4560 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4561 raw_string_ostream OS(Clobbers[I]);
4562 IP->printRegName(OS, ClobberRegs[I]);
4565 // Merge the various outputs and inputs. Output are expected first.
4566 if (NumOutputs || NumInputs) {
4567 unsigned NumExprs = NumOutputs + NumInputs;
4568 OpDecls.resize(NumExprs);
4569 Constraints.resize(NumExprs);
4570 for (unsigned i = 0; i < NumOutputs; ++i) {
4571 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4572 Constraints[i] = OutputConstraints[i];
4574 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4575 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4576 Constraints[j] = InputConstraints[i];
4580 // Build the IR assembly string.
4581 std::string AsmStringIR;
4582 raw_string_ostream OS(AsmStringIR);
4583 StringRef ASMString =
4584 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4585 const char *AsmStart = ASMString.begin();
4586 const char *AsmEnd = ASMString.end();
4587 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4588 for (const AsmRewrite &AR : AsmStrRewrites) {
4589 AsmRewriteKind Kind = AR.Kind;
4590 if (Kind == AOK_Delete)
4593 const char *Loc = AR.Loc.getPointer();
4594 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4596 // Emit everything up to the immediate/expression.
4597 if (unsigned Len = Loc - AsmStart)
4598 OS << StringRef(AsmStart, Len);
4600 // Skip the original expression.
4601 if (Kind == AOK_Skip) {
4602 AsmStart = Loc + AR.Len;
4606 unsigned AdditionalSkip = 0;
4607 // Rewrite expressions in $N notation.
4612 OS << "$$" << AR.Val;
4618 OS << '$' << InputIdx++;
4621 OS << '$' << OutputIdx++;
4623 case AOK_SizeDirective:
4626 case 8: OS << "byte ptr "; break;
4627 case 16: OS << "word ptr "; break;
4628 case 32: OS << "dword ptr "; break;
4629 case 64: OS << "qword ptr "; break;
4630 case 80: OS << "xword ptr "; break;
4631 case 128: OS << "xmmword ptr "; break;
4632 case 256: OS << "ymmword ptr "; break;
4639 unsigned Val = AR.Val;
4640 OS << ".align " << Val;
4642 // Skip the original immediate.
4643 assert(Val < 10 && "Expected alignment less then 2^10.");
4644 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4647 case AOK_DotOperator:
4648 // Insert the dot if the user omitted it.
4650 if (AsmStringIR.back() != '.')
4656 // Skip the original expression.
4657 AsmStart = Loc + AR.Len + AdditionalSkip;
4660 // Emit the remainder of the asm string.
4661 if (AsmStart != AsmEnd)
4662 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4664 AsmString = OS.str();
4668 /// \brief Create an MCAsmParser instance.
4669 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4670 MCStreamer &Out, const MCAsmInfo &MAI) {
4671 return new AsmParser(SM, C, Out, MAI);