1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCParser/AsmCond.h"
27 #include "llvm/MC/MCParser/AsmLexer.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCTargetAsmParser.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/raw_ostream.h"
48 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
51 /// \brief Helper types for tracking macro definitions.
52 typedef std::vector<AsmToken> MCAsmMacroArgument;
53 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
55 struct MCAsmMacroParameter {
57 MCAsmMacroArgument Value;
61 MCAsmMacroParameter() : Required(false), Vararg(false) {}
64 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
69 MCAsmMacroParameters Parameters;
72 MCAsmMacro(StringRef N, StringRef B, ArrayRef<MCAsmMacroParameter> P) :
73 Name(N), Body(B), Parameters(P) {}
76 /// \brief Helper class for storing information about an active macro
78 struct MacroInstantiation {
79 /// The location of the instantiation.
80 SMLoc InstantiationLoc;
82 /// The buffer where parsing should resume upon instantiation completion.
85 /// The location where parsing should resume upon instantiation completion.
88 /// The depth of TheCondStack at the start of the instantiation.
89 size_t CondStackDepth;
92 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
95 struct ParseStatementInfo {
96 /// \brief The parsed operands from the last parsed statement.
97 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
99 /// \brief The opcode from the last parsed instruction.
102 /// \brief Was there an error parsing the inline assembly?
105 SmallVectorImpl<AsmRewrite> *AsmRewrites;
107 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
108 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
109 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
112 /// \brief The concrete assembly parser instance.
113 class AsmParser : public MCAsmParser {
114 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
115 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
120 const MCAsmInfo &MAI;
122 SourceMgr::DiagHandlerTy SavedDiagHandler;
123 void *SavedDiagContext;
124 MCAsmParserExtension *PlatformParser;
126 /// This is the current buffer index we're lexing from as managed by the
127 /// SourceMgr object.
130 AsmCond TheCondState;
131 std::vector<AsmCond> TheCondStack;
133 /// \brief maps directive names to handler methods in parser
134 /// extensions. Extensions register themselves in this map by calling
135 /// addDirectiveHandler.
136 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
138 /// \brief Map of currently defined macros.
139 StringMap<MCAsmMacro*> MacroMap;
141 /// \brief Stack of active macro instantiations.
142 std::vector<MacroInstantiation*> ActiveMacros;
144 /// \brief List of bodies of anonymous macros.
145 std::deque<MCAsmMacro> MacroLikeBodies;
147 /// Boolean tracking whether macro substitution is enabled.
148 unsigned MacrosEnabledFlag : 1;
150 /// Flag tracking whether any errors have been encountered.
151 unsigned HadError : 1;
153 /// The values from the last parsed cpp hash file line comment if any.
154 StringRef CppHashFilename;
155 int64_t CppHashLineNumber;
158 /// When generating dwarf for assembly source files we need to calculate the
159 /// logical line number based on the last parsed cpp hash file line comment
160 /// and current line. Since this is slow and messes up the SourceMgr's
161 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
162 SMLoc LastQueryIDLoc;
163 unsigned LastQueryBuffer;
164 unsigned LastQueryLine;
166 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
167 unsigned AssemblerDialect;
169 /// \brief is Darwin compatibility enabled?
172 /// \brief Are we parsing ms-style inline assembly?
173 bool ParsingInlineAsm;
176 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
177 const MCAsmInfo &MAI);
178 virtual ~AsmParser();
180 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
182 void addDirectiveHandler(StringRef Directive,
183 ExtensionDirectiveHandler Handler) override {
184 ExtensionDirectiveMap[Directive] = Handler;
188 /// @name MCAsmParser Interface
191 SourceMgr &getSourceManager() override { return SrcMgr; }
192 MCAsmLexer &getLexer() override { return Lexer; }
193 MCContext &getContext() override { return Ctx; }
194 MCStreamer &getStreamer() override { return Out; }
195 unsigned getAssemblerDialect() override {
196 if (AssemblerDialect == ~0U)
197 return MAI.getAssemblerDialect();
199 return AssemblerDialect;
201 void setAssemblerDialect(unsigned i) override {
202 AssemblerDialect = i;
205 void Note(SMLoc L, const Twine &Msg,
206 ArrayRef<SMRange> Ranges = None) override;
207 bool Warning(SMLoc L, const Twine &Msg,
208 ArrayRef<SMRange> Ranges = None) override;
209 bool Error(SMLoc L, const Twine &Msg,
210 ArrayRef<SMRange> Ranges = None) override;
212 const AsmToken &Lex() override;
214 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
215 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
217 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
218 unsigned &NumOutputs, unsigned &NumInputs,
219 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
220 SmallVectorImpl<std::string> &Constraints,
221 SmallVectorImpl<std::string> &Clobbers,
222 const MCInstrInfo *MII, const MCInstPrinter *IP,
223 MCAsmParserSemaCallback &SI) override;
225 bool parseExpression(const MCExpr *&Res);
226 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
227 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
228 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
229 bool parseAbsoluteExpression(int64_t &Res) override;
231 /// \brief Parse an identifier or string (as a quoted identifier)
232 /// and set \p Res to the identifier contents.
233 bool parseIdentifier(StringRef &Res) override;
234 void eatToEndOfStatement() override;
236 void checkForValidSection() override;
241 bool parseStatement(ParseStatementInfo &Info,
242 MCAsmParserSemaCallback *SI);
243 void eatToEndOfLine();
244 bool parseCppHashLineFilenameComment(const SMLoc &L);
246 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
247 ArrayRef<MCAsmMacroParameter> Parameters);
248 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
249 ArrayRef<MCAsmMacroParameter> Parameters,
250 ArrayRef<MCAsmMacroArgument> A,
253 /// \brief Are macros enabled in the parser?
254 bool areMacrosEnabled() {return MacrosEnabledFlag;}
256 /// \brief Control a flag in the parser that enables or disables macros.
257 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
259 /// \brief Lookup a previously defined macro.
260 /// \param Name Macro name.
261 /// \returns Pointer to macro. NULL if no such macro was defined.
262 const MCAsmMacro* lookupMacro(StringRef Name);
264 /// \brief Define a new macro with the given name and information.
265 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
267 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
268 void undefineMacro(StringRef Name);
270 /// \brief Are we inside a macro instantiation?
271 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
273 /// \brief Handle entry to macro instantiation.
275 /// \param M The macro.
276 /// \param NameLoc Instantiation location.
277 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
279 /// \brief Handle exit from macro instantiation.
280 void handleMacroExit();
282 /// \brief Extract AsmTokens for a macro argument.
283 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
285 /// \brief Parse all macro arguments for a given macro.
286 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
288 void printMacroInstantiations();
289 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
290 ArrayRef<SMRange> Ranges = None) const {
291 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
293 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
295 /// \brief Enter the specified file. This returns true on failure.
296 bool enterIncludeFile(const std::string &Filename);
298 /// \brief Process the specified file for the .incbin directive.
299 /// This returns true on failure.
300 bool processIncbinFile(const std::string &Filename);
302 /// \brief Reset the current lexer position to that given by \p Loc. The
303 /// current token is not set; clients should ensure Lex() is called
306 /// \param InBuffer If not 0, should be the known buffer id that contains the
308 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
310 /// \brief Parse up to the end of statement and a return the contents from the
311 /// current token until the end of the statement; the current token on exit
312 /// will be either the EndOfStatement or EOF.
313 StringRef parseStringToEndOfStatement() override;
315 /// \brief Parse until the end of a statement or a comma is encountered,
316 /// return the contents from the current token up to the end or comma.
317 StringRef parseStringToComma();
319 bool parseAssignment(StringRef Name, bool allow_redef,
320 bool NoDeadStrip = false);
322 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
323 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
324 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
326 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
328 // Generic (target and platform independent) directive parsing.
330 DK_NO_DIRECTIVE, // Placeholder
331 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
332 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
333 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
334 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
335 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
336 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
337 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
338 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
339 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
340 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
341 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
342 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
343 DK_ELSEIF, DK_ELSE, DK_ENDIF,
344 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
345 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
346 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
347 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
348 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
349 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
350 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
351 DK_MACROS_ON, DK_MACROS_OFF,
352 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
353 DK_SLEB128, DK_ULEB128,
354 DK_ERR, DK_ERROR, DK_WARNING,
358 /// \brief Maps directive name --> DirectiveKind enum, for
359 /// directives parsed by this class.
360 StringMap<DirectiveKind> DirectiveKindMap;
362 // ".ascii", ".asciz", ".string"
363 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
364 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
365 bool parseDirectiveOctaValue(); // ".octa"
366 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
367 bool parseDirectiveFill(); // ".fill"
368 bool parseDirectiveZero(); // ".zero"
369 // ".set", ".equ", ".equiv"
370 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
371 bool parseDirectiveOrg(); // ".org"
372 // ".align{,32}", ".p2align{,w,l}"
373 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
375 // ".file", ".line", ".loc", ".stabs"
376 bool parseDirectiveFile(SMLoc DirectiveLoc);
377 bool parseDirectiveLine();
378 bool parseDirectiveLoc();
379 bool parseDirectiveStabs();
382 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
383 bool parseDirectiveCFIWindowSave();
384 bool parseDirectiveCFISections();
385 bool parseDirectiveCFIStartProc();
386 bool parseDirectiveCFIEndProc();
387 bool parseDirectiveCFIDefCfaOffset();
388 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
389 bool parseDirectiveCFIAdjustCfaOffset();
390 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
391 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
392 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
393 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
394 bool parseDirectiveCFIRememberState();
395 bool parseDirectiveCFIRestoreState();
396 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
397 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
398 bool parseDirectiveCFIEscape();
399 bool parseDirectiveCFISignalFrame();
400 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
403 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
404 bool parseDirectiveExitMacro(StringRef Directive);
405 bool parseDirectiveEndMacro(StringRef Directive);
406 bool parseDirectiveMacro(SMLoc DirectiveLoc);
407 bool parseDirectiveMacrosOnOff(StringRef Directive);
409 // ".bundle_align_mode"
410 bool parseDirectiveBundleAlignMode();
412 bool parseDirectiveBundleLock();
414 bool parseDirectiveBundleUnlock();
417 bool parseDirectiveSpace(StringRef IDVal);
419 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
420 bool parseDirectiveLEB128(bool Signed);
422 /// \brief Parse a directive like ".globl" which
423 /// accepts a single symbol (which should be a label or an external).
424 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
426 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
428 bool parseDirectiveAbort(); // ".abort"
429 bool parseDirectiveInclude(); // ".include"
430 bool parseDirectiveIncbin(); // ".incbin"
432 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
433 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
434 // ".ifb" or ".ifnb", depending on ExpectBlank.
435 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
436 // ".ifc" or ".ifnc", depending on ExpectEqual.
437 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
439 bool parseDirectiveIfeqs(SMLoc DirectiveLoc);
440 // ".ifdef" or ".ifndef", depending on expect_defined
441 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
442 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
443 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
444 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
445 bool parseEscapedString(std::string &Data) override;
447 const MCExpr *applyModifierToExpr(const MCExpr *E,
448 MCSymbolRefExpr::VariantKind Variant);
450 // Macro-like directives
451 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
452 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
453 raw_svector_ostream &OS);
454 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
455 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
456 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
457 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
459 // "_emit" or "__emit"
460 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
464 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
467 bool parseDirectiveEnd(SMLoc DirectiveLoc);
469 // ".err" or ".error"
470 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
473 bool parseDirectiveWarning(SMLoc DirectiveLoc);
475 void initializeDirectiveKindMap();
481 extern MCAsmParserExtension *createDarwinAsmParser();
482 extern MCAsmParserExtension *createELFAsmParser();
483 extern MCAsmParserExtension *createCOFFAsmParser();
487 enum { DEFAULT_ADDRSPACE = 0 };
489 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
490 const MCAsmInfo &_MAI)
491 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
492 PlatformParser(nullptr), CurBuffer(_SM.getMainFileID()),
493 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
494 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
495 // Save the old handler.
496 SavedDiagHandler = SrcMgr.getDiagHandler();
497 SavedDiagContext = SrcMgr.getDiagContext();
498 // Set our own handler which calls the saved handler.
499 SrcMgr.setDiagHandler(DiagHandler, this);
500 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
502 // Initialize the platform / file format parser.
503 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
504 case MCObjectFileInfo::IsCOFF:
505 PlatformParser = createCOFFAsmParser();
506 PlatformParser->Initialize(*this);
508 case MCObjectFileInfo::IsMachO:
509 PlatformParser = createDarwinAsmParser();
510 PlatformParser->Initialize(*this);
513 case MCObjectFileInfo::IsELF:
514 PlatformParser = createELFAsmParser();
515 PlatformParser->Initialize(*this);
519 initializeDirectiveKindMap();
522 AsmParser::~AsmParser() {
523 assert((HadError || ActiveMacros.empty()) &&
524 "Unexpected active macro instantiation!");
526 // Destroy any macros.
527 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
530 delete it->getValue();
532 delete PlatformParser;
535 void AsmParser::printMacroInstantiations() {
536 // Print the active macro instantiation stack.
537 for (std::vector<MacroInstantiation *>::const_reverse_iterator
538 it = ActiveMacros.rbegin(),
539 ie = ActiveMacros.rend();
541 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
542 "while in macro instantiation");
545 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
546 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
547 printMacroInstantiations();
550 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
551 if (getTargetParser().getTargetOptions().MCFatalWarnings)
552 return Error(L, Msg, Ranges);
553 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
554 printMacroInstantiations();
558 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
560 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
561 printMacroInstantiations();
565 bool AsmParser::enterIncludeFile(const std::string &Filename) {
566 std::string IncludedFile;
568 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
573 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
577 /// Process the specified .incbin file by searching for it in the include paths
578 /// then just emitting the byte contents of the file to the streamer. This
579 /// returns true on failure.
580 bool AsmParser::processIncbinFile(const std::string &Filename) {
581 std::string IncludedFile;
583 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
587 // Pick up the bytes from the file and emit them.
588 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
592 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
593 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
594 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
598 const AsmToken &AsmParser::Lex() {
599 const AsmToken *tok = &Lexer.Lex();
601 if (tok->is(AsmToken::Eof)) {
602 // If this is the end of an included file, pop the parent file off the
604 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
605 if (ParentIncludeLoc != SMLoc()) {
606 jumpToLoc(ParentIncludeLoc);
611 if (tok->is(AsmToken::Error))
612 Error(Lexer.getErrLoc(), Lexer.getErr());
617 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
618 // Create the initial section, if requested.
619 if (!NoInitialTextSection)
626 AsmCond StartingCondState = TheCondState;
628 // If we are generating dwarf for assembly source files save the initial text
629 // section and generate a .file directive.
630 if (getContext().getGenDwarfForAssembly()) {
631 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
632 getStreamer().EmitLabel(SectionStartSym);
633 auto InsertResult = getContext().addGenDwarfSection(
634 getStreamer().getCurrentSection().first);
635 assert(InsertResult.second && ".text section should not have debug info yet");
636 InsertResult.first->second.first = SectionStartSym;
637 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
638 0, StringRef(), getContext().getMainFileName()));
641 // While we have input, parse each statement.
642 while (Lexer.isNot(AsmToken::Eof)) {
643 ParseStatementInfo Info;
644 if (!parseStatement(Info, nullptr))
647 // We had an error, validate that one was emitted and recover by skipping to
649 assert(HadError && "Parse statement returned an error, but none emitted!");
650 eatToEndOfStatement();
653 if (TheCondState.TheCond != StartingCondState.TheCond ||
654 TheCondState.Ignore != StartingCondState.Ignore)
655 return TokError("unmatched .ifs or .elses");
657 // Check to see there are no empty DwarfFile slots.
658 const auto &LineTables = getContext().getMCDwarfLineTables();
659 if (!LineTables.empty()) {
661 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
662 if (File.Name.empty() && Index != 0)
663 TokError("unassigned file number: " + Twine(Index) +
664 " for .file directives");
669 // Check to see that all assembler local symbols were actually defined.
670 // Targets that don't do subsections via symbols may not want this, though,
671 // so conservatively exclude them. Only do this if we're finalizing, though,
672 // as otherwise we won't necessarilly have seen everything yet.
673 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
674 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
675 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
678 MCSymbol *Sym = i->getValue();
679 // Variable symbols may not be marked as defined, so check those
680 // explicitly. If we know it's a variable, we have a definition for
681 // the purposes of this check.
682 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
683 // FIXME: We would really like to refer back to where the symbol was
684 // first referenced for a source location. We need to add something
685 // to track that. Currently, we just point to the end of the file.
687 getLexer().getLoc(), SourceMgr::DK_Error,
688 "assembler local symbol '" + Sym->getName() + "' not defined");
692 // Finalize the output stream if there are no errors and if the client wants
694 if (!HadError && !NoFinalize)
700 void AsmParser::checkForValidSection() {
701 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
702 TokError("expected section directive before assembly directive");
707 /// \brief Throw away the rest of the line for testing purposes.
708 void AsmParser::eatToEndOfStatement() {
709 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
713 if (Lexer.is(AsmToken::EndOfStatement))
717 StringRef AsmParser::parseStringToEndOfStatement() {
718 const char *Start = getTok().getLoc().getPointer();
720 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
723 const char *End = getTok().getLoc().getPointer();
724 return StringRef(Start, End - Start);
727 StringRef AsmParser::parseStringToComma() {
728 const char *Start = getTok().getLoc().getPointer();
730 while (Lexer.isNot(AsmToken::EndOfStatement) &&
731 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
734 const char *End = getTok().getLoc().getPointer();
735 return StringRef(Start, End - Start);
738 /// \brief Parse a paren expression and return it.
739 /// NOTE: This assumes the leading '(' has already been consumed.
741 /// parenexpr ::= expr)
743 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
744 if (parseExpression(Res))
746 if (Lexer.isNot(AsmToken::RParen))
747 return TokError("expected ')' in parentheses expression");
748 EndLoc = Lexer.getTok().getEndLoc();
753 /// \brief Parse a bracket expression and return it.
754 /// NOTE: This assumes the leading '[' has already been consumed.
756 /// bracketexpr ::= expr]
758 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
759 if (parseExpression(Res))
761 if (Lexer.isNot(AsmToken::RBrac))
762 return TokError("expected ']' in brackets expression");
763 EndLoc = Lexer.getTok().getEndLoc();
768 /// \brief Parse a primary expression and return it.
769 /// primaryexpr ::= (parenexpr
770 /// primaryexpr ::= symbol
771 /// primaryexpr ::= number
772 /// primaryexpr ::= '.'
773 /// primaryexpr ::= ~,+,- primaryexpr
774 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
775 SMLoc FirstTokenLoc = getLexer().getLoc();
776 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
777 switch (FirstTokenKind) {
779 return TokError("unknown token in expression");
780 // If we have an error assume that we've already handled it.
781 case AsmToken::Error:
783 case AsmToken::Exclaim:
784 Lex(); // Eat the operator.
785 if (parsePrimaryExpr(Res, EndLoc))
787 Res = MCUnaryExpr::CreateLNot(Res, getContext());
789 case AsmToken::Dollar:
791 case AsmToken::String:
792 case AsmToken::Identifier: {
793 StringRef Identifier;
794 if (parseIdentifier(Identifier)) {
795 if (FirstTokenKind == AsmToken::Dollar) {
796 if (Lexer.getMAI().getDollarIsPC()) {
797 // This is a '$' reference, which references the current PC. Emit a
798 // temporary label to the streamer and refer to it.
799 MCSymbol *Sym = Ctx.CreateTempSymbol();
801 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
803 EndLoc = FirstTokenLoc;
806 return Error(FirstTokenLoc, "invalid token in expression");
809 // Parse symbol variant
810 std::pair<StringRef, StringRef> Split;
811 if (!MAI.useParensForSymbolVariant()) {
812 if (FirstTokenKind == AsmToken::String) {
813 if (Lexer.is(AsmToken::At)) {
814 Lexer.Lex(); // eat @
815 SMLoc AtLoc = getLexer().getLoc();
817 if (parseIdentifier(VName))
818 return Error(AtLoc, "expected symbol variant after '@'");
820 Split = std::make_pair(Identifier, VName);
823 Split = Identifier.split('@');
825 } else if (Lexer.is(AsmToken::LParen)) {
826 Lexer.Lex(); // eat (
828 parseIdentifier(VName);
829 if (Lexer.isNot(AsmToken::RParen)) {
830 return Error(Lexer.getTok().getLoc(),
831 "unexpected token in variant, expected ')'");
833 Lexer.Lex(); // eat )
834 Split = std::make_pair(Identifier, VName);
837 EndLoc = SMLoc::getFromPointer(Identifier.end());
839 // This is a symbol reference.
840 StringRef SymbolName = Identifier;
841 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
843 // Lookup the symbol variant if used.
844 if (Split.second.size()) {
845 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
846 if (Variant != MCSymbolRefExpr::VK_Invalid) {
847 SymbolName = Split.first;
848 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
849 Variant = MCSymbolRefExpr::VK_None;
851 return Error(SMLoc::getFromPointer(Split.second.begin()),
852 "invalid variant '" + Split.second + "'");
856 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
858 // If this is an absolute variable reference, substitute it now to preserve
859 // semantics in the face of reassignment.
860 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
862 return Error(EndLoc, "unexpected modifier on variable reference");
864 Res = Sym->getVariableValue();
868 // Otherwise create a symbol ref.
869 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
872 case AsmToken::BigNum:
873 return TokError("literal value out of range for directive");
874 case AsmToken::Integer: {
875 SMLoc Loc = getTok().getLoc();
876 int64_t IntVal = getTok().getIntVal();
877 Res = MCConstantExpr::Create(IntVal, getContext());
878 EndLoc = Lexer.getTok().getEndLoc();
880 // Look for 'b' or 'f' following an Integer as a directional label
881 if (Lexer.getKind() == AsmToken::Identifier) {
882 StringRef IDVal = getTok().getString();
883 // Lookup the symbol variant if used.
884 std::pair<StringRef, StringRef> Split = IDVal.split('@');
885 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
886 if (Split.first.size() != IDVal.size()) {
887 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
888 if (Variant == MCSymbolRefExpr::VK_Invalid)
889 return TokError("invalid variant '" + Split.second + "'");
892 if (IDVal == "f" || IDVal == "b") {
894 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "b");
895 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
896 if (IDVal == "b" && Sym->isUndefined())
897 return Error(Loc, "invalid reference to undefined symbol");
898 EndLoc = Lexer.getTok().getEndLoc();
899 Lex(); // Eat identifier.
904 case AsmToken::Real: {
905 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
906 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
907 Res = MCConstantExpr::Create(IntVal, getContext());
908 EndLoc = Lexer.getTok().getEndLoc();
912 case AsmToken::Dot: {
913 // This is a '.' reference, which references the current PC. Emit a
914 // temporary label to the streamer and refer to it.
915 MCSymbol *Sym = Ctx.CreateTempSymbol();
917 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
918 EndLoc = Lexer.getTok().getEndLoc();
919 Lex(); // Eat identifier.
922 case AsmToken::LParen:
923 Lex(); // Eat the '('.
924 return parseParenExpr(Res, EndLoc);
925 case AsmToken::LBrac:
926 if (!PlatformParser->HasBracketExpressions())
927 return TokError("brackets expression not supported on this target");
928 Lex(); // Eat the '['.
929 return parseBracketExpr(Res, EndLoc);
930 case AsmToken::Minus:
931 Lex(); // Eat the operator.
932 if (parsePrimaryExpr(Res, EndLoc))
934 Res = MCUnaryExpr::CreateMinus(Res, getContext());
937 Lex(); // Eat the operator.
938 if (parsePrimaryExpr(Res, EndLoc))
940 Res = MCUnaryExpr::CreatePlus(Res, getContext());
942 case AsmToken::Tilde:
943 Lex(); // Eat the operator.
944 if (parsePrimaryExpr(Res, EndLoc))
946 Res = MCUnaryExpr::CreateNot(Res, getContext());
951 bool AsmParser::parseExpression(const MCExpr *&Res) {
953 return parseExpression(Res, EndLoc);
957 AsmParser::applyModifierToExpr(const MCExpr *E,
958 MCSymbolRefExpr::VariantKind Variant) {
959 // Ask the target implementation about this expression first.
960 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
963 // Recurse over the given expression, rebuilding it to apply the given variant
964 // if there is exactly one symbol.
965 switch (E->getKind()) {
967 case MCExpr::Constant:
970 case MCExpr::SymbolRef: {
971 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
973 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
974 TokError("invalid variant on expression '" + getTok().getIdentifier() +
975 "' (already modified)");
979 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
982 case MCExpr::Unary: {
983 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
984 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
987 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
990 case MCExpr::Binary: {
991 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
992 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
993 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1003 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
1007 llvm_unreachable("Invalid expression kind!");
1010 /// \brief Parse an expression and return it.
1012 /// expr ::= expr &&,|| expr -> lowest.
1013 /// expr ::= expr |,^,&,! expr
1014 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1015 /// expr ::= expr <<,>> expr
1016 /// expr ::= expr +,- expr
1017 /// expr ::= expr *,/,% expr -> highest.
1018 /// expr ::= primaryexpr
1020 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1021 // Parse the expression.
1023 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1026 // As a special case, we support 'a op b @ modifier' by rewriting the
1027 // expression to include the modifier. This is inefficient, but in general we
1028 // expect users to use 'a@modifier op b'.
1029 if (Lexer.getKind() == AsmToken::At) {
1032 if (Lexer.isNot(AsmToken::Identifier))
1033 return TokError("unexpected symbol modifier following '@'");
1035 MCSymbolRefExpr::VariantKind Variant =
1036 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1037 if (Variant == MCSymbolRefExpr::VK_Invalid)
1038 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1040 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1042 return TokError("invalid modifier '" + getTok().getIdentifier() +
1043 "' (no symbols present)");
1050 // Try to constant fold it up front, if possible.
1052 if (Res->EvaluateAsAbsolute(Value))
1053 Res = MCConstantExpr::Create(Value, getContext());
1058 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1060 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1063 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1066 SMLoc StartLoc = Lexer.getLoc();
1067 if (parseExpression(Expr))
1070 if (!Expr->EvaluateAsAbsolute(Res))
1071 return Error(StartLoc, "expected absolute expression");
1076 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1077 MCBinaryExpr::Opcode &Kind) {
1080 return 0; // not a binop.
1082 // Lowest Precedence: &&, ||
1083 case AsmToken::AmpAmp:
1084 Kind = MCBinaryExpr::LAnd;
1086 case AsmToken::PipePipe:
1087 Kind = MCBinaryExpr::LOr;
1090 // Low Precedence: |, &, ^
1092 // FIXME: gas seems to support '!' as an infix operator?
1093 case AsmToken::Pipe:
1094 Kind = MCBinaryExpr::Or;
1096 case AsmToken::Caret:
1097 Kind = MCBinaryExpr::Xor;
1100 Kind = MCBinaryExpr::And;
1103 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1104 case AsmToken::EqualEqual:
1105 Kind = MCBinaryExpr::EQ;
1107 case AsmToken::ExclaimEqual:
1108 case AsmToken::LessGreater:
1109 Kind = MCBinaryExpr::NE;
1111 case AsmToken::Less:
1112 Kind = MCBinaryExpr::LT;
1114 case AsmToken::LessEqual:
1115 Kind = MCBinaryExpr::LTE;
1117 case AsmToken::Greater:
1118 Kind = MCBinaryExpr::GT;
1120 case AsmToken::GreaterEqual:
1121 Kind = MCBinaryExpr::GTE;
1124 // Intermediate Precedence: <<, >>
1125 case AsmToken::LessLess:
1126 Kind = MCBinaryExpr::Shl;
1128 case AsmToken::GreaterGreater:
1129 Kind = MCBinaryExpr::Shr;
1132 // High Intermediate Precedence: +, -
1133 case AsmToken::Plus:
1134 Kind = MCBinaryExpr::Add;
1136 case AsmToken::Minus:
1137 Kind = MCBinaryExpr::Sub;
1140 // Highest Precedence: *, /, %
1141 case AsmToken::Star:
1142 Kind = MCBinaryExpr::Mul;
1144 case AsmToken::Slash:
1145 Kind = MCBinaryExpr::Div;
1147 case AsmToken::Percent:
1148 Kind = MCBinaryExpr::Mod;
1153 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1154 /// Res contains the LHS of the expression on input.
1155 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1158 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1159 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1161 // If the next token is lower precedence than we are allowed to eat, return
1162 // successfully with what we ate already.
1163 if (TokPrec < Precedence)
1168 // Eat the next primary expression.
1170 if (parsePrimaryExpr(RHS, EndLoc))
1173 // If BinOp binds less tightly with RHS than the operator after RHS, let
1174 // the pending operator take RHS as its LHS.
1175 MCBinaryExpr::Opcode Dummy;
1176 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1177 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1180 // Merge LHS and RHS according to operator.
1181 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1186 /// ::= EndOfStatement
1187 /// ::= Label* Directive ...Operands... EndOfStatement
1188 /// ::= Label* Identifier OperandList* EndOfStatement
1189 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1190 MCAsmParserSemaCallback *SI) {
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 if (ParsingInlineAsm && SI) {
1302 StringRef RewrittenLabel = SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1303 assert(RewrittenLabel.size() && "We should have an internal name here.");
1304 Info.AsmRewrites->push_back(AsmRewrite(AOK_Label, IDLoc,
1305 IDVal.size(), RewrittenLabel));
1306 IDVal = RewrittenLabel;
1308 Sym = getContext().GetOrCreateSymbol(IDVal);
1310 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1311 if (!Sym->isUndefined() || Sym->isVariable())
1312 return Error(IDLoc, "invalid symbol redefinition");
1315 if (!ParsingInlineAsm)
1318 // If we are generating dwarf for assembly source files then gather the
1319 // info to make a dwarf label entry for this label if needed.
1320 if (getContext().getGenDwarfForAssembly())
1321 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1324 getTargetParser().onLabelParsed(Sym);
1326 // Consume any end of statement token, if present, to avoid spurious
1327 // AddBlankLine calls().
1328 if (Lexer.is(AsmToken::EndOfStatement)) {
1330 if (Lexer.is(AsmToken::Eof))
1337 case AsmToken::Equal:
1338 // identifier '=' ... -> assignment statement
1341 return parseAssignment(IDVal, true);
1343 default: // Normal instruction or directive.
1347 // If macros are enabled, check to see if this is a macro instantiation.
1348 if (areMacrosEnabled())
1349 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1350 return handleMacroEntry(M, IDLoc);
1353 // Otherwise, we have a normal instruction or directive.
1355 // Directives start with "."
1356 if (IDVal[0] == '.' && IDVal != ".") {
1357 // There are several entities interested in parsing directives:
1359 // 1. The target-specific assembly parser. Some directives are target
1360 // specific or may potentially behave differently on certain targets.
1361 // 2. Asm parser extensions. For example, platform-specific parsers
1362 // (like the ELF parser) register themselves as extensions.
1363 // 3. The generic directive parser implemented by this class. These are
1364 // all the directives that behave in a target and platform independent
1365 // manner, or at least have a default behavior that's shared between
1366 // all targets and platforms.
1368 // First query the target-specific parser. It will return 'true' if it
1369 // isn't interested in this directive.
1370 if (!getTargetParser().ParseDirective(ID))
1373 // Next, check the extension directive map to see if any extension has
1374 // registered itself to parse this directive.
1375 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1376 ExtensionDirectiveMap.lookup(IDVal);
1378 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1380 // Finally, if no one else is interested in this directive, it must be
1381 // generic and familiar to this class.
1387 return parseDirectiveSet(IDVal, true);
1389 return parseDirectiveSet(IDVal, false);
1391 return parseDirectiveAscii(IDVal, false);
1394 return parseDirectiveAscii(IDVal, true);
1396 return parseDirectiveValue(1);
1400 return parseDirectiveValue(2);
1404 return parseDirectiveValue(4);
1407 return parseDirectiveValue(8);
1409 return parseDirectiveOctaValue();
1412 return parseDirectiveRealValue(APFloat::IEEEsingle);
1414 return parseDirectiveRealValue(APFloat::IEEEdouble);
1416 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1417 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1420 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1421 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1424 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1426 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1428 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1430 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1432 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1434 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1436 return parseDirectiveOrg();
1438 return parseDirectiveFill();
1440 return parseDirectiveZero();
1442 eatToEndOfStatement(); // .extern is the default, ignore it.
1446 return parseDirectiveSymbolAttribute(MCSA_Global);
1447 case DK_LAZY_REFERENCE:
1448 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1449 case DK_NO_DEAD_STRIP:
1450 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1451 case DK_SYMBOL_RESOLVER:
1452 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1453 case DK_PRIVATE_EXTERN:
1454 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1456 return parseDirectiveSymbolAttribute(MCSA_Reference);
1457 case DK_WEAK_DEFINITION:
1458 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1459 case DK_WEAK_REFERENCE:
1460 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1461 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1462 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1465 return parseDirectiveComm(/*IsLocal=*/false);
1467 return parseDirectiveComm(/*IsLocal=*/true);
1469 return parseDirectiveAbort();
1471 return parseDirectiveInclude();
1473 return parseDirectiveIncbin();
1476 return TokError(Twine(IDVal) + " not supported yet");
1478 return parseDirectiveRept(IDLoc, IDVal);
1480 return parseDirectiveIrp(IDLoc);
1482 return parseDirectiveIrpc(IDLoc);
1484 return parseDirectiveEndr(IDLoc);
1485 case DK_BUNDLE_ALIGN_MODE:
1486 return parseDirectiveBundleAlignMode();
1487 case DK_BUNDLE_LOCK:
1488 return parseDirectiveBundleLock();
1489 case DK_BUNDLE_UNLOCK:
1490 return parseDirectiveBundleUnlock();
1492 return parseDirectiveLEB128(true);
1494 return parseDirectiveLEB128(false);
1497 return parseDirectiveSpace(IDVal);
1499 return parseDirectiveFile(IDLoc);
1501 return parseDirectiveLine();
1503 return parseDirectiveLoc();
1505 return parseDirectiveStabs();
1506 case DK_CFI_SECTIONS:
1507 return parseDirectiveCFISections();
1508 case DK_CFI_STARTPROC:
1509 return parseDirectiveCFIStartProc();
1510 case DK_CFI_ENDPROC:
1511 return parseDirectiveCFIEndProc();
1512 case DK_CFI_DEF_CFA:
1513 return parseDirectiveCFIDefCfa(IDLoc);
1514 case DK_CFI_DEF_CFA_OFFSET:
1515 return parseDirectiveCFIDefCfaOffset();
1516 case DK_CFI_ADJUST_CFA_OFFSET:
1517 return parseDirectiveCFIAdjustCfaOffset();
1518 case DK_CFI_DEF_CFA_REGISTER:
1519 return parseDirectiveCFIDefCfaRegister(IDLoc);
1521 return parseDirectiveCFIOffset(IDLoc);
1522 case DK_CFI_REL_OFFSET:
1523 return parseDirectiveCFIRelOffset(IDLoc);
1524 case DK_CFI_PERSONALITY:
1525 return parseDirectiveCFIPersonalityOrLsda(true);
1527 return parseDirectiveCFIPersonalityOrLsda(false);
1528 case DK_CFI_REMEMBER_STATE:
1529 return parseDirectiveCFIRememberState();
1530 case DK_CFI_RESTORE_STATE:
1531 return parseDirectiveCFIRestoreState();
1532 case DK_CFI_SAME_VALUE:
1533 return parseDirectiveCFISameValue(IDLoc);
1534 case DK_CFI_RESTORE:
1535 return parseDirectiveCFIRestore(IDLoc);
1537 return parseDirectiveCFIEscape();
1538 case DK_CFI_SIGNAL_FRAME:
1539 return parseDirectiveCFISignalFrame();
1540 case DK_CFI_UNDEFINED:
1541 return parseDirectiveCFIUndefined(IDLoc);
1542 case DK_CFI_REGISTER:
1543 return parseDirectiveCFIRegister(IDLoc);
1544 case DK_CFI_WINDOW_SAVE:
1545 return parseDirectiveCFIWindowSave();
1548 return parseDirectiveMacrosOnOff(IDVal);
1550 return parseDirectiveMacro(IDLoc);
1552 return parseDirectiveExitMacro(IDVal);
1555 return parseDirectiveEndMacro(IDVal);
1557 return parseDirectivePurgeMacro(IDLoc);
1559 return parseDirectiveEnd(IDLoc);
1561 return parseDirectiveError(IDLoc, false);
1563 return parseDirectiveError(IDLoc, true);
1565 return parseDirectiveWarning(IDLoc);
1568 return Error(IDLoc, "unknown directive");
1571 // __asm _emit or __asm __emit
1572 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1573 IDVal == "_EMIT" || IDVal == "__EMIT"))
1574 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1577 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1578 return parseDirectiveMSAlign(IDLoc, Info);
1580 checkForValidSection();
1582 // Canonicalize the opcode to lower case.
1583 std::string OpcodeStr = IDVal.lower();
1584 ParseInstructionInfo IInfo(Info.AsmRewrites);
1585 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1586 Info.ParsedOperands);
1587 Info.ParseError = HadError;
1589 // Dump the parsed representation, if requested.
1590 if (getShowParsedOperands()) {
1591 SmallString<256> Str;
1592 raw_svector_ostream OS(Str);
1593 OS << "parsed instruction: [";
1594 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1597 Info.ParsedOperands[i]->print(OS);
1601 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1604 // If we are generating dwarf for the current section then generate a .loc
1605 // directive for the instruction.
1606 if (!HadError && getContext().getGenDwarfForAssembly() &&
1607 getContext().getGenDwarfSectionSyms().count(
1608 getStreamer().getCurrentSection().first)) {
1610 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1612 // If we previously parsed a cpp hash file line comment then make sure the
1613 // current Dwarf File is for the CppHashFilename if not then emit the
1614 // Dwarf File table for it and adjust the line number for the .loc.
1615 if (CppHashFilename.size() != 0) {
1616 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1617 0, StringRef(), CppHashFilename);
1618 getContext().setGenDwarfFileNumber(FileNumber);
1620 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1621 // cache with the different Loc from the call above we save the last
1622 // info we queried here with SrcMgr.FindLineNumber().
1623 unsigned CppHashLocLineNo;
1624 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1625 CppHashLocLineNo = LastQueryLine;
1627 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1628 LastQueryLine = CppHashLocLineNo;
1629 LastQueryIDLoc = CppHashLoc;
1630 LastQueryBuffer = CppHashBuf;
1632 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1635 getStreamer().EmitDwarfLocDirective(
1636 getContext().getGenDwarfFileNumber(), Line, 0,
1637 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1641 // If parsing succeeded, match the instruction.
1644 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1645 Info.ParsedOperands, Out,
1646 ErrorInfo, ParsingInlineAsm);
1649 // Don't skip the rest of the line, the instruction parser is responsible for
1654 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1655 /// since they may not be able to be tokenized to get to the end of line token.
1656 void AsmParser::eatToEndOfLine() {
1657 if (!Lexer.is(AsmToken::EndOfStatement))
1658 Lexer.LexUntilEndOfLine();
1663 /// parseCppHashLineFilenameComment as this:
1664 /// ::= # number "filename"
1665 /// or just as a full line comment if it doesn't have a number and a string.
1666 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1667 Lex(); // Eat the hash token.
1669 if (getLexer().isNot(AsmToken::Integer)) {
1670 // Consume the line since in cases it is not a well-formed line directive,
1671 // as if were simply a full line comment.
1676 int64_t LineNumber = getTok().getIntVal();
1679 if (getLexer().isNot(AsmToken::String)) {
1684 StringRef Filename = getTok().getString();
1685 // Get rid of the enclosing quotes.
1686 Filename = Filename.substr(1, Filename.size() - 2);
1688 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1690 CppHashFilename = Filename;
1691 CppHashLineNumber = LineNumber;
1692 CppHashBuf = CurBuffer;
1694 // Ignore any trailing characters, they're just comment.
1699 /// \brief will use the last parsed cpp hash line filename comment
1700 /// for the Filename and LineNo if any in the diagnostic.
1701 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1702 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1703 raw_ostream &OS = errs();
1705 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1706 const SMLoc &DiagLoc = Diag.getLoc();
1707 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1708 unsigned CppHashBuf =
1709 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1711 // Like SourceMgr::printMessage() we need to print the include stack if any
1712 // before printing the message.
1713 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1714 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1715 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
1716 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1717 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1720 // If we have not parsed a cpp hash line filename comment or the source
1721 // manager changed or buffer changed (like in a nested include) then just
1722 // print the normal diagnostic using its Filename and LineNo.
1723 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1724 DiagBuf != CppHashBuf) {
1725 if (Parser->SavedDiagHandler)
1726 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1728 Diag.print(nullptr, OS);
1732 // Use the CppHashFilename and calculate a line number based on the
1733 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1735 const std::string &Filename = Parser->CppHashFilename;
1737 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1738 int CppHashLocLineNo =
1739 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1741 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1743 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1744 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1745 Diag.getLineContents(), Diag.getRanges());
1747 if (Parser->SavedDiagHandler)
1748 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1750 NewDiag.print(nullptr, OS);
1753 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1754 // difference being that that function accepts '@' as part of identifiers and
1755 // we can't do that. AsmLexer.cpp should probably be changed to handle
1756 // '@' as a special case when needed.
1757 static bool isIdentifierChar(char c) {
1758 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1762 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1763 ArrayRef<MCAsmMacroParameter> Parameters,
1764 ArrayRef<MCAsmMacroArgument> A, const SMLoc &L) {
1765 unsigned NParameters = Parameters.size();
1766 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1767 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1768 return Error(L, "Wrong number of arguments");
1770 // A macro without parameters is handled differently on Darwin:
1771 // gas accepts no arguments and does no substitutions
1772 while (!Body.empty()) {
1773 // Scan for the next substitution.
1774 std::size_t End = Body.size(), Pos = 0;
1775 for (; Pos != End; ++Pos) {
1776 // Check for a substitution or escape.
1777 if (IsDarwin && !NParameters) {
1778 // This macro has no parameters, look for $0, $1, etc.
1779 if (Body[Pos] != '$' || Pos + 1 == End)
1782 char Next = Body[Pos + 1];
1783 if (Next == '$' || Next == 'n' ||
1784 isdigit(static_cast<unsigned char>(Next)))
1787 // This macro has parameters, look for \foo, \bar, etc.
1788 if (Body[Pos] == '\\' && Pos + 1 != End)
1794 OS << Body.slice(0, Pos);
1796 // Check if we reached the end.
1800 if (IsDarwin && !NParameters) {
1801 switch (Body[Pos + 1]) {
1807 // $n => number of arguments
1812 // $[0-9] => argument
1814 // Missing arguments are ignored.
1815 unsigned Index = Body[Pos + 1] - '0';
1816 if (Index >= A.size())
1819 // Otherwise substitute with the token values, with spaces eliminated.
1820 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1821 ie = A[Index].end();
1823 OS << it->getString();
1829 unsigned I = Pos + 1;
1830 while (isIdentifierChar(Body[I]) && I + 1 != End)
1833 const char *Begin = Body.data() + Pos + 1;
1834 StringRef Argument(Begin, I - (Pos + 1));
1836 for (; Index < NParameters; ++Index)
1837 if (Parameters[Index].Name == Argument)
1840 if (Index == NParameters) {
1841 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1844 OS << '\\' << Argument;
1848 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1849 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1850 ie = A[Index].end();
1852 // We expect no quotes around the string's contents when
1853 // parsing for varargs.
1854 if (it->getKind() != AsmToken::String || VarargParameter)
1855 OS << it->getString();
1857 OS << it->getStringContents();
1859 Pos += 1 + Argument.size();
1862 // Update the scan point.
1863 Body = Body.substr(Pos);
1869 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
1870 size_t CondStackDepth)
1871 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
1872 CondStackDepth(CondStackDepth) {}
1874 static bool isOperator(AsmToken::TokenKind kind) {
1878 case AsmToken::Plus:
1879 case AsmToken::Minus:
1880 case AsmToken::Tilde:
1881 case AsmToken::Slash:
1882 case AsmToken::Star:
1884 case AsmToken::Equal:
1885 case AsmToken::EqualEqual:
1886 case AsmToken::Pipe:
1887 case AsmToken::PipePipe:
1888 case AsmToken::Caret:
1890 case AsmToken::AmpAmp:
1891 case AsmToken::Exclaim:
1892 case AsmToken::ExclaimEqual:
1893 case AsmToken::Percent:
1894 case AsmToken::Less:
1895 case AsmToken::LessEqual:
1896 case AsmToken::LessLess:
1897 case AsmToken::LessGreater:
1898 case AsmToken::Greater:
1899 case AsmToken::GreaterEqual:
1900 case AsmToken::GreaterGreater:
1906 class AsmLexerSkipSpaceRAII {
1908 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1909 Lexer.setSkipSpace(SkipSpace);
1912 ~AsmLexerSkipSpaceRAII() {
1913 Lexer.setSkipSpace(true);
1921 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1924 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1925 StringRef Str = parseStringToEndOfStatement();
1926 MA.push_back(AsmToken(AsmToken::String, Str));
1931 unsigned ParenLevel = 0;
1932 unsigned AddTokens = 0;
1934 // Darwin doesn't use spaces to delmit arguments.
1935 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1938 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1939 return TokError("unexpected token in macro instantiation");
1941 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1944 if (Lexer.is(AsmToken::Space)) {
1945 Lex(); // Eat spaces
1947 // Spaces can delimit parameters, but could also be part an expression.
1948 // If the token after a space is an operator, add the token and the next
1949 // one into this argument
1951 if (isOperator(Lexer.getKind())) {
1952 // Check to see whether the token is used as an operator,
1953 // or part of an identifier
1954 const char *NextChar = getTok().getEndLoc().getPointer();
1955 if (*NextChar == ' ')
1959 if (!AddTokens && ParenLevel == 0) {
1965 // handleMacroEntry relies on not advancing the lexer here
1966 // to be able to fill in the remaining default parameter values
1967 if (Lexer.is(AsmToken::EndOfStatement))
1970 // Adjust the current parentheses level.
1971 if (Lexer.is(AsmToken::LParen))
1973 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1976 // Append the token to the current argument list.
1977 MA.push_back(getTok());
1983 if (ParenLevel != 0)
1984 return TokError("unbalanced parentheses in macro argument");
1988 // Parse the macro instantiation arguments.
1989 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1990 MCAsmMacroArguments &A) {
1991 const unsigned NParameters = M ? M->Parameters.size() : 0;
1992 bool NamedParametersFound = false;
1993 SmallVector<SMLoc, 4> FALocs;
1995 A.resize(NParameters);
1996 FALocs.resize(NParameters);
1998 // Parse two kinds of macro invocations:
1999 // - macros defined without any parameters accept an arbitrary number of them
2000 // - macros defined with parameters accept at most that many of them
2001 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2002 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2004 SMLoc IDLoc = Lexer.getLoc();
2005 MCAsmMacroParameter FA;
2007 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2008 if (parseIdentifier(FA.Name)) {
2009 Error(IDLoc, "invalid argument identifier for formal argument");
2010 eatToEndOfStatement();
2014 if (!Lexer.is(AsmToken::Equal)) {
2015 TokError("expected '=' after formal parameter identifier");
2016 eatToEndOfStatement();
2021 NamedParametersFound = true;
2024 if (NamedParametersFound && FA.Name.empty()) {
2025 Error(IDLoc, "cannot mix positional and keyword arguments");
2026 eatToEndOfStatement();
2030 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2031 if (parseMacroArgument(FA.Value, Vararg))
2034 unsigned PI = Parameter;
2035 if (!FA.Name.empty()) {
2037 for (FAI = 0; FAI < NParameters; ++FAI)
2038 if (M->Parameters[FAI].Name == FA.Name)
2041 if (FAI >= NParameters) {
2042 assert(M && "expected macro to be defined");
2044 "parameter named '" + FA.Name + "' does not exist for macro '" +
2051 if (!FA.Value.empty()) {
2056 if (FALocs.size() <= PI)
2057 FALocs.resize(PI + 1);
2059 FALocs[PI] = Lexer.getLoc();
2062 // At the end of the statement, fill in remaining arguments that have
2063 // default values. If there aren't any, then the next argument is
2064 // required but missing
2065 if (Lexer.is(AsmToken::EndOfStatement)) {
2066 bool Failure = false;
2067 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2068 if (A[FAI].empty()) {
2069 if (M->Parameters[FAI].Required) {
2070 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2071 "missing value for required parameter "
2072 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2076 if (!M->Parameters[FAI].Value.empty())
2077 A[FAI] = M->Parameters[FAI].Value;
2083 if (Lexer.is(AsmToken::Comma))
2087 return TokError("too many positional arguments");
2090 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2091 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2092 return (I == MacroMap.end()) ? nullptr : I->getValue();
2095 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
2096 MacroMap[Name] = new MCAsmMacro(Macro);
2099 void AsmParser::undefineMacro(StringRef Name) {
2100 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2101 if (I != MacroMap.end()) {
2102 delete I->getValue();
2107 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2108 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2109 // this, although we should protect against infinite loops.
2110 if (ActiveMacros.size() == 20)
2111 return TokError("macros cannot be nested more than 20 levels deep");
2113 MCAsmMacroArguments A;
2114 if (parseMacroArguments(M, A))
2117 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2118 // to hold the macro body with substitutions.
2119 SmallString<256> Buf;
2120 StringRef Body = M->Body;
2121 raw_svector_ostream OS(Buf);
2123 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2126 // We include the .endmacro in the buffer as our cue to exit the macro
2128 OS << ".endmacro\n";
2130 std::unique_ptr<MemoryBuffer> Instantiation =
2131 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2133 // Create the macro instantiation object and add to the current macro
2134 // instantiation stack.
2135 MacroInstantiation *MI = new MacroInstantiation(
2136 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2137 ActiveMacros.push_back(MI);
2139 // Jump to the macro instantiation and prime the lexer.
2140 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2141 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2147 void AsmParser::handleMacroExit() {
2148 // Jump to the EndOfStatement we should return to, and consume it.
2149 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2152 // Pop the instantiation entry.
2153 delete ActiveMacros.back();
2154 ActiveMacros.pop_back();
2157 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2158 switch (Value->getKind()) {
2159 case MCExpr::Binary: {
2160 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2161 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2163 case MCExpr::Target:
2164 case MCExpr::Constant:
2166 case MCExpr::SymbolRef: {
2168 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2170 return isUsedIn(Sym, S.getVariableValue());
2174 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2177 llvm_unreachable("Unknown expr kind!");
2180 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2182 // FIXME: Use better location, we should use proper tokens.
2183 SMLoc EqualLoc = Lexer.getLoc();
2185 const MCExpr *Value;
2186 if (parseExpression(Value))
2189 // Note: we don't count b as used in "a = b". This is to allow
2193 if (Lexer.isNot(AsmToken::EndOfStatement))
2194 return TokError("unexpected token in assignment");
2196 // Eat the end of statement marker.
2199 // Validate that the LHS is allowed to be a variable (either it has not been
2200 // used as a symbol, or it is an absolute symbol).
2201 MCSymbol *Sym = getContext().LookupSymbol(Name);
2203 // Diagnose assignment to a label.
2205 // FIXME: Diagnostics. Note the location of the definition as a label.
2206 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2207 if (isUsedIn(Sym, Value))
2208 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2209 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2210 ; // Allow redefinitions of undefined symbols only used in directives.
2211 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2212 ; // Allow redefinitions of variables that haven't yet been used.
2213 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2214 return Error(EqualLoc, "redefinition of '" + Name + "'");
2215 else if (!Sym->isVariable())
2216 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2217 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2218 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2221 // Don't count these checks as uses.
2222 Sym->setUsed(false);
2223 } else if (Name == ".") {
2224 if (Out.EmitValueToOffset(Value, 0)) {
2225 Error(EqualLoc, "expected absolute expression");
2226 eatToEndOfStatement();
2230 Sym = getContext().GetOrCreateSymbol(Name);
2232 // Do the assignment.
2233 Out.EmitAssignment(Sym, Value);
2235 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2240 /// parseIdentifier:
2243 bool AsmParser::parseIdentifier(StringRef &Res) {
2244 // The assembler has relaxed rules for accepting identifiers, in particular we
2245 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2246 // separate tokens. At this level, we have already lexed so we cannot (currently)
2247 // handle this as a context dependent token, instead we detect adjacent tokens
2248 // and return the combined identifier.
2249 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2250 SMLoc PrefixLoc = getLexer().getLoc();
2252 // Consume the prefix character, and check for a following identifier.
2254 if (Lexer.isNot(AsmToken::Identifier))
2257 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2258 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2261 // Construct the joined identifier and consume the token.
2263 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2268 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2271 Res = getTok().getIdentifier();
2273 Lex(); // Consume the identifier token.
2278 /// parseDirectiveSet:
2279 /// ::= .equ identifier ',' expression
2280 /// ::= .equiv identifier ',' expression
2281 /// ::= .set identifier ',' expression
2282 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2285 if (parseIdentifier(Name))
2286 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2288 if (getLexer().isNot(AsmToken::Comma))
2289 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2292 return parseAssignment(Name, allow_redef, true);
2295 bool AsmParser::parseEscapedString(std::string &Data) {
2296 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2299 StringRef Str = getTok().getStringContents();
2300 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2301 if (Str[i] != '\\') {
2306 // Recognize escaped characters. Note that this escape semantics currently
2307 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2310 return TokError("unexpected backslash at end of string");
2312 // Recognize octal sequences.
2313 if ((unsigned)(Str[i] - '0') <= 7) {
2314 // Consume up to three octal characters.
2315 unsigned Value = Str[i] - '0';
2317 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2319 Value = Value * 8 + (Str[i] - '0');
2321 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2323 Value = Value * 8 + (Str[i] - '0');
2328 return TokError("invalid octal escape sequence (out of range)");
2330 Data += (unsigned char)Value;
2334 // Otherwise recognize individual escapes.
2337 // Just reject invalid escape sequences for now.
2338 return TokError("invalid escape sequence (unrecognized character)");
2340 case 'b': Data += '\b'; break;
2341 case 'f': Data += '\f'; break;
2342 case 'n': Data += '\n'; break;
2343 case 'r': Data += '\r'; break;
2344 case 't': Data += '\t'; break;
2345 case '"': Data += '"'; break;
2346 case '\\': Data += '\\'; break;
2353 /// parseDirectiveAscii:
2354 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2355 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2356 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2357 checkForValidSection();
2360 if (getLexer().isNot(AsmToken::String))
2361 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2364 if (parseEscapedString(Data))
2367 getStreamer().EmitBytes(Data);
2369 getStreamer().EmitBytes(StringRef("\0", 1));
2373 if (getLexer().is(AsmToken::EndOfStatement))
2376 if (getLexer().isNot(AsmToken::Comma))
2377 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2386 /// parseDirectiveValue
2387 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2388 bool AsmParser::parseDirectiveValue(unsigned Size) {
2389 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2390 checkForValidSection();
2393 const MCExpr *Value;
2394 SMLoc ExprLoc = getLexer().getLoc();
2395 if (parseExpression(Value))
2398 // Special case constant expressions to match code generator.
2399 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2400 assert(Size <= 8 && "Invalid size");
2401 uint64_t IntValue = MCE->getValue();
2402 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2403 return Error(ExprLoc, "literal value out of range for directive");
2404 getStreamer().EmitIntValue(IntValue, Size);
2406 getStreamer().EmitValue(Value, Size, ExprLoc);
2408 if (getLexer().is(AsmToken::EndOfStatement))
2411 // FIXME: Improve diagnostic.
2412 if (getLexer().isNot(AsmToken::Comma))
2413 return TokError("unexpected token in directive");
2422 /// ParseDirectiveOctaValue
2423 /// ::= .octa [ hexconstant (, hexconstant)* ]
2424 bool AsmParser::parseDirectiveOctaValue() {
2425 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2426 checkForValidSection();
2429 if (Lexer.getKind() == AsmToken::Error)
2431 if (Lexer.getKind() != AsmToken::Integer &&
2432 Lexer.getKind() != AsmToken::BigNum)
2433 return TokError("unknown token in expression");
2435 SMLoc ExprLoc = getLexer().getLoc();
2436 APInt IntValue = getTok().getAPIntVal();
2440 if (IntValue.isIntN(64)) {
2442 lo = IntValue.getZExtValue();
2443 } else if (IntValue.isIntN(128)) {
2444 // It might actually have more than 128 bits, but the top ones are zero.
2445 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2446 lo = IntValue.getLoBits(64).getZExtValue();
2448 return Error(ExprLoc, "literal value out of range for directive");
2450 if (MAI.isLittleEndian()) {
2451 getStreamer().EmitIntValue(lo, 8);
2452 getStreamer().EmitIntValue(hi, 8);
2454 getStreamer().EmitIntValue(hi, 8);
2455 getStreamer().EmitIntValue(lo, 8);
2458 if (getLexer().is(AsmToken::EndOfStatement))
2461 // FIXME: Improve diagnostic.
2462 if (getLexer().isNot(AsmToken::Comma))
2463 return TokError("unexpected token in directive");
2472 /// parseDirectiveRealValue
2473 /// ::= (.single | .double) [ expression (, expression)* ]
2474 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2475 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2476 checkForValidSection();
2479 // We don't truly support arithmetic on floating point expressions, so we
2480 // have to manually parse unary prefixes.
2482 if (getLexer().is(AsmToken::Minus)) {
2485 } else if (getLexer().is(AsmToken::Plus))
2488 if (getLexer().isNot(AsmToken::Integer) &&
2489 getLexer().isNot(AsmToken::Real) &&
2490 getLexer().isNot(AsmToken::Identifier))
2491 return TokError("unexpected token in directive");
2493 // Convert to an APFloat.
2494 APFloat Value(Semantics);
2495 StringRef IDVal = getTok().getString();
2496 if (getLexer().is(AsmToken::Identifier)) {
2497 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2498 Value = APFloat::getInf(Semantics);
2499 else if (!IDVal.compare_lower("nan"))
2500 Value = APFloat::getNaN(Semantics, false, ~0);
2502 return TokError("invalid floating point literal");
2503 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2504 APFloat::opInvalidOp)
2505 return TokError("invalid floating point literal");
2509 // Consume the numeric token.
2512 // Emit the value as an integer.
2513 APInt AsInt = Value.bitcastToAPInt();
2514 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2515 AsInt.getBitWidth() / 8);
2517 if (getLexer().is(AsmToken::EndOfStatement))
2520 if (getLexer().isNot(AsmToken::Comma))
2521 return TokError("unexpected token in directive");
2530 /// parseDirectiveZero
2531 /// ::= .zero expression
2532 bool AsmParser::parseDirectiveZero() {
2533 checkForValidSection();
2536 if (parseAbsoluteExpression(NumBytes))
2540 if (getLexer().is(AsmToken::Comma)) {
2542 if (parseAbsoluteExpression(Val))
2546 if (getLexer().isNot(AsmToken::EndOfStatement))
2547 return TokError("unexpected token in '.zero' directive");
2551 getStreamer().EmitFill(NumBytes, Val);
2556 /// parseDirectiveFill
2557 /// ::= .fill expression [ , expression [ , expression ] ]
2558 bool AsmParser::parseDirectiveFill() {
2559 checkForValidSection();
2561 SMLoc RepeatLoc = getLexer().getLoc();
2563 if (parseAbsoluteExpression(NumValues))
2566 if (NumValues < 0) {
2568 "'.fill' directive with negative repeat count has no effect");
2572 int64_t FillSize = 1;
2573 int64_t FillExpr = 0;
2575 SMLoc SizeLoc, ExprLoc;
2576 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2577 if (getLexer().isNot(AsmToken::Comma))
2578 return TokError("unexpected token in '.fill' directive");
2581 SizeLoc = getLexer().getLoc();
2582 if (parseAbsoluteExpression(FillSize))
2585 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2586 if (getLexer().isNot(AsmToken::Comma))
2587 return TokError("unexpected token in '.fill' directive");
2590 ExprLoc = getLexer().getLoc();
2591 if (parseAbsoluteExpression(FillExpr))
2594 if (getLexer().isNot(AsmToken::EndOfStatement))
2595 return TokError("unexpected token in '.fill' directive");
2602 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2606 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2610 if (!isUInt<32>(FillExpr) && FillSize > 4)
2611 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2613 if (NumValues > 0) {
2614 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2615 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2616 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2617 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2618 if (NonZeroFillSize < FillSize)
2619 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2626 /// parseDirectiveOrg
2627 /// ::= .org expression [ , expression ]
2628 bool AsmParser::parseDirectiveOrg() {
2629 checkForValidSection();
2631 const MCExpr *Offset;
2632 SMLoc Loc = getTok().getLoc();
2633 if (parseExpression(Offset))
2636 // Parse optional fill expression.
2637 int64_t FillExpr = 0;
2638 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2639 if (getLexer().isNot(AsmToken::Comma))
2640 return TokError("unexpected token in '.org' directive");
2643 if (parseAbsoluteExpression(FillExpr))
2646 if (getLexer().isNot(AsmToken::EndOfStatement))
2647 return TokError("unexpected token in '.org' directive");
2652 // Only limited forms of relocatable expressions are accepted here, it
2653 // has to be relative to the current section. The streamer will return
2654 // 'true' if the expression wasn't evaluatable.
2655 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2656 return Error(Loc, "expected assembly-time absolute expression");
2661 /// parseDirectiveAlign
2662 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2663 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2664 checkForValidSection();
2666 SMLoc AlignmentLoc = getLexer().getLoc();
2668 if (parseAbsoluteExpression(Alignment))
2672 bool HasFillExpr = false;
2673 int64_t FillExpr = 0;
2674 int64_t MaxBytesToFill = 0;
2675 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2676 if (getLexer().isNot(AsmToken::Comma))
2677 return TokError("unexpected token in directive");
2680 // The fill expression can be omitted while specifying a maximum number of
2681 // alignment bytes, e.g:
2683 if (getLexer().isNot(AsmToken::Comma)) {
2685 if (parseAbsoluteExpression(FillExpr))
2689 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2690 if (getLexer().isNot(AsmToken::Comma))
2691 return TokError("unexpected token in directive");
2694 MaxBytesLoc = getLexer().getLoc();
2695 if (parseAbsoluteExpression(MaxBytesToFill))
2698 if (getLexer().isNot(AsmToken::EndOfStatement))
2699 return TokError("unexpected token in directive");
2708 // Compute alignment in bytes.
2710 // FIXME: Diagnose overflow.
2711 if (Alignment >= 32) {
2712 Error(AlignmentLoc, "invalid alignment value");
2716 Alignment = 1ULL << Alignment;
2718 // Reject alignments that aren't a power of two, for gas compatibility.
2719 if (!isPowerOf2_64(Alignment))
2720 Error(AlignmentLoc, "alignment must be a power of 2");
2723 // Diagnose non-sensical max bytes to align.
2724 if (MaxBytesLoc.isValid()) {
2725 if (MaxBytesToFill < 1) {
2726 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2727 "many bytes, ignoring maximum bytes expression");
2731 if (MaxBytesToFill >= Alignment) {
2732 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2738 // Check whether we should use optimal code alignment for this .align
2740 const MCSection *Section = getStreamer().getCurrentSection().first;
2741 assert(Section && "must have section to emit alignment");
2742 bool UseCodeAlign = Section->UseCodeAlign();
2743 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2744 ValueSize == 1 && UseCodeAlign) {
2745 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2747 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2748 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2755 /// parseDirectiveFile
2756 /// ::= .file [number] filename
2757 /// ::= .file number directory filename
2758 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2759 // FIXME: I'm not sure what this is.
2760 int64_t FileNumber = -1;
2761 SMLoc FileNumberLoc = getLexer().getLoc();
2762 if (getLexer().is(AsmToken::Integer)) {
2763 FileNumber = getTok().getIntVal();
2767 return TokError("file number less than one");
2770 if (getLexer().isNot(AsmToken::String))
2771 return TokError("unexpected token in '.file' directive");
2773 // Usually the directory and filename together, otherwise just the directory.
2774 // Allow the strings to have escaped octal character sequence.
2775 std::string Path = getTok().getString();
2776 if (parseEscapedString(Path))
2780 StringRef Directory;
2782 std::string FilenameData;
2783 if (getLexer().is(AsmToken::String)) {
2784 if (FileNumber == -1)
2785 return TokError("explicit path specified, but no file number");
2786 if (parseEscapedString(FilenameData))
2788 Filename = FilenameData;
2795 if (getLexer().isNot(AsmToken::EndOfStatement))
2796 return TokError("unexpected token in '.file' directive");
2798 if (FileNumber == -1)
2799 getStreamer().EmitFileDirective(Filename);
2801 if (getContext().getGenDwarfForAssembly() == true)
2803 "input can't have .file dwarf directives when -g is "
2804 "used to generate dwarf debug info for assembly code");
2806 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2808 Error(FileNumberLoc, "file number already allocated");
2814 /// parseDirectiveLine
2815 /// ::= .line [number]
2816 bool AsmParser::parseDirectiveLine() {
2817 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2818 if (getLexer().isNot(AsmToken::Integer))
2819 return TokError("unexpected token in '.line' directive");
2821 int64_t LineNumber = getTok().getIntVal();
2825 // FIXME: Do something with the .line.
2828 if (getLexer().isNot(AsmToken::EndOfStatement))
2829 return TokError("unexpected token in '.line' directive");
2834 /// parseDirectiveLoc
2835 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2836 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2837 /// The first number is a file number, must have been previously assigned with
2838 /// a .file directive, the second number is the line number and optionally the
2839 /// third number is a column position (zero if not specified). The remaining
2840 /// optional items are .loc sub-directives.
2841 bool AsmParser::parseDirectiveLoc() {
2842 if (getLexer().isNot(AsmToken::Integer))
2843 return TokError("unexpected token in '.loc' directive");
2844 int64_t FileNumber = getTok().getIntVal();
2846 return TokError("file number less than one in '.loc' directive");
2847 if (!getContext().isValidDwarfFileNumber(FileNumber))
2848 return TokError("unassigned file number in '.loc' directive");
2851 int64_t LineNumber = 0;
2852 if (getLexer().is(AsmToken::Integer)) {
2853 LineNumber = getTok().getIntVal();
2855 return TokError("line number less than zero in '.loc' directive");
2859 int64_t ColumnPos = 0;
2860 if (getLexer().is(AsmToken::Integer)) {
2861 ColumnPos = getTok().getIntVal();
2863 return TokError("column position less than zero in '.loc' directive");
2867 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2869 int64_t Discriminator = 0;
2870 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2872 if (getLexer().is(AsmToken::EndOfStatement))
2876 SMLoc Loc = getTok().getLoc();
2877 if (parseIdentifier(Name))
2878 return TokError("unexpected token in '.loc' directive");
2880 if (Name == "basic_block")
2881 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2882 else if (Name == "prologue_end")
2883 Flags |= DWARF2_FLAG_PROLOGUE_END;
2884 else if (Name == "epilogue_begin")
2885 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2886 else if (Name == "is_stmt") {
2887 Loc = getTok().getLoc();
2888 const MCExpr *Value;
2889 if (parseExpression(Value))
2891 // The expression must be the constant 0 or 1.
2892 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2893 int Value = MCE->getValue();
2895 Flags &= ~DWARF2_FLAG_IS_STMT;
2896 else if (Value == 1)
2897 Flags |= DWARF2_FLAG_IS_STMT;
2899 return Error(Loc, "is_stmt value not 0 or 1");
2901 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2903 } else if (Name == "isa") {
2904 Loc = getTok().getLoc();
2905 const MCExpr *Value;
2906 if (parseExpression(Value))
2908 // The expression must be a constant greater or equal to 0.
2909 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2910 int Value = MCE->getValue();
2912 return Error(Loc, "isa number less than zero");
2915 return Error(Loc, "isa number not a constant value");
2917 } else if (Name == "discriminator") {
2918 if (parseAbsoluteExpression(Discriminator))
2921 return Error(Loc, "unknown sub-directive in '.loc' directive");
2924 if (getLexer().is(AsmToken::EndOfStatement))
2929 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2930 Isa, Discriminator, StringRef());
2935 /// parseDirectiveStabs
2936 /// ::= .stabs string, number, number, number
2937 bool AsmParser::parseDirectiveStabs() {
2938 return TokError("unsupported directive '.stabs'");
2941 /// parseDirectiveCFISections
2942 /// ::= .cfi_sections section [, section]
2943 bool AsmParser::parseDirectiveCFISections() {
2948 if (parseIdentifier(Name))
2949 return TokError("Expected an identifier");
2951 if (Name == ".eh_frame")
2953 else if (Name == ".debug_frame")
2956 if (getLexer().is(AsmToken::Comma)) {
2959 if (parseIdentifier(Name))
2960 return TokError("Expected an identifier");
2962 if (Name == ".eh_frame")
2964 else if (Name == ".debug_frame")
2968 getStreamer().EmitCFISections(EH, Debug);
2972 /// parseDirectiveCFIStartProc
2973 /// ::= .cfi_startproc [simple]
2974 bool AsmParser::parseDirectiveCFIStartProc() {
2976 if (getLexer().isNot(AsmToken::EndOfStatement))
2977 if (parseIdentifier(Simple) || Simple != "simple")
2978 return TokError("unexpected token in .cfi_startproc directive");
2980 getStreamer().EmitCFIStartProc(!Simple.empty());
2984 /// parseDirectiveCFIEndProc
2985 /// ::= .cfi_endproc
2986 bool AsmParser::parseDirectiveCFIEndProc() {
2987 getStreamer().EmitCFIEndProc();
2991 /// \brief parse register name or number.
2992 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2993 SMLoc DirectiveLoc) {
2996 if (getLexer().isNot(AsmToken::Integer)) {
2997 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2999 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
3001 return parseAbsoluteExpression(Register);
3006 /// parseDirectiveCFIDefCfa
3007 /// ::= .cfi_def_cfa register, offset
3008 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3009 int64_t Register = 0;
3010 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3013 if (getLexer().isNot(AsmToken::Comma))
3014 return TokError("unexpected token in directive");
3018 if (parseAbsoluteExpression(Offset))
3021 getStreamer().EmitCFIDefCfa(Register, Offset);
3025 /// parseDirectiveCFIDefCfaOffset
3026 /// ::= .cfi_def_cfa_offset offset
3027 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3029 if (parseAbsoluteExpression(Offset))
3032 getStreamer().EmitCFIDefCfaOffset(Offset);
3036 /// parseDirectiveCFIRegister
3037 /// ::= .cfi_register register, register
3038 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3039 int64_t Register1 = 0;
3040 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3043 if (getLexer().isNot(AsmToken::Comma))
3044 return TokError("unexpected token in directive");
3047 int64_t Register2 = 0;
3048 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3051 getStreamer().EmitCFIRegister(Register1, Register2);
3055 /// parseDirectiveCFIWindowSave
3056 /// ::= .cfi_window_save
3057 bool AsmParser::parseDirectiveCFIWindowSave() {
3058 getStreamer().EmitCFIWindowSave();
3062 /// parseDirectiveCFIAdjustCfaOffset
3063 /// ::= .cfi_adjust_cfa_offset adjustment
3064 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3065 int64_t Adjustment = 0;
3066 if (parseAbsoluteExpression(Adjustment))
3069 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3073 /// parseDirectiveCFIDefCfaRegister
3074 /// ::= .cfi_def_cfa_register register
3075 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3076 int64_t Register = 0;
3077 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3080 getStreamer().EmitCFIDefCfaRegister(Register);
3084 /// parseDirectiveCFIOffset
3085 /// ::= .cfi_offset register, offset
3086 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3087 int64_t Register = 0;
3090 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3093 if (getLexer().isNot(AsmToken::Comma))
3094 return TokError("unexpected token in directive");
3097 if (parseAbsoluteExpression(Offset))
3100 getStreamer().EmitCFIOffset(Register, Offset);
3104 /// parseDirectiveCFIRelOffset
3105 /// ::= .cfi_rel_offset register, offset
3106 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3107 int64_t Register = 0;
3109 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3112 if (getLexer().isNot(AsmToken::Comma))
3113 return TokError("unexpected token in directive");
3117 if (parseAbsoluteExpression(Offset))
3120 getStreamer().EmitCFIRelOffset(Register, Offset);
3124 static bool isValidEncoding(int64_t Encoding) {
3125 if (Encoding & ~0xff)
3128 if (Encoding == dwarf::DW_EH_PE_omit)
3131 const unsigned Format = Encoding & 0xf;
3132 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3133 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3134 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3135 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3138 const unsigned Application = Encoding & 0x70;
3139 if (Application != dwarf::DW_EH_PE_absptr &&
3140 Application != dwarf::DW_EH_PE_pcrel)
3146 /// parseDirectiveCFIPersonalityOrLsda
3147 /// IsPersonality true for cfi_personality, false for cfi_lsda
3148 /// ::= .cfi_personality encoding, [symbol_name]
3149 /// ::= .cfi_lsda encoding, [symbol_name]
3150 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3151 int64_t Encoding = 0;
3152 if (parseAbsoluteExpression(Encoding))
3154 if (Encoding == dwarf::DW_EH_PE_omit)
3157 if (!isValidEncoding(Encoding))
3158 return TokError("unsupported encoding.");
3160 if (getLexer().isNot(AsmToken::Comma))
3161 return TokError("unexpected token in directive");
3165 if (parseIdentifier(Name))
3166 return TokError("expected identifier in directive");
3168 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3171 getStreamer().EmitCFIPersonality(Sym, Encoding);
3173 getStreamer().EmitCFILsda(Sym, Encoding);
3177 /// parseDirectiveCFIRememberState
3178 /// ::= .cfi_remember_state
3179 bool AsmParser::parseDirectiveCFIRememberState() {
3180 getStreamer().EmitCFIRememberState();
3184 /// parseDirectiveCFIRestoreState
3185 /// ::= .cfi_remember_state
3186 bool AsmParser::parseDirectiveCFIRestoreState() {
3187 getStreamer().EmitCFIRestoreState();
3191 /// parseDirectiveCFISameValue
3192 /// ::= .cfi_same_value register
3193 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3194 int64_t Register = 0;
3196 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3199 getStreamer().EmitCFISameValue(Register);
3203 /// parseDirectiveCFIRestore
3204 /// ::= .cfi_restore register
3205 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3206 int64_t Register = 0;
3207 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3210 getStreamer().EmitCFIRestore(Register);
3214 /// parseDirectiveCFIEscape
3215 /// ::= .cfi_escape expression[,...]
3216 bool AsmParser::parseDirectiveCFIEscape() {
3219 if (parseAbsoluteExpression(CurrValue))
3222 Values.push_back((uint8_t)CurrValue);
3224 while (getLexer().is(AsmToken::Comma)) {
3227 if (parseAbsoluteExpression(CurrValue))
3230 Values.push_back((uint8_t)CurrValue);
3233 getStreamer().EmitCFIEscape(Values);
3237 /// parseDirectiveCFISignalFrame
3238 /// ::= .cfi_signal_frame
3239 bool AsmParser::parseDirectiveCFISignalFrame() {
3240 if (getLexer().isNot(AsmToken::EndOfStatement))
3241 return Error(getLexer().getLoc(),
3242 "unexpected token in '.cfi_signal_frame'");
3244 getStreamer().EmitCFISignalFrame();
3248 /// parseDirectiveCFIUndefined
3249 /// ::= .cfi_undefined register
3250 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3251 int64_t Register = 0;
3253 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3256 getStreamer().EmitCFIUndefined(Register);
3260 /// parseDirectiveMacrosOnOff
3263 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3264 if (getLexer().isNot(AsmToken::EndOfStatement))
3265 return Error(getLexer().getLoc(),
3266 "unexpected token in '" + Directive + "' directive");
3268 setMacrosEnabled(Directive == ".macros_on");
3272 /// parseDirectiveMacro
3273 /// ::= .macro name[,] [parameters]
3274 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3276 if (parseIdentifier(Name))
3277 return TokError("expected identifier in '.macro' directive");
3279 if (getLexer().is(AsmToken::Comma))
3282 MCAsmMacroParameters Parameters;
3283 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3285 if (Parameters.size() && Parameters.back().Vararg)
3286 return Error(Lexer.getLoc(),
3287 "Vararg parameter '" + Parameters.back().Name +
3288 "' should be last one in the list of parameters.");
3290 MCAsmMacroParameter Parameter;
3291 if (parseIdentifier(Parameter.Name))
3292 return TokError("expected identifier in '.macro' directive");
3294 if (Lexer.is(AsmToken::Colon)) {
3295 Lex(); // consume ':'
3298 StringRef Qualifier;
3300 QualLoc = Lexer.getLoc();
3301 if (parseIdentifier(Qualifier))
3302 return Error(QualLoc, "missing parameter qualifier for "
3303 "'" + Parameter.Name + "' in macro '" + Name + "'");
3305 if (Qualifier == "req")
3306 Parameter.Required = true;
3307 else if (Qualifier == "vararg")
3308 Parameter.Vararg = true;
3310 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3311 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3314 if (getLexer().is(AsmToken::Equal)) {
3319 ParamLoc = Lexer.getLoc();
3320 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3323 if (Parameter.Required)
3324 Warning(ParamLoc, "pointless default value for required parameter "
3325 "'" + Parameter.Name + "' in macro '" + Name + "'");
3328 Parameters.push_back(Parameter);
3330 if (getLexer().is(AsmToken::Comma))
3334 // Eat the end of statement.
3337 AsmToken EndToken, StartToken = getTok();
3338 unsigned MacroDepth = 0;
3340 // Lex the macro definition.
3342 // Check whether we have reached the end of the file.
3343 if (getLexer().is(AsmToken::Eof))
3344 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3346 // Otherwise, check whether we have reach the .endmacro.
3347 if (getLexer().is(AsmToken::Identifier)) {
3348 if (getTok().getIdentifier() == ".endm" ||
3349 getTok().getIdentifier() == ".endmacro") {
3350 if (MacroDepth == 0) { // Outermost macro.
3351 EndToken = getTok();
3353 if (getLexer().isNot(AsmToken::EndOfStatement))
3354 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3358 // Otherwise we just found the end of an inner macro.
3361 } else if (getTok().getIdentifier() == ".macro") {
3362 // We allow nested macros. Those aren't instantiated until the outermost
3363 // macro is expanded so just ignore them for now.
3368 // Otherwise, scan til the end of the statement.
3369 eatToEndOfStatement();
3372 if (lookupMacro(Name)) {
3373 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3376 const char *BodyStart = StartToken.getLoc().getPointer();
3377 const char *BodyEnd = EndToken.getLoc().getPointer();
3378 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3379 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3380 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3384 /// checkForBadMacro
3386 /// With the support added for named parameters there may be code out there that
3387 /// is transitioning from positional parameters. In versions of gas that did
3388 /// not support named parameters they would be ignored on the macro definition.
3389 /// But to support both styles of parameters this is not possible so if a macro
3390 /// definition has named parameters but does not use them and has what appears
3391 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3392 /// warning that the positional parameter found in body which have no effect.
3393 /// Hoping the developer will either remove the named parameters from the macro
3394 /// definition so the positional parameters get used if that was what was
3395 /// intended or change the macro to use the named parameters. It is possible
3396 /// this warning will trigger when the none of the named parameters are used
3397 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3398 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3400 ArrayRef<MCAsmMacroParameter> Parameters) {
3401 // If this macro is not defined with named parameters the warning we are
3402 // checking for here doesn't apply.
3403 unsigned NParameters = Parameters.size();
3404 if (NParameters == 0)
3407 bool NamedParametersFound = false;
3408 bool PositionalParametersFound = false;
3410 // Look at the body of the macro for use of both the named parameters and what
3411 // are likely to be positional parameters. This is what expandMacro() is
3412 // doing when it finds the parameters in the body.
3413 while (!Body.empty()) {
3414 // Scan for the next possible parameter.
3415 std::size_t End = Body.size(), Pos = 0;
3416 for (; Pos != End; ++Pos) {
3417 // Check for a substitution or escape.
3418 // This macro is defined with parameters, look for \foo, \bar, etc.
3419 if (Body[Pos] == '\\' && Pos + 1 != End)
3422 // This macro should have parameters, but look for $0, $1, ..., $n too.
3423 if (Body[Pos] != '$' || Pos + 1 == End)
3425 char Next = Body[Pos + 1];
3426 if (Next == '$' || Next == 'n' ||
3427 isdigit(static_cast<unsigned char>(Next)))
3431 // Check if we reached the end.
3435 if (Body[Pos] == '$') {
3436 switch (Body[Pos + 1]) {
3441 // $n => number of arguments
3443 PositionalParametersFound = true;
3446 // $[0-9] => argument
3448 PositionalParametersFound = true;
3454 unsigned I = Pos + 1;
3455 while (isIdentifierChar(Body[I]) && I + 1 != End)
3458 const char *Begin = Body.data() + Pos + 1;
3459 StringRef Argument(Begin, I - (Pos + 1));
3461 for (; Index < NParameters; ++Index)
3462 if (Parameters[Index].Name == Argument)
3465 if (Index == NParameters) {
3466 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3472 NamedParametersFound = true;
3473 Pos += 1 + Argument.size();
3476 // Update the scan point.
3477 Body = Body.substr(Pos);
3480 if (!NamedParametersFound && PositionalParametersFound)
3481 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3482 "used in macro body, possible positional parameter "
3483 "found in body which will have no effect");
3486 /// parseDirectiveExitMacro
3488 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3489 if (getLexer().isNot(AsmToken::EndOfStatement))
3490 return TokError("unexpected token in '" + Directive + "' directive");
3492 if (!isInsideMacroInstantiation())
3493 return TokError("unexpected '" + Directive + "' in file, "
3494 "no current macro definition");
3496 // Exit all conditionals that are active in the current macro.
3497 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3498 TheCondState = TheCondStack.back();
3499 TheCondStack.pop_back();
3506 /// parseDirectiveEndMacro
3509 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3510 if (getLexer().isNot(AsmToken::EndOfStatement))
3511 return TokError("unexpected token in '" + Directive + "' directive");
3513 // If we are inside a macro instantiation, terminate the current
3515 if (isInsideMacroInstantiation()) {
3520 // Otherwise, this .endmacro is a stray entry in the file; well formed
3521 // .endmacro directives are handled during the macro definition parsing.
3522 return TokError("unexpected '" + Directive + "' in file, "
3523 "no current macro definition");
3526 /// parseDirectivePurgeMacro
3528 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3530 if (parseIdentifier(Name))
3531 return TokError("expected identifier in '.purgem' directive");
3533 if (getLexer().isNot(AsmToken::EndOfStatement))
3534 return TokError("unexpected token in '.purgem' directive");
3536 if (!lookupMacro(Name))
3537 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3539 undefineMacro(Name);
3543 /// parseDirectiveBundleAlignMode
3544 /// ::= {.bundle_align_mode} expression
3545 bool AsmParser::parseDirectiveBundleAlignMode() {
3546 checkForValidSection();
3548 // Expect a single argument: an expression that evaluates to a constant
3549 // in the inclusive range 0-30.
3550 SMLoc ExprLoc = getLexer().getLoc();
3551 int64_t AlignSizePow2;
3552 if (parseAbsoluteExpression(AlignSizePow2))
3554 else if (getLexer().isNot(AsmToken::EndOfStatement))
3555 return TokError("unexpected token after expression in"
3556 " '.bundle_align_mode' directive");
3557 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3558 return Error(ExprLoc,
3559 "invalid bundle alignment size (expected between 0 and 30)");
3563 // Because of AlignSizePow2's verified range we can safely truncate it to
3565 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3569 /// parseDirectiveBundleLock
3570 /// ::= {.bundle_lock} [align_to_end]
3571 bool AsmParser::parseDirectiveBundleLock() {
3572 checkForValidSection();
3573 bool AlignToEnd = false;
3575 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3577 SMLoc Loc = getTok().getLoc();
3578 const char *kInvalidOptionError =
3579 "invalid option for '.bundle_lock' directive";
3581 if (parseIdentifier(Option))
3582 return Error(Loc, kInvalidOptionError);
3584 if (Option != "align_to_end")
3585 return Error(Loc, kInvalidOptionError);
3586 else if (getLexer().isNot(AsmToken::EndOfStatement))
3588 "unexpected token after '.bundle_lock' directive option");
3594 getStreamer().EmitBundleLock(AlignToEnd);
3598 /// parseDirectiveBundleLock
3599 /// ::= {.bundle_lock}
3600 bool AsmParser::parseDirectiveBundleUnlock() {
3601 checkForValidSection();
3603 if (getLexer().isNot(AsmToken::EndOfStatement))
3604 return TokError("unexpected token in '.bundle_unlock' directive");
3607 getStreamer().EmitBundleUnlock();
3611 /// parseDirectiveSpace
3612 /// ::= (.skip | .space) expression [ , expression ]
3613 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3614 checkForValidSection();
3617 if (parseAbsoluteExpression(NumBytes))
3620 int64_t FillExpr = 0;
3621 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3622 if (getLexer().isNot(AsmToken::Comma))
3623 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3626 if (parseAbsoluteExpression(FillExpr))
3629 if (getLexer().isNot(AsmToken::EndOfStatement))
3630 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3636 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3639 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3640 getStreamer().EmitFill(NumBytes, FillExpr);
3645 /// parseDirectiveLEB128
3646 /// ::= (.sleb128 | .uleb128) expression
3647 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3648 checkForValidSection();
3649 const MCExpr *Value;
3651 if (parseExpression(Value))
3654 if (getLexer().isNot(AsmToken::EndOfStatement))
3655 return TokError("unexpected token in directive");
3658 getStreamer().EmitSLEB128Value(Value);
3660 getStreamer().EmitULEB128Value(Value);
3665 /// parseDirectiveSymbolAttribute
3666 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3667 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3668 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3671 SMLoc Loc = getTok().getLoc();
3673 if (parseIdentifier(Name))
3674 return Error(Loc, "expected identifier in directive");
3676 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3678 // Assembler local symbols don't make any sense here. Complain loudly.
3679 if (Sym->isTemporary())
3680 return Error(Loc, "non-local symbol required in directive");
3682 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3683 return Error(Loc, "unable to emit symbol attribute");
3685 if (getLexer().is(AsmToken::EndOfStatement))
3688 if (getLexer().isNot(AsmToken::Comma))
3689 return TokError("unexpected token in directive");
3698 /// parseDirectiveComm
3699 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3700 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3701 checkForValidSection();
3703 SMLoc IDLoc = getLexer().getLoc();
3705 if (parseIdentifier(Name))
3706 return TokError("expected identifier in directive");
3708 // Handle the identifier as the key symbol.
3709 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3711 if (getLexer().isNot(AsmToken::Comma))
3712 return TokError("unexpected token in directive");
3716 SMLoc SizeLoc = getLexer().getLoc();
3717 if (parseAbsoluteExpression(Size))
3720 int64_t Pow2Alignment = 0;
3721 SMLoc Pow2AlignmentLoc;
3722 if (getLexer().is(AsmToken::Comma)) {
3724 Pow2AlignmentLoc = getLexer().getLoc();
3725 if (parseAbsoluteExpression(Pow2Alignment))
3728 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3729 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3730 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3732 // If this target takes alignments in bytes (not log) validate and convert.
3733 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3734 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3735 if (!isPowerOf2_64(Pow2Alignment))
3736 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3737 Pow2Alignment = Log2_64(Pow2Alignment);
3741 if (getLexer().isNot(AsmToken::EndOfStatement))
3742 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3746 // NOTE: a size of zero for a .comm should create a undefined symbol
3747 // but a size of .lcomm creates a bss symbol of size zero.
3749 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3750 "be less than zero");
3752 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3753 // may internally end up wanting an alignment in bytes.
3754 // FIXME: Diagnose overflow.
3755 if (Pow2Alignment < 0)
3756 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3757 "alignment, can't be less than zero");
3759 if (!Sym->isUndefined())
3760 return Error(IDLoc, "invalid symbol redefinition");
3762 // Create the Symbol as a common or local common with Size and Pow2Alignment
3764 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3768 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3772 /// parseDirectiveAbort
3773 /// ::= .abort [... message ...]
3774 bool AsmParser::parseDirectiveAbort() {
3775 // FIXME: Use loc from directive.
3776 SMLoc Loc = getLexer().getLoc();
3778 StringRef Str = parseStringToEndOfStatement();
3779 if (getLexer().isNot(AsmToken::EndOfStatement))
3780 return TokError("unexpected token in '.abort' directive");
3785 Error(Loc, ".abort detected. Assembly stopping.");
3787 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3788 // FIXME: Actually abort assembly here.
3793 /// parseDirectiveInclude
3794 /// ::= .include "filename"
3795 bool AsmParser::parseDirectiveInclude() {
3796 if (getLexer().isNot(AsmToken::String))
3797 return TokError("expected string in '.include' directive");
3799 // Allow the strings to have escaped octal character sequence.
3800 std::string Filename;
3801 if (parseEscapedString(Filename))
3803 SMLoc IncludeLoc = getLexer().getLoc();
3806 if (getLexer().isNot(AsmToken::EndOfStatement))
3807 return TokError("unexpected token in '.include' directive");
3809 // Attempt to switch the lexer to the included file before consuming the end
3810 // of statement to avoid losing it when we switch.
3811 if (enterIncludeFile(Filename)) {
3812 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3819 /// parseDirectiveIncbin
3820 /// ::= .incbin "filename"
3821 bool AsmParser::parseDirectiveIncbin() {
3822 if (getLexer().isNot(AsmToken::String))
3823 return TokError("expected string in '.incbin' directive");
3825 // Allow the strings to have escaped octal character sequence.
3826 std::string Filename;
3827 if (parseEscapedString(Filename))
3829 SMLoc IncbinLoc = getLexer().getLoc();
3832 if (getLexer().isNot(AsmToken::EndOfStatement))
3833 return TokError("unexpected token in '.incbin' directive");
3835 // Attempt to process the included file.
3836 if (processIncbinFile(Filename)) {
3837 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3844 /// parseDirectiveIf
3845 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
3846 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
3847 TheCondStack.push_back(TheCondState);
3848 TheCondState.TheCond = AsmCond::IfCond;
3849 if (TheCondState.Ignore) {
3850 eatToEndOfStatement();
3853 if (parseAbsoluteExpression(ExprValue))
3856 if (getLexer().isNot(AsmToken::EndOfStatement))
3857 return TokError("unexpected token in '.if' directive");
3863 llvm_unreachable("unsupported directive");
3868 ExprValue = ExprValue == 0;
3871 ExprValue = ExprValue >= 0;
3874 ExprValue = ExprValue > 0;
3877 ExprValue = ExprValue <= 0;
3880 ExprValue = ExprValue < 0;
3884 TheCondState.CondMet = ExprValue;
3885 TheCondState.Ignore = !TheCondState.CondMet;
3891 /// parseDirectiveIfb
3893 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3894 TheCondStack.push_back(TheCondState);
3895 TheCondState.TheCond = AsmCond::IfCond;
3897 if (TheCondState.Ignore) {
3898 eatToEndOfStatement();
3900 StringRef Str = parseStringToEndOfStatement();
3902 if (getLexer().isNot(AsmToken::EndOfStatement))
3903 return TokError("unexpected token in '.ifb' directive");
3907 TheCondState.CondMet = ExpectBlank == Str.empty();
3908 TheCondState.Ignore = !TheCondState.CondMet;
3914 /// parseDirectiveIfc
3915 /// ::= .ifc string1, string2
3916 /// ::= .ifnc string1, string2
3917 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3918 TheCondStack.push_back(TheCondState);
3919 TheCondState.TheCond = AsmCond::IfCond;
3921 if (TheCondState.Ignore) {
3922 eatToEndOfStatement();
3924 StringRef Str1 = parseStringToComma();
3926 if (getLexer().isNot(AsmToken::Comma))
3927 return TokError("unexpected token in '.ifc' directive");
3931 StringRef Str2 = parseStringToEndOfStatement();
3933 if (getLexer().isNot(AsmToken::EndOfStatement))
3934 return TokError("unexpected token in '.ifc' directive");
3938 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3939 TheCondState.Ignore = !TheCondState.CondMet;
3945 /// parseDirectiveIfeqs
3946 /// ::= .ifeqs string1, string2
3947 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc) {
3948 if (Lexer.isNot(AsmToken::String)) {
3949 TokError("expected string parameter for '.ifeqs' directive");
3950 eatToEndOfStatement();
3954 StringRef String1 = getTok().getStringContents();
3957 if (Lexer.isNot(AsmToken::Comma)) {
3958 TokError("expected comma after first string for '.ifeqs' directive");
3959 eatToEndOfStatement();
3965 if (Lexer.isNot(AsmToken::String)) {
3966 TokError("expected string parameter for '.ifeqs' directive");
3967 eatToEndOfStatement();
3971 StringRef String2 = getTok().getStringContents();
3974 TheCondStack.push_back(TheCondState);
3975 TheCondState.TheCond = AsmCond::IfCond;
3976 TheCondState.CondMet = String1 == String2;
3977 TheCondState.Ignore = !TheCondState.CondMet;
3982 /// parseDirectiveIfdef
3983 /// ::= .ifdef symbol
3984 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3986 TheCondStack.push_back(TheCondState);
3987 TheCondState.TheCond = AsmCond::IfCond;
3989 if (TheCondState.Ignore) {
3990 eatToEndOfStatement();
3992 if (parseIdentifier(Name))
3993 return TokError("expected identifier after '.ifdef'");
3997 MCSymbol *Sym = getContext().LookupSymbol(Name);
4000 TheCondState.CondMet = (Sym && !Sym->isUndefined());
4002 TheCondState.CondMet = (!Sym || Sym->isUndefined());
4003 TheCondState.Ignore = !TheCondState.CondMet;
4009 /// parseDirectiveElseIf
4010 /// ::= .elseif expression
4011 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4012 if (TheCondState.TheCond != AsmCond::IfCond &&
4013 TheCondState.TheCond != AsmCond::ElseIfCond)
4014 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4016 TheCondState.TheCond = AsmCond::ElseIfCond;
4018 bool LastIgnoreState = false;
4019 if (!TheCondStack.empty())
4020 LastIgnoreState = TheCondStack.back().Ignore;
4021 if (LastIgnoreState || TheCondState.CondMet) {
4022 TheCondState.Ignore = true;
4023 eatToEndOfStatement();
4026 if (parseAbsoluteExpression(ExprValue))
4029 if (getLexer().isNot(AsmToken::EndOfStatement))
4030 return TokError("unexpected token in '.elseif' directive");
4033 TheCondState.CondMet = ExprValue;
4034 TheCondState.Ignore = !TheCondState.CondMet;
4040 /// parseDirectiveElse
4042 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4043 if (getLexer().isNot(AsmToken::EndOfStatement))
4044 return TokError("unexpected token in '.else' directive");
4048 if (TheCondState.TheCond != AsmCond::IfCond &&
4049 TheCondState.TheCond != AsmCond::ElseIfCond)
4050 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4052 TheCondState.TheCond = AsmCond::ElseCond;
4053 bool LastIgnoreState = false;
4054 if (!TheCondStack.empty())
4055 LastIgnoreState = TheCondStack.back().Ignore;
4056 if (LastIgnoreState || TheCondState.CondMet)
4057 TheCondState.Ignore = true;
4059 TheCondState.Ignore = false;
4064 /// parseDirectiveEnd
4066 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4067 if (getLexer().isNot(AsmToken::EndOfStatement))
4068 return TokError("unexpected token in '.end' directive");
4072 while (Lexer.isNot(AsmToken::Eof))
4078 /// parseDirectiveError
4080 /// ::= .error [string]
4081 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4082 if (!TheCondStack.empty()) {
4083 if (TheCondStack.back().Ignore) {
4084 eatToEndOfStatement();
4090 return Error(L, ".err encountered");
4092 StringRef Message = ".error directive invoked in source file";
4093 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4094 if (Lexer.isNot(AsmToken::String)) {
4095 TokError(".error argument must be a string");
4096 eatToEndOfStatement();
4100 Message = getTok().getStringContents();
4108 /// parseDirectiveWarning
4109 /// ::= .warning [string]
4110 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4111 if (!TheCondStack.empty()) {
4112 if (TheCondStack.back().Ignore) {
4113 eatToEndOfStatement();
4118 StringRef Message = ".warning directive invoked in source file";
4119 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4120 if (Lexer.isNot(AsmToken::String)) {
4121 TokError(".warning argument must be a string");
4122 eatToEndOfStatement();
4126 Message = getTok().getStringContents();
4130 Warning(L, Message);
4134 /// parseDirectiveEndIf
4136 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4137 if (getLexer().isNot(AsmToken::EndOfStatement))
4138 return TokError("unexpected token in '.endif' directive");
4142 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4143 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4145 if (!TheCondStack.empty()) {
4146 TheCondState = TheCondStack.back();
4147 TheCondStack.pop_back();
4153 void AsmParser::initializeDirectiveKindMap() {
4154 DirectiveKindMap[".set"] = DK_SET;
4155 DirectiveKindMap[".equ"] = DK_EQU;
4156 DirectiveKindMap[".equiv"] = DK_EQUIV;
4157 DirectiveKindMap[".ascii"] = DK_ASCII;
4158 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4159 DirectiveKindMap[".string"] = DK_STRING;
4160 DirectiveKindMap[".byte"] = DK_BYTE;
4161 DirectiveKindMap[".short"] = DK_SHORT;
4162 DirectiveKindMap[".value"] = DK_VALUE;
4163 DirectiveKindMap[".2byte"] = DK_2BYTE;
4164 DirectiveKindMap[".long"] = DK_LONG;
4165 DirectiveKindMap[".int"] = DK_INT;
4166 DirectiveKindMap[".4byte"] = DK_4BYTE;
4167 DirectiveKindMap[".quad"] = DK_QUAD;
4168 DirectiveKindMap[".8byte"] = DK_8BYTE;
4169 DirectiveKindMap[".octa"] = DK_OCTA;
4170 DirectiveKindMap[".single"] = DK_SINGLE;
4171 DirectiveKindMap[".float"] = DK_FLOAT;
4172 DirectiveKindMap[".double"] = DK_DOUBLE;
4173 DirectiveKindMap[".align"] = DK_ALIGN;
4174 DirectiveKindMap[".align32"] = DK_ALIGN32;
4175 DirectiveKindMap[".balign"] = DK_BALIGN;
4176 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4177 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4178 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4179 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4180 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4181 DirectiveKindMap[".org"] = DK_ORG;
4182 DirectiveKindMap[".fill"] = DK_FILL;
4183 DirectiveKindMap[".zero"] = DK_ZERO;
4184 DirectiveKindMap[".extern"] = DK_EXTERN;
4185 DirectiveKindMap[".globl"] = DK_GLOBL;
4186 DirectiveKindMap[".global"] = DK_GLOBAL;
4187 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4188 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4189 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4190 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4191 DirectiveKindMap[".reference"] = DK_REFERENCE;
4192 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4193 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4194 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4195 DirectiveKindMap[".comm"] = DK_COMM;
4196 DirectiveKindMap[".common"] = DK_COMMON;
4197 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4198 DirectiveKindMap[".abort"] = DK_ABORT;
4199 DirectiveKindMap[".include"] = DK_INCLUDE;
4200 DirectiveKindMap[".incbin"] = DK_INCBIN;
4201 DirectiveKindMap[".code16"] = DK_CODE16;
4202 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4203 DirectiveKindMap[".rept"] = DK_REPT;
4204 DirectiveKindMap[".rep"] = DK_REPT;
4205 DirectiveKindMap[".irp"] = DK_IRP;
4206 DirectiveKindMap[".irpc"] = DK_IRPC;
4207 DirectiveKindMap[".endr"] = DK_ENDR;
4208 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4209 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4210 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4211 DirectiveKindMap[".if"] = DK_IF;
4212 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4213 DirectiveKindMap[".ifge"] = DK_IFGE;
4214 DirectiveKindMap[".ifgt"] = DK_IFGT;
4215 DirectiveKindMap[".ifle"] = DK_IFLE;
4216 DirectiveKindMap[".iflt"] = DK_IFLT;
4217 DirectiveKindMap[".ifne"] = DK_IFNE;
4218 DirectiveKindMap[".ifb"] = DK_IFB;
4219 DirectiveKindMap[".ifnb"] = DK_IFNB;
4220 DirectiveKindMap[".ifc"] = DK_IFC;
4221 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4222 DirectiveKindMap[".ifnc"] = DK_IFNC;
4223 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4224 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4225 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4226 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4227 DirectiveKindMap[".else"] = DK_ELSE;
4228 DirectiveKindMap[".end"] = DK_END;
4229 DirectiveKindMap[".endif"] = DK_ENDIF;
4230 DirectiveKindMap[".skip"] = DK_SKIP;
4231 DirectiveKindMap[".space"] = DK_SPACE;
4232 DirectiveKindMap[".file"] = DK_FILE;
4233 DirectiveKindMap[".line"] = DK_LINE;
4234 DirectiveKindMap[".loc"] = DK_LOC;
4235 DirectiveKindMap[".stabs"] = DK_STABS;
4236 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4237 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4238 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4239 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4240 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4241 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4242 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4243 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4244 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4245 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4246 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4247 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4248 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4249 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4250 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4251 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4252 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4253 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4254 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4255 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4256 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4257 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4258 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4259 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4260 DirectiveKindMap[".macro"] = DK_MACRO;
4261 DirectiveKindMap[".exitm"] = DK_EXITM;
4262 DirectiveKindMap[".endm"] = DK_ENDM;
4263 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4264 DirectiveKindMap[".purgem"] = DK_PURGEM;
4265 DirectiveKindMap[".err"] = DK_ERR;
4266 DirectiveKindMap[".error"] = DK_ERROR;
4267 DirectiveKindMap[".warning"] = DK_WARNING;
4270 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4271 AsmToken EndToken, StartToken = getTok();
4273 unsigned NestLevel = 0;
4275 // Check whether we have reached the end of the file.
4276 if (getLexer().is(AsmToken::Eof)) {
4277 Error(DirectiveLoc, "no matching '.endr' in definition");
4281 if (Lexer.is(AsmToken::Identifier) &&
4282 (getTok().getIdentifier() == ".rept")) {
4286 // Otherwise, check whether we have reached the .endr.
4287 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4288 if (NestLevel == 0) {
4289 EndToken = getTok();
4291 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4292 TokError("unexpected token in '.endr' directive");
4300 // Otherwise, scan till the end of the statement.
4301 eatToEndOfStatement();
4304 const char *BodyStart = StartToken.getLoc().getPointer();
4305 const char *BodyEnd = EndToken.getLoc().getPointer();
4306 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4308 // We Are Anonymous.
4309 MacroLikeBodies.push_back(MCAsmMacro(StringRef(), Body, None));
4310 return &MacroLikeBodies.back();
4313 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4314 raw_svector_ostream &OS) {
4317 std::unique_ptr<MemoryBuffer> Instantiation =
4318 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4320 // Create the macro instantiation object and add to the current macro
4321 // instantiation stack.
4322 MacroInstantiation *MI = new MacroInstantiation(
4323 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
4324 ActiveMacros.push_back(MI);
4326 // Jump to the macro instantiation and prime the lexer.
4327 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
4328 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
4332 /// parseDirectiveRept
4333 /// ::= .rep | .rept count
4334 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4335 const MCExpr *CountExpr;
4336 SMLoc CountLoc = getTok().getLoc();
4337 if (parseExpression(CountExpr))
4341 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4342 eatToEndOfStatement();
4343 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4347 return Error(CountLoc, "Count is negative");
4349 if (Lexer.isNot(AsmToken::EndOfStatement))
4350 return TokError("unexpected token in '" + Dir + "' directive");
4352 // Eat the end of statement.
4355 // Lex the rept definition.
4356 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4360 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4361 // to hold the macro body with substitutions.
4362 SmallString<256> Buf;
4363 raw_svector_ostream OS(Buf);
4365 if (expandMacro(OS, M->Body, None, None, getTok().getLoc()))
4368 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4373 /// parseDirectiveIrp
4374 /// ::= .irp symbol,values
4375 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4376 MCAsmMacroParameter Parameter;
4378 if (parseIdentifier(Parameter.Name))
4379 return TokError("expected identifier in '.irp' directive");
4381 if (Lexer.isNot(AsmToken::Comma))
4382 return TokError("expected comma in '.irp' directive");
4386 MCAsmMacroArguments A;
4387 if (parseMacroArguments(nullptr, A))
4390 // Eat the end of statement.
4393 // Lex the irp definition.
4394 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4398 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4399 // to hold the macro body with substitutions.
4400 SmallString<256> Buf;
4401 raw_svector_ostream OS(Buf);
4403 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4404 if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc()))
4408 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4413 /// parseDirectiveIrpc
4414 /// ::= .irpc symbol,values
4415 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4416 MCAsmMacroParameter Parameter;
4418 if (parseIdentifier(Parameter.Name))
4419 return TokError("expected identifier in '.irpc' directive");
4421 if (Lexer.isNot(AsmToken::Comma))
4422 return TokError("expected comma in '.irpc' directive");
4426 MCAsmMacroArguments A;
4427 if (parseMacroArguments(nullptr, A))
4430 if (A.size() != 1 || A.front().size() != 1)
4431 return TokError("unexpected token in '.irpc' directive");
4433 // Eat the end of statement.
4436 // Lex the irpc definition.
4437 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4441 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4442 // to hold the macro body with substitutions.
4443 SmallString<256> Buf;
4444 raw_svector_ostream OS(Buf);
4446 StringRef Values = A.front().front().getString();
4447 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4448 MCAsmMacroArgument Arg;
4449 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4451 if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc()))
4455 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4460 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4461 if (ActiveMacros.empty())
4462 return TokError("unmatched '.endr' directive");
4464 // The only .repl that should get here are the ones created by
4465 // instantiateMacroLikeBody.
4466 assert(getLexer().is(AsmToken::EndOfStatement));
4472 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4474 const MCExpr *Value;
4475 SMLoc ExprLoc = getLexer().getLoc();
4476 if (parseExpression(Value))
4478 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4480 return Error(ExprLoc, "unexpected expression in _emit");
4481 uint64_t IntValue = MCE->getValue();
4482 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4483 return Error(ExprLoc, "literal value out of range for directive");
4485 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4489 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4490 const MCExpr *Value;
4491 SMLoc ExprLoc = getLexer().getLoc();
4492 if (parseExpression(Value))
4494 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4496 return Error(ExprLoc, "unexpected expression in align");
4497 uint64_t IntValue = MCE->getValue();
4498 if (!isPowerOf2_64(IntValue))
4499 return Error(ExprLoc, "literal value not a power of two greater then zero");
4501 Info.AsmRewrites->push_back(
4502 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4506 // We are comparing pointers, but the pointers are relative to a single string.
4507 // Thus, this should always be deterministic.
4508 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4509 const AsmRewrite *AsmRewriteB) {
4510 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4512 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4515 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4516 // rewrite to the same location. Make sure the SizeDirective rewrite is
4517 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4518 // ensures the sort algorithm is stable.
4519 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4520 AsmRewritePrecedence[AsmRewriteB->Kind])
4523 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4524 AsmRewritePrecedence[AsmRewriteB->Kind])
4526 llvm_unreachable("Unstable rewrite sort.");
4529 bool AsmParser::parseMSInlineAsm(
4530 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4531 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4532 SmallVectorImpl<std::string> &Constraints,
4533 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4534 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4535 SmallVector<void *, 4> InputDecls;
4536 SmallVector<void *, 4> OutputDecls;
4537 SmallVector<bool, 4> InputDeclsAddressOf;
4538 SmallVector<bool, 4> OutputDeclsAddressOf;
4539 SmallVector<std::string, 4> InputConstraints;
4540 SmallVector<std::string, 4> OutputConstraints;
4541 SmallVector<unsigned, 4> ClobberRegs;
4543 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4548 // While we have input, parse each statement.
4549 unsigned InputIdx = 0;
4550 unsigned OutputIdx = 0;
4551 while (getLexer().isNot(AsmToken::Eof)) {
4552 ParseStatementInfo Info(&AsmStrRewrites);
4553 if (parseStatement(Info, &SI))
4556 if (Info.ParseError)
4559 if (Info.Opcode == ~0U)
4562 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4564 // Build the list of clobbers, outputs and inputs.
4565 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4566 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4569 if (Operand.isImm())
4572 // Register operand.
4573 if (Operand.isReg() && !Operand.needAddressOf() &&
4574 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
4575 unsigned NumDefs = Desc.getNumDefs();
4577 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4578 ClobberRegs.push_back(Operand.getReg());
4582 // Expr/Input or Output.
4583 StringRef SymName = Operand.getSymName();
4584 if (SymName.empty())
4587 void *OpDecl = Operand.getOpDecl();
4591 bool isOutput = (i == 1) && Desc.mayStore();
4592 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4595 OutputDecls.push_back(OpDecl);
4596 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4597 OutputConstraints.push_back('=' + Operand.getConstraint().str());
4598 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4600 InputDecls.push_back(OpDecl);
4601 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4602 InputConstraints.push_back(Operand.getConstraint().str());
4603 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4607 // Consider implicit defs to be clobbers. Think of cpuid and push.
4608 ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
4609 Desc.getNumImplicitDefs());
4610 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
4613 // Set the number of Outputs and Inputs.
4614 NumOutputs = OutputDecls.size();
4615 NumInputs = InputDecls.size();
4617 // Set the unique clobbers.
4618 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4619 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4621 Clobbers.assign(ClobberRegs.size(), std::string());
4622 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4623 raw_string_ostream OS(Clobbers[I]);
4624 IP->printRegName(OS, ClobberRegs[I]);
4627 // Merge the various outputs and inputs. Output are expected first.
4628 if (NumOutputs || NumInputs) {
4629 unsigned NumExprs = NumOutputs + NumInputs;
4630 OpDecls.resize(NumExprs);
4631 Constraints.resize(NumExprs);
4632 for (unsigned i = 0; i < NumOutputs; ++i) {
4633 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4634 Constraints[i] = OutputConstraints[i];
4636 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4637 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4638 Constraints[j] = InputConstraints[i];
4642 // Build the IR assembly string.
4643 std::string AsmStringIR;
4644 raw_string_ostream OS(AsmStringIR);
4645 StringRef ASMString =
4646 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4647 const char *AsmStart = ASMString.begin();
4648 const char *AsmEnd = ASMString.end();
4649 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4650 for (const AsmRewrite &AR : AsmStrRewrites) {
4651 AsmRewriteKind Kind = AR.Kind;
4652 if (Kind == AOK_Delete)
4655 const char *Loc = AR.Loc.getPointer();
4656 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4658 // Emit everything up to the immediate/expression.
4659 if (unsigned Len = Loc - AsmStart)
4660 OS << StringRef(AsmStart, Len);
4662 // Skip the original expression.
4663 if (Kind == AOK_Skip) {
4664 AsmStart = Loc + AR.Len;
4668 unsigned AdditionalSkip = 0;
4669 // Rewrite expressions in $N notation.
4674 OS << "$$" << AR.Val;
4680 OS << Ctx.getAsmInfo()->getPrivateGlobalPrefix() << AR.Label;
4683 OS << '$' << InputIdx++;
4686 OS << '$' << OutputIdx++;
4688 case AOK_SizeDirective:
4691 case 8: OS << "byte ptr "; break;
4692 case 16: OS << "word ptr "; break;
4693 case 32: OS << "dword ptr "; break;
4694 case 64: OS << "qword ptr "; break;
4695 case 80: OS << "xword ptr "; break;
4696 case 128: OS << "xmmword ptr "; break;
4697 case 256: OS << "ymmword ptr "; break;
4704 unsigned Val = AR.Val;
4705 OS << ".align " << Val;
4707 // Skip the original immediate.
4708 assert(Val < 10 && "Expected alignment less then 2^10.");
4709 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4712 case AOK_DotOperator:
4713 // Insert the dot if the user omitted it.
4715 if (AsmStringIR.back() != '.')
4721 // Skip the original expression.
4722 AsmStart = Loc + AR.Len + AdditionalSkip;
4725 // Emit the remainder of the asm string.
4726 if (AsmStart != AsmEnd)
4727 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4729 AsmString = OS.str();
4733 /// \brief Create an MCAsmParser instance.
4734 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4735 MCStreamer &Out, const MCAsmInfo &MAI) {
4736 return new AsmParser(SM, C, Out, MAI);