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 FatalAssemblerWarnings("fatal-assembler-warnings",
49 cl::desc("Consider warnings as error"));
51 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
54 /// \brief Helper types for tracking macro definitions.
55 typedef std::vector<AsmToken> MCAsmMacroArgument;
56 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
58 struct MCAsmMacroParameter {
60 MCAsmMacroArgument Value;
64 MCAsmMacroParameter() : Required(false), Vararg(false) {}
67 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
72 MCAsmMacroParameters Parameters;
75 MCAsmMacro(StringRef N, StringRef B, ArrayRef<MCAsmMacroParameter> P) :
76 Name(N), Body(B), Parameters(P) {}
79 /// \brief Helper class for storing information about an active macro
81 struct MacroInstantiation {
82 /// The macro being instantiated.
83 const MCAsmMacro *TheMacro;
85 /// The macro instantiation with substitutions.
86 MemoryBuffer *Instantiation;
88 /// The location of the instantiation.
89 SMLoc InstantiationLoc;
91 /// The buffer where parsing should resume upon instantiation completion.
94 /// The location where parsing should resume upon instantiation completion.
98 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
102 struct ParseStatementInfo {
103 /// \brief The parsed operands from the last parsed statement.
104 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
106 /// \brief The opcode from the last parsed instruction.
109 /// \brief Was there an error parsing the inline assembly?
112 SmallVectorImpl<AsmRewrite> *AsmRewrites;
114 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
115 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
116 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
118 ~ParseStatementInfo() {
119 // Free any parsed operands.
120 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
121 delete ParsedOperands[i];
122 ParsedOperands.clear();
126 /// \brief The concrete assembly parser instance.
127 class AsmParser : public MCAsmParser {
128 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
129 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
134 const MCAsmInfo &MAI;
136 SourceMgr::DiagHandlerTy SavedDiagHandler;
137 void *SavedDiagContext;
138 MCAsmParserExtension *PlatformParser;
140 /// This is the current buffer index we're lexing from as managed by the
141 /// SourceMgr object.
144 AsmCond TheCondState;
145 std::vector<AsmCond> TheCondStack;
147 /// \brief maps directive names to handler methods in parser
148 /// extensions. Extensions register themselves in this map by calling
149 /// addDirectiveHandler.
150 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
152 /// \brief Map of currently defined macros.
153 StringMap<MCAsmMacro*> MacroMap;
155 /// \brief Stack of active macro instantiations.
156 std::vector<MacroInstantiation*> ActiveMacros;
158 /// \brief List of bodies of anonymous macros.
159 std::deque<MCAsmMacro> MacroLikeBodies;
161 /// Boolean tracking whether macro substitution is enabled.
162 unsigned MacrosEnabledFlag : 1;
164 /// Flag tracking whether any errors have been encountered.
165 unsigned HadError : 1;
167 /// The values from the last parsed cpp hash file line comment if any.
168 StringRef CppHashFilename;
169 int64_t CppHashLineNumber;
172 /// When generating dwarf for assembly source files we need to calculate the
173 /// logical line number based on the last parsed cpp hash file line comment
174 /// and current line. Since this is slow and messes up the SourceMgr's
175 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
176 SMLoc LastQueryIDLoc;
178 unsigned LastQueryLine;
180 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
181 unsigned AssemblerDialect;
183 /// \brief is Darwin compatibility enabled?
186 /// \brief Are we parsing ms-style inline assembly?
187 bool ParsingInlineAsm;
190 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
191 const MCAsmInfo &MAI);
192 virtual ~AsmParser();
194 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
196 void addDirectiveHandler(StringRef Directive,
197 ExtensionDirectiveHandler Handler) override {
198 ExtensionDirectiveMap[Directive] = Handler;
202 /// @name MCAsmParser Interface
205 SourceMgr &getSourceManager() override { return SrcMgr; }
206 MCAsmLexer &getLexer() override { return Lexer; }
207 MCContext &getContext() override { return Ctx; }
208 MCStreamer &getStreamer() override { return Out; }
209 unsigned getAssemblerDialect() override {
210 if (AssemblerDialect == ~0U)
211 return MAI.getAssemblerDialect();
213 return AssemblerDialect;
215 void setAssemblerDialect(unsigned i) override {
216 AssemblerDialect = i;
219 void Note(SMLoc L, const Twine &Msg,
220 ArrayRef<SMRange> Ranges = None) override;
221 bool Warning(SMLoc L, const Twine &Msg,
222 ArrayRef<SMRange> Ranges = None) override;
223 bool Error(SMLoc L, const Twine &Msg,
224 ArrayRef<SMRange> Ranges = None) override;
226 const AsmToken &Lex() override;
228 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
229 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
231 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
232 unsigned &NumOutputs, unsigned &NumInputs,
233 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
234 SmallVectorImpl<std::string> &Constraints,
235 SmallVectorImpl<std::string> &Clobbers,
236 const MCInstrInfo *MII, const MCInstPrinter *IP,
237 MCAsmParserSemaCallback &SI) override;
239 bool parseExpression(const MCExpr *&Res);
240 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
241 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
242 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
243 bool parseAbsoluteExpression(int64_t &Res) override;
245 /// \brief Parse an identifier or string (as a quoted identifier)
246 /// and set \p Res to the identifier contents.
247 bool parseIdentifier(StringRef &Res) override;
248 void eatToEndOfStatement() override;
250 void checkForValidSection() override;
255 bool parseStatement(ParseStatementInfo &Info);
256 void eatToEndOfLine();
257 bool parseCppHashLineFilenameComment(const SMLoc &L);
259 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
260 ArrayRef<MCAsmMacroParameter> Parameters);
261 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
262 ArrayRef<MCAsmMacroParameter> Parameters,
263 ArrayRef<MCAsmMacroArgument> A,
266 /// \brief Are macros enabled in the parser?
267 bool areMacrosEnabled() {return MacrosEnabledFlag;}
269 /// \brief Control a flag in the parser that enables or disables macros.
270 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
272 /// \brief Lookup a previously defined macro.
273 /// \param Name Macro name.
274 /// \returns Pointer to macro. NULL if no such macro was defined.
275 const MCAsmMacro* lookupMacro(StringRef Name);
277 /// \brief Define a new macro with the given name and information.
278 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
280 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
281 void undefineMacro(StringRef Name);
283 /// \brief Are we inside a macro instantiation?
284 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
286 /// \brief Handle entry to macro instantiation.
288 /// \param M The macro.
289 /// \param NameLoc Instantiation location.
290 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
292 /// \brief Handle exit from macro instantiation.
293 void handleMacroExit();
295 /// \brief Extract AsmTokens for a macro argument.
296 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
298 /// \brief Parse all macro arguments for a given macro.
299 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
301 void printMacroInstantiations();
302 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
303 ArrayRef<SMRange> Ranges = None) const {
304 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
306 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
308 /// \brief Enter the specified file. This returns true on failure.
309 bool enterIncludeFile(const std::string &Filename);
311 /// \brief Process the specified file for the .incbin directive.
312 /// This returns true on failure.
313 bool processIncbinFile(const std::string &Filename);
315 /// \brief Reset the current lexer position to that given by \p Loc. The
316 /// current token is not set; clients should ensure Lex() is called
319 /// \param InBuffer If not -1, should be the known buffer id that contains the
321 void jumpToLoc(SMLoc Loc, int InBuffer=-1);
323 /// \brief Parse up to the end of statement and a return the contents from the
324 /// current token until the end of the statement; the current token on exit
325 /// will be either the EndOfStatement or EOF.
326 StringRef parseStringToEndOfStatement() override;
328 /// \brief Parse until the end of a statement or a comma is encountered,
329 /// return the contents from the current token up to the end or comma.
330 StringRef parseStringToComma();
332 bool parseAssignment(StringRef Name, bool allow_redef,
333 bool NoDeadStrip = false);
335 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
336 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
337 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
339 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
341 // Generic (target and platform independent) directive parsing.
343 DK_NO_DIRECTIVE, // Placeholder
344 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
345 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
346 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
347 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
348 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
349 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
350 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
351 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
352 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
353 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
354 DK_IF, DK_IFNE, DK_IFB, DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFDEF,
355 DK_IFNDEF, DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
356 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
357 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
358 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
359 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
360 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
361 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
362 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
363 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
364 DK_SLEB128, DK_ULEB128,
369 /// \brief Maps directive name --> DirectiveKind enum, for
370 /// directives parsed by this class.
371 StringMap<DirectiveKind> DirectiveKindMap;
373 // ".ascii", ".asciz", ".string"
374 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
375 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
376 bool parseDirectiveOctaValue(); // ".octa"
377 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
378 bool parseDirectiveFill(); // ".fill"
379 bool parseDirectiveZero(); // ".zero"
380 // ".set", ".equ", ".equiv"
381 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
382 bool parseDirectiveOrg(); // ".org"
383 // ".align{,32}", ".p2align{,w,l}"
384 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
386 // ".file", ".line", ".loc", ".stabs"
387 bool parseDirectiveFile(SMLoc DirectiveLoc);
388 bool parseDirectiveLine();
389 bool parseDirectiveLoc();
390 bool parseDirectiveStabs();
393 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
394 bool parseDirectiveCFIWindowSave();
395 bool parseDirectiveCFISections();
396 bool parseDirectiveCFIStartProc();
397 bool parseDirectiveCFIEndProc();
398 bool parseDirectiveCFIDefCfaOffset();
399 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
400 bool parseDirectiveCFIAdjustCfaOffset();
401 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
403 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
404 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
405 bool parseDirectiveCFIRememberState();
406 bool parseDirectiveCFIRestoreState();
407 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
408 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
409 bool parseDirectiveCFIEscape();
410 bool parseDirectiveCFISignalFrame();
411 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
414 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
415 bool parseDirectiveEndMacro(StringRef Directive);
416 bool parseDirectiveMacro(SMLoc DirectiveLoc);
417 bool parseDirectiveMacrosOnOff(StringRef Directive);
419 // ".bundle_align_mode"
420 bool parseDirectiveBundleAlignMode();
422 bool parseDirectiveBundleLock();
424 bool parseDirectiveBundleUnlock();
427 bool parseDirectiveSpace(StringRef IDVal);
429 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
430 bool parseDirectiveLEB128(bool Signed);
432 /// \brief Parse a directive like ".globl" which
433 /// accepts a single symbol (which should be a label or an external).
434 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
436 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
438 bool parseDirectiveAbort(); // ".abort"
439 bool parseDirectiveInclude(); // ".include"
440 bool parseDirectiveIncbin(); // ".incbin"
443 bool parseDirectiveIf(SMLoc DirectiveLoc);
444 // ".ifb" or ".ifnb", depending on ExpectBlank.
445 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
446 // ".ifc" or ".ifnc", depending on ExpectEqual.
447 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
449 bool parseDirectiveIfeqs(SMLoc DirectiveLoc);
450 // ".ifdef" or ".ifndef", depending on expect_defined
451 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
452 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
453 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
454 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
455 bool parseEscapedString(std::string &Data) override;
457 const MCExpr *applyModifierToExpr(const MCExpr *E,
458 MCSymbolRefExpr::VariantKind Variant);
460 // Macro-like directives
461 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
462 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
463 raw_svector_ostream &OS);
464 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
465 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
466 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
467 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
469 // "_emit" or "__emit"
470 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
474 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
477 bool parseDirectiveEnd(SMLoc DirectiveLoc);
479 // ".err" or ".error"
480 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
482 void initializeDirectiveKindMap();
488 extern MCAsmParserExtension *createDarwinAsmParser();
489 extern MCAsmParserExtension *createELFAsmParser();
490 extern MCAsmParserExtension *createCOFFAsmParser();
494 enum { DEFAULT_ADDRSPACE = 0 };
496 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
497 const MCAsmInfo &_MAI)
498 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
499 PlatformParser(0), CurBuffer(0), MacrosEnabledFlag(true),
500 CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false),
501 ParsingInlineAsm(false) {
502 // Save the old handler.
503 SavedDiagHandler = SrcMgr.getDiagHandler();
504 SavedDiagContext = SrcMgr.getDiagContext();
505 // Set our own handler which calls the saved handler.
506 SrcMgr.setDiagHandler(DiagHandler, this);
507 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
509 // Initialize the platform / file format parser.
510 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
511 case MCObjectFileInfo::IsCOFF:
512 PlatformParser = createCOFFAsmParser();
513 PlatformParser->Initialize(*this);
515 case MCObjectFileInfo::IsMachO:
516 PlatformParser = createDarwinAsmParser();
517 PlatformParser->Initialize(*this);
520 case MCObjectFileInfo::IsELF:
521 PlatformParser = createELFAsmParser();
522 PlatformParser->Initialize(*this);
526 initializeDirectiveKindMap();
529 AsmParser::~AsmParser() {
530 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
532 // Destroy any macros.
533 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
536 delete it->getValue();
538 delete PlatformParser;
541 void AsmParser::printMacroInstantiations() {
542 // Print the active macro instantiation stack.
543 for (std::vector<MacroInstantiation *>::const_reverse_iterator
544 it = ActiveMacros.rbegin(),
545 ie = ActiveMacros.rend();
547 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
548 "while in macro instantiation");
551 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
552 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
553 printMacroInstantiations();
556 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
557 if (FatalAssemblerWarnings)
558 return Error(L, Msg, Ranges);
559 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
560 printMacroInstantiations();
564 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
566 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
567 printMacroInstantiations();
571 bool AsmParser::enterIncludeFile(const std::string &Filename) {
572 std::string IncludedFile;
573 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
579 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
584 /// Process the specified .incbin file by searching for it in the include paths
585 /// then just emitting the byte contents of the file to the streamer. This
586 /// returns true on failure.
587 bool AsmParser::processIncbinFile(const std::string &Filename) {
588 std::string IncludedFile;
589 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
593 // Pick up the bytes from the file and emit them.
594 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
598 void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
599 if (InBuffer != -1) {
600 CurBuffer = InBuffer;
602 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
604 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
607 const AsmToken &AsmParser::Lex() {
608 const AsmToken *tok = &Lexer.Lex();
610 if (tok->is(AsmToken::Eof)) {
611 // If this is the end of an included file, pop the parent file off the
613 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
614 if (ParentIncludeLoc != SMLoc()) {
615 jumpToLoc(ParentIncludeLoc);
620 if (tok->is(AsmToken::Error))
621 Error(Lexer.getErrLoc(), Lexer.getErr());
626 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
627 // Create the initial section, if requested.
628 if (!NoInitialTextSection)
635 AsmCond StartingCondState = TheCondState;
637 // If we are generating dwarf for assembly source files save the initial text
638 // section and generate a .file directive.
639 if (getContext().getGenDwarfForAssembly()) {
640 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
641 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
642 getStreamer().EmitLabel(SectionStartSym);
643 getContext().setGenDwarfSectionStartSym(SectionStartSym);
644 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
645 0, StringRef(), getContext().getMainFileName()));
648 // While we have input, parse each statement.
649 while (Lexer.isNot(AsmToken::Eof)) {
650 ParseStatementInfo Info;
651 if (!parseStatement(Info))
654 // We had an error, validate that one was emitted and recover by skipping to
656 assert(HadError && "Parse statement returned an error, but none emitted!");
657 eatToEndOfStatement();
660 if (TheCondState.TheCond != StartingCondState.TheCond ||
661 TheCondState.Ignore != StartingCondState.Ignore)
662 return TokError("unmatched .ifs or .elses");
664 // Check to see there are no empty DwarfFile slots.
665 const auto &LineTables = getContext().getMCDwarfLineTables();
666 if (!LineTables.empty()) {
668 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
669 if (File.Name.empty() && Index != 0)
670 TokError("unassigned file number: " + Twine(Index) +
671 " for .file directives");
676 // Check to see that all assembler local symbols were actually defined.
677 // Targets that don't do subsections via symbols may not want this, though,
678 // so conservatively exclude them. Only do this if we're finalizing, though,
679 // as otherwise we won't necessarilly have seen everything yet.
680 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
681 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
682 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
685 MCSymbol *Sym = i->getValue();
686 // Variable symbols may not be marked as defined, so check those
687 // explicitly. If we know it's a variable, we have a definition for
688 // the purposes of this check.
689 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
690 // FIXME: We would really like to refer back to where the symbol was
691 // first referenced for a source location. We need to add something
692 // to track that. Currently, we just point to the end of the file.
694 getLexer().getLoc(), SourceMgr::DK_Error,
695 "assembler local symbol '" + Sym->getName() + "' not defined");
699 // Finalize the output stream if there are no errors and if the client wants
701 if (!HadError && !NoFinalize)
707 void AsmParser::checkForValidSection() {
708 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
709 TokError("expected section directive before assembly directive");
714 /// \brief Throw away the rest of the line for testing purposes.
715 void AsmParser::eatToEndOfStatement() {
716 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
720 if (Lexer.is(AsmToken::EndOfStatement))
724 StringRef AsmParser::parseStringToEndOfStatement() {
725 const char *Start = getTok().getLoc().getPointer();
727 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
730 const char *End = getTok().getLoc().getPointer();
731 return StringRef(Start, End - Start);
734 StringRef AsmParser::parseStringToComma() {
735 const char *Start = getTok().getLoc().getPointer();
737 while (Lexer.isNot(AsmToken::EndOfStatement) &&
738 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
741 const char *End = getTok().getLoc().getPointer();
742 return StringRef(Start, End - Start);
745 /// \brief Parse a paren expression and return it.
746 /// NOTE: This assumes the leading '(' has already been consumed.
748 /// parenexpr ::= expr)
750 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
751 if (parseExpression(Res))
753 if (Lexer.isNot(AsmToken::RParen))
754 return TokError("expected ')' in parentheses expression");
755 EndLoc = Lexer.getTok().getEndLoc();
760 /// \brief Parse a bracket expression and return it.
761 /// NOTE: This assumes the leading '[' has already been consumed.
763 /// bracketexpr ::= expr]
765 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
766 if (parseExpression(Res))
768 if (Lexer.isNot(AsmToken::RBrac))
769 return TokError("expected ']' in brackets expression");
770 EndLoc = Lexer.getTok().getEndLoc();
775 /// \brief Parse a primary expression and return it.
776 /// primaryexpr ::= (parenexpr
777 /// primaryexpr ::= symbol
778 /// primaryexpr ::= number
779 /// primaryexpr ::= '.'
780 /// primaryexpr ::= ~,+,- primaryexpr
781 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
782 SMLoc FirstTokenLoc = getLexer().getLoc();
783 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
784 switch (FirstTokenKind) {
786 return TokError("unknown token in expression");
787 // If we have an error assume that we've already handled it.
788 case AsmToken::Error:
790 case AsmToken::Exclaim:
791 Lex(); // Eat the operator.
792 if (parsePrimaryExpr(Res, EndLoc))
794 Res = MCUnaryExpr::CreateLNot(Res, getContext());
796 case AsmToken::Dollar:
798 case AsmToken::String:
799 case AsmToken::Identifier: {
800 StringRef Identifier;
801 if (parseIdentifier(Identifier)) {
802 if (FirstTokenKind == AsmToken::Dollar) {
803 if (Lexer.getMAI().getDollarIsPC()) {
804 // This is a '$' reference, which references the current PC. Emit a
805 // temporary label to the streamer and refer to it.
806 MCSymbol *Sym = Ctx.CreateTempSymbol();
808 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
810 EndLoc = FirstTokenLoc;
813 return Error(FirstTokenLoc, "invalid token in expression");
816 // Parse symbol variant
817 std::pair<StringRef, StringRef> Split;
818 if (!MAI.useParensForSymbolVariant()) {
819 Split = Identifier.split('@');
820 } else if (Lexer.is(AsmToken::LParen)) {
821 Lexer.Lex(); // eat (
823 parseIdentifier(VName);
824 if (Lexer.isNot(AsmToken::RParen)) {
825 return Error(Lexer.getTok().getLoc(),
826 "unexpected token in variant, expected ')'");
828 Lexer.Lex(); // eat )
829 Split = std::make_pair(Identifier, VName);
832 EndLoc = SMLoc::getFromPointer(Identifier.end());
834 // This is a symbol reference.
835 StringRef SymbolName = Identifier;
836 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
838 // Lookup the symbol variant if used.
839 if (Split.second.size()) {
840 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
841 if (Variant != MCSymbolRefExpr::VK_Invalid) {
842 SymbolName = Split.first;
843 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
844 Variant = MCSymbolRefExpr::VK_None;
846 return Error(SMLoc::getFromPointer(Split.second.begin()),
847 "invalid variant '" + Split.second + "'");
851 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
853 // If this is an absolute variable reference, substitute it now to preserve
854 // semantics in the face of reassignment.
855 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
857 return Error(EndLoc, "unexpected modifier on variable reference");
859 Res = Sym->getVariableValue();
863 // Otherwise create a symbol ref.
864 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
867 case AsmToken::BigNum:
868 return TokError("literal value out of range for directive");
869 case AsmToken::Integer: {
870 SMLoc Loc = getTok().getLoc();
871 int64_t IntVal = getTok().getIntVal();
872 Res = MCConstantExpr::Create(IntVal, getContext());
873 EndLoc = Lexer.getTok().getEndLoc();
875 // Look for 'b' or 'f' following an Integer as a directional label
876 if (Lexer.getKind() == AsmToken::Identifier) {
877 StringRef IDVal = getTok().getString();
878 // Lookup the symbol variant if used.
879 std::pair<StringRef, StringRef> Split = IDVal.split('@');
880 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
881 if (Split.first.size() != IDVal.size()) {
882 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
883 if (Variant == MCSymbolRefExpr::VK_Invalid)
884 return TokError("invalid variant '" + Split.second + "'");
887 if (IDVal == "f" || IDVal == "b") {
889 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "b");
890 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
891 if (IDVal == "b" && Sym->isUndefined())
892 return Error(Loc, "invalid reference to undefined symbol");
893 EndLoc = Lexer.getTok().getEndLoc();
894 Lex(); // Eat identifier.
899 case AsmToken::Real: {
900 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
901 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
902 Res = MCConstantExpr::Create(IntVal, getContext());
903 EndLoc = Lexer.getTok().getEndLoc();
907 case AsmToken::Dot: {
908 // This is a '.' reference, which references the current PC. Emit a
909 // temporary label to the streamer and refer to it.
910 MCSymbol *Sym = Ctx.CreateTempSymbol();
912 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
913 EndLoc = Lexer.getTok().getEndLoc();
914 Lex(); // Eat identifier.
917 case AsmToken::LParen:
918 Lex(); // Eat the '('.
919 return parseParenExpr(Res, EndLoc);
920 case AsmToken::LBrac:
921 if (!PlatformParser->HasBracketExpressions())
922 return TokError("brackets expression not supported on this target");
923 Lex(); // Eat the '['.
924 return parseBracketExpr(Res, EndLoc);
925 case AsmToken::Minus:
926 Lex(); // Eat the operator.
927 if (parsePrimaryExpr(Res, EndLoc))
929 Res = MCUnaryExpr::CreateMinus(Res, getContext());
932 Lex(); // Eat the operator.
933 if (parsePrimaryExpr(Res, EndLoc))
935 Res = MCUnaryExpr::CreatePlus(Res, getContext());
937 case AsmToken::Tilde:
938 Lex(); // Eat the operator.
939 if (parsePrimaryExpr(Res, EndLoc))
941 Res = MCUnaryExpr::CreateNot(Res, getContext());
946 bool AsmParser::parseExpression(const MCExpr *&Res) {
948 return parseExpression(Res, EndLoc);
952 AsmParser::applyModifierToExpr(const MCExpr *E,
953 MCSymbolRefExpr::VariantKind Variant) {
954 // Ask the target implementation about this expression first.
955 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
958 // Recurse over the given expression, rebuilding it to apply the given variant
959 // if there is exactly one symbol.
960 switch (E->getKind()) {
962 case MCExpr::Constant:
965 case MCExpr::SymbolRef: {
966 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
968 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
969 TokError("invalid variant on expression '" + getTok().getIdentifier() +
970 "' (already modified)");
974 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
977 case MCExpr::Unary: {
978 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
979 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
982 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
985 case MCExpr::Binary: {
986 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
987 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
988 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
998 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
1002 llvm_unreachable("Invalid expression kind!");
1005 /// \brief Parse an expression and return it.
1007 /// expr ::= expr &&,|| expr -> lowest.
1008 /// expr ::= expr |,^,&,! expr
1009 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1010 /// expr ::= expr <<,>> expr
1011 /// expr ::= expr +,- expr
1012 /// expr ::= expr *,/,% expr -> highest.
1013 /// expr ::= primaryexpr
1015 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1016 // Parse the expression.
1018 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1021 // As a special case, we support 'a op b @ modifier' by rewriting the
1022 // expression to include the modifier. This is inefficient, but in general we
1023 // expect users to use 'a@modifier op b'.
1024 if (Lexer.getKind() == AsmToken::At) {
1027 if (Lexer.isNot(AsmToken::Identifier))
1028 return TokError("unexpected symbol modifier following '@'");
1030 MCSymbolRefExpr::VariantKind Variant =
1031 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1032 if (Variant == MCSymbolRefExpr::VK_Invalid)
1033 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1035 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1037 return TokError("invalid modifier '" + getTok().getIdentifier() +
1038 "' (no symbols present)");
1045 // Try to constant fold it up front, if possible.
1047 if (Res->EvaluateAsAbsolute(Value))
1048 Res = MCConstantExpr::Create(Value, getContext());
1053 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1055 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1058 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1061 SMLoc StartLoc = Lexer.getLoc();
1062 if (parseExpression(Expr))
1065 if (!Expr->EvaluateAsAbsolute(Res))
1066 return Error(StartLoc, "expected absolute expression");
1071 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1072 MCBinaryExpr::Opcode &Kind) {
1075 return 0; // not a binop.
1077 // Lowest Precedence: &&, ||
1078 case AsmToken::AmpAmp:
1079 Kind = MCBinaryExpr::LAnd;
1081 case AsmToken::PipePipe:
1082 Kind = MCBinaryExpr::LOr;
1085 // Low Precedence: |, &, ^
1087 // FIXME: gas seems to support '!' as an infix operator?
1088 case AsmToken::Pipe:
1089 Kind = MCBinaryExpr::Or;
1091 case AsmToken::Caret:
1092 Kind = MCBinaryExpr::Xor;
1095 Kind = MCBinaryExpr::And;
1098 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1099 case AsmToken::EqualEqual:
1100 Kind = MCBinaryExpr::EQ;
1102 case AsmToken::ExclaimEqual:
1103 case AsmToken::LessGreater:
1104 Kind = MCBinaryExpr::NE;
1106 case AsmToken::Less:
1107 Kind = MCBinaryExpr::LT;
1109 case AsmToken::LessEqual:
1110 Kind = MCBinaryExpr::LTE;
1112 case AsmToken::Greater:
1113 Kind = MCBinaryExpr::GT;
1115 case AsmToken::GreaterEqual:
1116 Kind = MCBinaryExpr::GTE;
1119 // Intermediate Precedence: <<, >>
1120 case AsmToken::LessLess:
1121 Kind = MCBinaryExpr::Shl;
1123 case AsmToken::GreaterGreater:
1124 Kind = MCBinaryExpr::Shr;
1127 // High Intermediate Precedence: +, -
1128 case AsmToken::Plus:
1129 Kind = MCBinaryExpr::Add;
1131 case AsmToken::Minus:
1132 Kind = MCBinaryExpr::Sub;
1135 // Highest Precedence: *, /, %
1136 case AsmToken::Star:
1137 Kind = MCBinaryExpr::Mul;
1139 case AsmToken::Slash:
1140 Kind = MCBinaryExpr::Div;
1142 case AsmToken::Percent:
1143 Kind = MCBinaryExpr::Mod;
1148 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1149 /// Res contains the LHS of the expression on input.
1150 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1153 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1154 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1156 // If the next token is lower precedence than we are allowed to eat, return
1157 // successfully with what we ate already.
1158 if (TokPrec < Precedence)
1163 // Eat the next primary expression.
1165 if (parsePrimaryExpr(RHS, EndLoc))
1168 // If BinOp binds less tightly with RHS than the operator after RHS, let
1169 // the pending operator take RHS as its LHS.
1170 MCBinaryExpr::Opcode Dummy;
1171 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1172 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1175 // Merge LHS and RHS according to operator.
1176 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1181 /// ::= EndOfStatement
1182 /// ::= Label* Directive ...Operands... EndOfStatement
1183 /// ::= Label* Identifier OperandList* EndOfStatement
1184 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1185 if (Lexer.is(AsmToken::EndOfStatement)) {
1191 // Statements always start with an identifier or are a full line comment.
1192 AsmToken ID = getTok();
1193 SMLoc IDLoc = ID.getLoc();
1195 int64_t LocalLabelVal = -1;
1196 // A full line comment is a '#' as the first token.
1197 if (Lexer.is(AsmToken::Hash))
1198 return parseCppHashLineFilenameComment(IDLoc);
1200 // Allow an integer followed by a ':' as a directional local label.
1201 if (Lexer.is(AsmToken::Integer)) {
1202 LocalLabelVal = getTok().getIntVal();
1203 if (LocalLabelVal < 0) {
1204 if (!TheCondState.Ignore)
1205 return TokError("unexpected token at start of statement");
1208 IDVal = getTok().getString();
1209 Lex(); // Consume the integer token to be used as an identifier token.
1210 if (Lexer.getKind() != AsmToken::Colon) {
1211 if (!TheCondState.Ignore)
1212 return TokError("unexpected token at start of statement");
1215 } else if (Lexer.is(AsmToken::Dot)) {
1216 // Treat '.' as a valid identifier in this context.
1219 } else if (parseIdentifier(IDVal)) {
1220 if (!TheCondState.Ignore)
1221 return TokError("unexpected token at start of statement");
1225 // Handle conditional assembly here before checking for skipping. We
1226 // have to do this so that .endif isn't skipped in a ".if 0" block for
1228 StringMap<DirectiveKind>::const_iterator DirKindIt =
1229 DirectiveKindMap.find(IDVal);
1230 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1232 : DirKindIt->getValue();
1238 return parseDirectiveIf(IDLoc);
1240 return parseDirectiveIfb(IDLoc, true);
1242 return parseDirectiveIfb(IDLoc, false);
1244 return parseDirectiveIfc(IDLoc, true);
1246 return parseDirectiveIfeqs(IDLoc);
1248 return parseDirectiveIfc(IDLoc, false);
1250 return parseDirectiveIfdef(IDLoc, true);
1253 return parseDirectiveIfdef(IDLoc, false);
1255 return parseDirectiveElseIf(IDLoc);
1257 return parseDirectiveElse(IDLoc);
1259 return parseDirectiveEndIf(IDLoc);
1262 // Ignore the statement if in the middle of inactive conditional
1264 if (TheCondState.Ignore) {
1265 eatToEndOfStatement();
1269 // FIXME: Recurse on local labels?
1271 // See what kind of statement we have.
1272 switch (Lexer.getKind()) {
1273 case AsmToken::Colon: {
1274 checkForValidSection();
1276 // identifier ':' -> Label.
1279 // Diagnose attempt to use '.' as a label.
1281 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1283 // Diagnose attempt to use a variable as a label.
1285 // FIXME: Diagnostics. Note the location of the definition as a label.
1286 // FIXME: This doesn't diagnose assignment to a symbol which has been
1287 // implicitly marked as external.
1289 if (LocalLabelVal == -1)
1290 Sym = getContext().GetOrCreateSymbol(IDVal);
1292 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1293 if (!Sym->isUndefined() || Sym->isVariable())
1294 return Error(IDLoc, "invalid symbol redefinition");
1297 if (!ParsingInlineAsm)
1300 // If we are generating dwarf for assembly source files then gather the
1301 // info to make a dwarf label entry for this label if needed.
1302 if (getContext().getGenDwarfForAssembly())
1303 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1306 getTargetParser().onLabelParsed(Sym);
1308 // Consume any end of statement token, if present, to avoid spurious
1309 // AddBlankLine calls().
1310 if (Lexer.is(AsmToken::EndOfStatement)) {
1312 if (Lexer.is(AsmToken::Eof))
1319 case AsmToken::Equal:
1320 // identifier '=' ... -> assignment statement
1323 return parseAssignment(IDVal, true);
1325 default: // Normal instruction or directive.
1329 // If macros are enabled, check to see if this is a macro instantiation.
1330 if (areMacrosEnabled())
1331 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1332 return handleMacroEntry(M, IDLoc);
1335 // Otherwise, we have a normal instruction or directive.
1337 // Directives start with "."
1338 if (IDVal[0] == '.' && IDVal != ".") {
1339 // There are several entities interested in parsing directives:
1341 // 1. The target-specific assembly parser. Some directives are target
1342 // specific or may potentially behave differently on certain targets.
1343 // 2. Asm parser extensions. For example, platform-specific parsers
1344 // (like the ELF parser) register themselves as extensions.
1345 // 3. The generic directive parser implemented by this class. These are
1346 // all the directives that behave in a target and platform independent
1347 // manner, or at least have a default behavior that's shared between
1348 // all targets and platforms.
1350 // First query the target-specific parser. It will return 'true' if it
1351 // isn't interested in this directive.
1352 if (!getTargetParser().ParseDirective(ID))
1355 // Next, check the extension directive map to see if any extension has
1356 // registered itself to parse this directive.
1357 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1358 ExtensionDirectiveMap.lookup(IDVal);
1360 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1362 // Finally, if no one else is interested in this directive, it must be
1363 // generic and familiar to this class.
1369 return parseDirectiveSet(IDVal, true);
1371 return parseDirectiveSet(IDVal, false);
1373 return parseDirectiveAscii(IDVal, false);
1376 return parseDirectiveAscii(IDVal, true);
1378 return parseDirectiveValue(1);
1382 return parseDirectiveValue(2);
1386 return parseDirectiveValue(4);
1389 return parseDirectiveValue(8);
1391 return parseDirectiveOctaValue();
1394 return parseDirectiveRealValue(APFloat::IEEEsingle);
1396 return parseDirectiveRealValue(APFloat::IEEEdouble);
1398 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1399 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1402 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1403 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1406 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1408 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1410 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1412 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1414 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1416 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1418 return parseDirectiveOrg();
1420 return parseDirectiveFill();
1422 return parseDirectiveZero();
1424 eatToEndOfStatement(); // .extern is the default, ignore it.
1428 return parseDirectiveSymbolAttribute(MCSA_Global);
1429 case DK_LAZY_REFERENCE:
1430 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1431 case DK_NO_DEAD_STRIP:
1432 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1433 case DK_SYMBOL_RESOLVER:
1434 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1435 case DK_PRIVATE_EXTERN:
1436 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1438 return parseDirectiveSymbolAttribute(MCSA_Reference);
1439 case DK_WEAK_DEFINITION:
1440 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1441 case DK_WEAK_REFERENCE:
1442 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1443 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1444 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1447 return parseDirectiveComm(/*IsLocal=*/false);
1449 return parseDirectiveComm(/*IsLocal=*/true);
1451 return parseDirectiveAbort();
1453 return parseDirectiveInclude();
1455 return parseDirectiveIncbin();
1458 return TokError(Twine(IDVal) + " not supported yet");
1460 return parseDirectiveRept(IDLoc, IDVal);
1462 return parseDirectiveIrp(IDLoc);
1464 return parseDirectiveIrpc(IDLoc);
1466 return parseDirectiveEndr(IDLoc);
1467 case DK_BUNDLE_ALIGN_MODE:
1468 return parseDirectiveBundleAlignMode();
1469 case DK_BUNDLE_LOCK:
1470 return parseDirectiveBundleLock();
1471 case DK_BUNDLE_UNLOCK:
1472 return parseDirectiveBundleUnlock();
1474 return parseDirectiveLEB128(true);
1476 return parseDirectiveLEB128(false);
1479 return parseDirectiveSpace(IDVal);
1481 return parseDirectiveFile(IDLoc);
1483 return parseDirectiveLine();
1485 return parseDirectiveLoc();
1487 return parseDirectiveStabs();
1488 case DK_CFI_SECTIONS:
1489 return parseDirectiveCFISections();
1490 case DK_CFI_STARTPROC:
1491 return parseDirectiveCFIStartProc();
1492 case DK_CFI_ENDPROC:
1493 return parseDirectiveCFIEndProc();
1494 case DK_CFI_DEF_CFA:
1495 return parseDirectiveCFIDefCfa(IDLoc);
1496 case DK_CFI_DEF_CFA_OFFSET:
1497 return parseDirectiveCFIDefCfaOffset();
1498 case DK_CFI_ADJUST_CFA_OFFSET:
1499 return parseDirectiveCFIAdjustCfaOffset();
1500 case DK_CFI_DEF_CFA_REGISTER:
1501 return parseDirectiveCFIDefCfaRegister(IDLoc);
1503 return parseDirectiveCFIOffset(IDLoc);
1504 case DK_CFI_REL_OFFSET:
1505 return parseDirectiveCFIRelOffset(IDLoc);
1506 case DK_CFI_PERSONALITY:
1507 return parseDirectiveCFIPersonalityOrLsda(true);
1509 return parseDirectiveCFIPersonalityOrLsda(false);
1510 case DK_CFI_REMEMBER_STATE:
1511 return parseDirectiveCFIRememberState();
1512 case DK_CFI_RESTORE_STATE:
1513 return parseDirectiveCFIRestoreState();
1514 case DK_CFI_SAME_VALUE:
1515 return parseDirectiveCFISameValue(IDLoc);
1516 case DK_CFI_RESTORE:
1517 return parseDirectiveCFIRestore(IDLoc);
1519 return parseDirectiveCFIEscape();
1520 case DK_CFI_SIGNAL_FRAME:
1521 return parseDirectiveCFISignalFrame();
1522 case DK_CFI_UNDEFINED:
1523 return parseDirectiveCFIUndefined(IDLoc);
1524 case DK_CFI_REGISTER:
1525 return parseDirectiveCFIRegister(IDLoc);
1526 case DK_CFI_WINDOW_SAVE:
1527 return parseDirectiveCFIWindowSave();
1530 return parseDirectiveMacrosOnOff(IDVal);
1532 return parseDirectiveMacro(IDLoc);
1535 return parseDirectiveEndMacro(IDVal);
1537 return parseDirectivePurgeMacro(IDLoc);
1539 return parseDirectiveEnd(IDLoc);
1541 return parseDirectiveError(IDLoc, false);
1543 return parseDirectiveError(IDLoc, true);
1546 return Error(IDLoc, "unknown directive");
1549 // __asm _emit or __asm __emit
1550 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1551 IDVal == "_EMIT" || IDVal == "__EMIT"))
1552 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1555 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1556 return parseDirectiveMSAlign(IDLoc, Info);
1558 checkForValidSection();
1560 // Canonicalize the opcode to lower case.
1561 std::string OpcodeStr = IDVal.lower();
1562 ParseInstructionInfo IInfo(Info.AsmRewrites);
1563 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1564 Info.ParsedOperands);
1565 Info.ParseError = HadError;
1567 // Dump the parsed representation, if requested.
1568 if (getShowParsedOperands()) {
1569 SmallString<256> Str;
1570 raw_svector_ostream OS(Str);
1571 OS << "parsed instruction: [";
1572 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1575 Info.ParsedOperands[i]->print(OS);
1579 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1582 // If we are generating dwarf for assembly source files and the current
1583 // section is the initial text section then generate a .loc directive for
1585 if (!HadError && getContext().getGenDwarfForAssembly() &&
1586 getContext().getGenDwarfSection() ==
1587 getStreamer().getCurrentSection().first) {
1589 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1591 // If we previously parsed a cpp hash file line comment then make sure the
1592 // current Dwarf File is for the CppHashFilename if not then emit the
1593 // Dwarf File table for it and adjust the line number for the .loc.
1594 if (CppHashFilename.size() != 0) {
1595 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1596 0, StringRef(), CppHashFilename);
1597 getContext().setGenDwarfFileNumber(FileNumber);
1599 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1600 // cache with the different Loc from the call above we save the last
1601 // info we queried here with SrcMgr.FindLineNumber().
1602 unsigned CppHashLocLineNo;
1603 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1604 CppHashLocLineNo = LastQueryLine;
1606 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1607 LastQueryLine = CppHashLocLineNo;
1608 LastQueryIDLoc = CppHashLoc;
1609 LastQueryBuffer = CppHashBuf;
1611 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1614 getStreamer().EmitDwarfLocDirective(
1615 getContext().getGenDwarfFileNumber(), Line, 0,
1616 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1620 // If parsing succeeded, match the instruction.
1623 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1624 Info.ParsedOperands, Out,
1625 ErrorInfo, ParsingInlineAsm);
1628 // Don't skip the rest of the line, the instruction parser is responsible for
1633 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1634 /// since they may not be able to be tokenized to get to the end of line token.
1635 void AsmParser::eatToEndOfLine() {
1636 if (!Lexer.is(AsmToken::EndOfStatement))
1637 Lexer.LexUntilEndOfLine();
1642 /// parseCppHashLineFilenameComment as this:
1643 /// ::= # number "filename"
1644 /// or just as a full line comment if it doesn't have a number and a string.
1645 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1646 Lex(); // Eat the hash token.
1648 if (getLexer().isNot(AsmToken::Integer)) {
1649 // Consume the line since in cases it is not a well-formed line directive,
1650 // as if were simply a full line comment.
1655 int64_t LineNumber = getTok().getIntVal();
1658 if (getLexer().isNot(AsmToken::String)) {
1663 StringRef Filename = getTok().getString();
1664 // Get rid of the enclosing quotes.
1665 Filename = Filename.substr(1, Filename.size() - 2);
1667 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1669 CppHashFilename = Filename;
1670 CppHashLineNumber = LineNumber;
1671 CppHashBuf = CurBuffer;
1673 // Ignore any trailing characters, they're just comment.
1678 /// \brief will use the last parsed cpp hash line filename comment
1679 /// for the Filename and LineNo if any in the diagnostic.
1680 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1681 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1682 raw_ostream &OS = errs();
1684 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1685 const SMLoc &DiagLoc = Diag.getLoc();
1686 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1687 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1689 // Like SourceMgr::printMessage() we need to print the include stack if any
1690 // before printing the message.
1691 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1692 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1693 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1694 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1697 // If we have not parsed a cpp hash line filename comment or the source
1698 // manager changed or buffer changed (like in a nested include) then just
1699 // print the normal diagnostic using its Filename and LineNo.
1700 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1701 DiagBuf != CppHashBuf) {
1702 if (Parser->SavedDiagHandler)
1703 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1709 // Use the CppHashFilename and calculate a line number based on the
1710 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1712 const std::string &Filename = Parser->CppHashFilename;
1714 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1715 int CppHashLocLineNo =
1716 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1718 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1720 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1721 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1722 Diag.getLineContents(), Diag.getRanges());
1724 if (Parser->SavedDiagHandler)
1725 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1727 NewDiag.print(0, OS);
1730 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1731 // difference being that that function accepts '@' as part of identifiers and
1732 // we can't do that. AsmLexer.cpp should probably be changed to handle
1733 // '@' as a special case when needed.
1734 static bool isIdentifierChar(char c) {
1735 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1739 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1740 ArrayRef<MCAsmMacroParameter> Parameters,
1741 ArrayRef<MCAsmMacroArgument> A, const SMLoc &L) {
1742 unsigned NParameters = Parameters.size();
1743 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1744 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1745 return Error(L, "Wrong number of arguments");
1747 // A macro without parameters is handled differently on Darwin:
1748 // gas accepts no arguments and does no substitutions
1749 while (!Body.empty()) {
1750 // Scan for the next substitution.
1751 std::size_t End = Body.size(), Pos = 0;
1752 for (; Pos != End; ++Pos) {
1753 // Check for a substitution or escape.
1754 if (IsDarwin && !NParameters) {
1755 // This macro has no parameters, look for $0, $1, etc.
1756 if (Body[Pos] != '$' || Pos + 1 == End)
1759 char Next = Body[Pos + 1];
1760 if (Next == '$' || Next == 'n' ||
1761 isdigit(static_cast<unsigned char>(Next)))
1764 // This macro has parameters, look for \foo, \bar, etc.
1765 if (Body[Pos] == '\\' && Pos + 1 != End)
1771 OS << Body.slice(0, Pos);
1773 // Check if we reached the end.
1777 if (IsDarwin && !NParameters) {
1778 switch (Body[Pos + 1]) {
1784 // $n => number of arguments
1789 // $[0-9] => argument
1791 // Missing arguments are ignored.
1792 unsigned Index = Body[Pos + 1] - '0';
1793 if (Index >= A.size())
1796 // Otherwise substitute with the token values, with spaces eliminated.
1797 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1798 ie = A[Index].end();
1800 OS << it->getString();
1806 unsigned I = Pos + 1;
1807 while (isIdentifierChar(Body[I]) && I + 1 != End)
1810 const char *Begin = Body.data() + Pos + 1;
1811 StringRef Argument(Begin, I - (Pos + 1));
1813 for (; Index < NParameters; ++Index)
1814 if (Parameters[Index].Name == Argument)
1817 if (Index == NParameters) {
1818 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1821 OS << '\\' << Argument;
1825 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1826 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1827 ie = A[Index].end();
1829 // We expect no quotes around the string's contents when
1830 // parsing for varargs.
1831 if (it->getKind() != AsmToken::String || VarargParameter)
1832 OS << it->getString();
1834 OS << it->getStringContents();
1836 Pos += 1 + Argument.size();
1839 // Update the scan point.
1840 Body = Body.substr(Pos);
1846 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1847 SMLoc EL, MemoryBuffer *I)
1848 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1851 static bool isOperator(AsmToken::TokenKind kind) {
1855 case AsmToken::Plus:
1856 case AsmToken::Minus:
1857 case AsmToken::Tilde:
1858 case AsmToken::Slash:
1859 case AsmToken::Star:
1861 case AsmToken::Equal:
1862 case AsmToken::EqualEqual:
1863 case AsmToken::Pipe:
1864 case AsmToken::PipePipe:
1865 case AsmToken::Caret:
1867 case AsmToken::AmpAmp:
1868 case AsmToken::Exclaim:
1869 case AsmToken::ExclaimEqual:
1870 case AsmToken::Percent:
1871 case AsmToken::Less:
1872 case AsmToken::LessEqual:
1873 case AsmToken::LessLess:
1874 case AsmToken::LessGreater:
1875 case AsmToken::Greater:
1876 case AsmToken::GreaterEqual:
1877 case AsmToken::GreaterGreater:
1883 class AsmLexerSkipSpaceRAII {
1885 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1886 Lexer.setSkipSpace(SkipSpace);
1889 ~AsmLexerSkipSpaceRAII() {
1890 Lexer.setSkipSpace(true);
1898 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1901 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1902 StringRef Str = parseStringToEndOfStatement();
1903 MA.push_back(AsmToken(AsmToken::String, Str));
1908 unsigned ParenLevel = 0;
1909 unsigned AddTokens = 0;
1911 // Darwin doesn't use spaces to delmit arguments.
1912 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1915 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1916 return TokError("unexpected token in macro instantiation");
1918 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1921 if (Lexer.is(AsmToken::Space)) {
1922 Lex(); // Eat spaces
1924 // Spaces can delimit parameters, but could also be part an expression.
1925 // If the token after a space is an operator, add the token and the next
1926 // one into this argument
1928 if (isOperator(Lexer.getKind())) {
1929 // Check to see whether the token is used as an operator,
1930 // or part of an identifier
1931 const char *NextChar = getTok().getEndLoc().getPointer();
1932 if (*NextChar == ' ')
1936 if (!AddTokens && ParenLevel == 0) {
1942 // handleMacroEntry relies on not advancing the lexer here
1943 // to be able to fill in the remaining default parameter values
1944 if (Lexer.is(AsmToken::EndOfStatement))
1947 // Adjust the current parentheses level.
1948 if (Lexer.is(AsmToken::LParen))
1950 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1953 // Append the token to the current argument list.
1954 MA.push_back(getTok());
1960 if (ParenLevel != 0)
1961 return TokError("unbalanced parentheses in macro argument");
1965 // Parse the macro instantiation arguments.
1966 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1967 MCAsmMacroArguments &A) {
1968 const unsigned NParameters = M ? M->Parameters.size() : 0;
1969 bool NamedParametersFound = false;
1970 SmallVector<SMLoc, 4> FALocs;
1972 A.resize(NParameters);
1973 FALocs.resize(NParameters);
1975 // Parse two kinds of macro invocations:
1976 // - macros defined without any parameters accept an arbitrary number of them
1977 // - macros defined with parameters accept at most that many of them
1978 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
1979 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1981 SMLoc IDLoc = Lexer.getLoc();
1982 MCAsmMacroParameter FA;
1984 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
1985 if (parseIdentifier(FA.Name)) {
1986 Error(IDLoc, "invalid argument identifier for formal argument");
1987 eatToEndOfStatement();
1991 if (!Lexer.is(AsmToken::Equal)) {
1992 TokError("expected '=' after formal parameter identifier");
1993 eatToEndOfStatement();
1998 NamedParametersFound = true;
2001 if (NamedParametersFound && FA.Name.empty()) {
2002 Error(IDLoc, "cannot mix positional and keyword arguments");
2003 eatToEndOfStatement();
2007 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2008 if (parseMacroArgument(FA.Value, Vararg))
2011 unsigned PI = Parameter;
2012 if (!FA.Name.empty()) {
2014 for (FAI = 0; FAI < NParameters; ++FAI)
2015 if (M->Parameters[FAI].Name == FA.Name)
2018 if (FAI >= NParameters) {
2019 assert(M && "expected macro to be defined");
2021 "parameter named '" + FA.Name + "' does not exist for macro '" +
2028 if (!FA.Value.empty()) {
2033 if (FALocs.size() <= PI)
2034 FALocs.resize(PI + 1);
2036 FALocs[PI] = Lexer.getLoc();
2039 // At the end of the statement, fill in remaining arguments that have
2040 // default values. If there aren't any, then the next argument is
2041 // required but missing
2042 if (Lexer.is(AsmToken::EndOfStatement)) {
2043 bool Failure = false;
2044 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2045 if (A[FAI].empty()) {
2046 if (M->Parameters[FAI].Required) {
2047 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2048 "missing value for required parameter "
2049 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2053 if (!M->Parameters[FAI].Value.empty())
2054 A[FAI] = M->Parameters[FAI].Value;
2060 if (Lexer.is(AsmToken::Comma))
2064 return TokError("too many positional arguments");
2067 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2068 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2069 return (I == MacroMap.end()) ? NULL : I->getValue();
2072 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
2073 MacroMap[Name] = new MCAsmMacro(Macro);
2076 void AsmParser::undefineMacro(StringRef Name) {
2077 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2078 if (I != MacroMap.end()) {
2079 delete I->getValue();
2084 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2085 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2086 // this, although we should protect against infinite loops.
2087 if (ActiveMacros.size() == 20)
2088 return TokError("macros cannot be nested more than 20 levels deep");
2090 MCAsmMacroArguments A;
2091 if (parseMacroArguments(M, A))
2094 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2095 // to hold the macro body with substitutions.
2096 SmallString<256> Buf;
2097 StringRef Body = M->Body;
2098 raw_svector_ostream OS(Buf);
2100 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2103 // We include the .endmacro in the buffer as our cue to exit the macro
2105 OS << ".endmacro\n";
2107 MemoryBuffer *Instantiation =
2108 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2110 // Create the macro instantiation object and add to the current macro
2111 // instantiation stack.
2112 MacroInstantiation *MI = new MacroInstantiation(
2113 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
2114 ActiveMacros.push_back(MI);
2116 // Jump to the macro instantiation and prime the lexer.
2117 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2118 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2124 void AsmParser::handleMacroExit() {
2125 // Jump to the EndOfStatement we should return to, and consume it.
2126 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2129 // Pop the instantiation entry.
2130 delete ActiveMacros.back();
2131 ActiveMacros.pop_back();
2134 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2135 switch (Value->getKind()) {
2136 case MCExpr::Binary: {
2137 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2138 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2140 case MCExpr::Target:
2141 case MCExpr::Constant:
2143 case MCExpr::SymbolRef: {
2145 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2147 return isUsedIn(Sym, S.getVariableValue());
2151 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2154 llvm_unreachable("Unknown expr kind!");
2157 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2159 // FIXME: Use better location, we should use proper tokens.
2160 SMLoc EqualLoc = Lexer.getLoc();
2162 const MCExpr *Value;
2163 if (parseExpression(Value))
2166 // Note: we don't count b as used in "a = b". This is to allow
2170 if (Lexer.isNot(AsmToken::EndOfStatement))
2171 return TokError("unexpected token in assignment");
2173 // Eat the end of statement marker.
2176 // Validate that the LHS is allowed to be a variable (either it has not been
2177 // used as a symbol, or it is an absolute symbol).
2178 MCSymbol *Sym = getContext().LookupSymbol(Name);
2180 // Diagnose assignment to a label.
2182 // FIXME: Diagnostics. Note the location of the definition as a label.
2183 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2184 if (isUsedIn(Sym, Value))
2185 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2186 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2187 ; // Allow redefinitions of undefined symbols only used in directives.
2188 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2189 ; // Allow redefinitions of variables that haven't yet been used.
2190 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2191 return Error(EqualLoc, "redefinition of '" + Name + "'");
2192 else if (!Sym->isVariable())
2193 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2194 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2195 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2198 // Don't count these checks as uses.
2199 Sym->setUsed(false);
2200 } else if (Name == ".") {
2201 if (Out.EmitValueToOffset(Value, 0)) {
2202 Error(EqualLoc, "expected absolute expression");
2203 eatToEndOfStatement();
2207 Sym = getContext().GetOrCreateSymbol(Name);
2209 // Do the assignment.
2210 Out.EmitAssignment(Sym, Value);
2212 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2217 /// parseIdentifier:
2220 bool AsmParser::parseIdentifier(StringRef &Res) {
2221 // The assembler has relaxed rules for accepting identifiers, in particular we
2222 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2223 // separate tokens. At this level, we have already lexed so we cannot (currently)
2224 // handle this as a context dependent token, instead we detect adjacent tokens
2225 // and return the combined identifier.
2226 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2227 SMLoc PrefixLoc = getLexer().getLoc();
2229 // Consume the prefix character, and check for a following identifier.
2231 if (Lexer.isNot(AsmToken::Identifier))
2234 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2235 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2238 // Construct the joined identifier and consume the token.
2240 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2245 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2248 Res = getTok().getIdentifier();
2250 Lex(); // Consume the identifier token.
2255 /// parseDirectiveSet:
2256 /// ::= .equ identifier ',' expression
2257 /// ::= .equiv identifier ',' expression
2258 /// ::= .set identifier ',' expression
2259 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2262 if (parseIdentifier(Name))
2263 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2265 if (getLexer().isNot(AsmToken::Comma))
2266 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2269 return parseAssignment(Name, allow_redef, true);
2272 bool AsmParser::parseEscapedString(std::string &Data) {
2273 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2276 StringRef Str = getTok().getStringContents();
2277 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2278 if (Str[i] != '\\') {
2283 // Recognize escaped characters. Note that this escape semantics currently
2284 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2287 return TokError("unexpected backslash at end of string");
2289 // Recognize octal sequences.
2290 if ((unsigned)(Str[i] - '0') <= 7) {
2291 // Consume up to three octal characters.
2292 unsigned Value = Str[i] - '0';
2294 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2296 Value = Value * 8 + (Str[i] - '0');
2298 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2300 Value = Value * 8 + (Str[i] - '0');
2305 return TokError("invalid octal escape sequence (out of range)");
2307 Data += (unsigned char)Value;
2311 // Otherwise recognize individual escapes.
2314 // Just reject invalid escape sequences for now.
2315 return TokError("invalid escape sequence (unrecognized character)");
2317 case 'b': Data += '\b'; break;
2318 case 'f': Data += '\f'; break;
2319 case 'n': Data += '\n'; break;
2320 case 'r': Data += '\r'; break;
2321 case 't': Data += '\t'; break;
2322 case '"': Data += '"'; break;
2323 case '\\': Data += '\\'; break;
2330 /// parseDirectiveAscii:
2331 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2332 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2333 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2334 checkForValidSection();
2337 if (getLexer().isNot(AsmToken::String))
2338 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2341 if (parseEscapedString(Data))
2344 getStreamer().EmitBytes(Data);
2346 getStreamer().EmitBytes(StringRef("\0", 1));
2350 if (getLexer().is(AsmToken::EndOfStatement))
2353 if (getLexer().isNot(AsmToken::Comma))
2354 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2363 /// parseDirectiveValue
2364 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2365 bool AsmParser::parseDirectiveValue(unsigned Size) {
2366 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2367 checkForValidSection();
2370 const MCExpr *Value;
2371 SMLoc ExprLoc = getLexer().getLoc();
2372 if (parseExpression(Value))
2375 // Special case constant expressions to match code generator.
2376 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2377 assert(Size <= 8 && "Invalid size");
2378 uint64_t IntValue = MCE->getValue();
2379 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2380 return Error(ExprLoc, "literal value out of range for directive");
2381 getStreamer().EmitIntValue(IntValue, Size);
2383 getStreamer().EmitValue(Value, Size, ExprLoc);
2385 if (getLexer().is(AsmToken::EndOfStatement))
2388 // FIXME: Improve diagnostic.
2389 if (getLexer().isNot(AsmToken::Comma))
2390 return TokError("unexpected token in directive");
2399 /// ParseDirectiveOctaValue
2400 /// ::= .octa [ hexconstant (, hexconstant)* ]
2401 bool AsmParser::parseDirectiveOctaValue() {
2402 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2403 checkForValidSection();
2406 if (Lexer.getKind() == AsmToken::Error)
2408 if (Lexer.getKind() != AsmToken::Integer &&
2409 Lexer.getKind() != AsmToken::BigNum)
2410 return TokError("unknown token in expression");
2412 SMLoc ExprLoc = getLexer().getLoc();
2413 APInt IntValue = getTok().getAPIntVal();
2417 if (IntValue.isIntN(64)) {
2419 lo = IntValue.getZExtValue();
2420 } else if (IntValue.isIntN(128)) {
2421 // It might actually have more than 128 bits, but the top ones are zero.
2422 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2423 lo = IntValue.getLoBits(64).getZExtValue();
2425 return Error(ExprLoc, "literal value out of range for directive");
2427 if (MAI.isLittleEndian()) {
2428 getStreamer().EmitIntValue(lo, 8);
2429 getStreamer().EmitIntValue(hi, 8);
2431 getStreamer().EmitIntValue(hi, 8);
2432 getStreamer().EmitIntValue(lo, 8);
2435 if (getLexer().is(AsmToken::EndOfStatement))
2438 // FIXME: Improve diagnostic.
2439 if (getLexer().isNot(AsmToken::Comma))
2440 return TokError("unexpected token in directive");
2449 /// parseDirectiveRealValue
2450 /// ::= (.single | .double) [ expression (, expression)* ]
2451 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2452 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2453 checkForValidSection();
2456 // We don't truly support arithmetic on floating point expressions, so we
2457 // have to manually parse unary prefixes.
2459 if (getLexer().is(AsmToken::Minus)) {
2462 } else if (getLexer().is(AsmToken::Plus))
2465 if (getLexer().isNot(AsmToken::Integer) &&
2466 getLexer().isNot(AsmToken::Real) &&
2467 getLexer().isNot(AsmToken::Identifier))
2468 return TokError("unexpected token in directive");
2470 // Convert to an APFloat.
2471 APFloat Value(Semantics);
2472 StringRef IDVal = getTok().getString();
2473 if (getLexer().is(AsmToken::Identifier)) {
2474 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2475 Value = APFloat::getInf(Semantics);
2476 else if (!IDVal.compare_lower("nan"))
2477 Value = APFloat::getNaN(Semantics, false, ~0);
2479 return TokError("invalid floating point literal");
2480 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2481 APFloat::opInvalidOp)
2482 return TokError("invalid floating point literal");
2486 // Consume the numeric token.
2489 // Emit the value as an integer.
2490 APInt AsInt = Value.bitcastToAPInt();
2491 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2492 AsInt.getBitWidth() / 8);
2494 if (getLexer().is(AsmToken::EndOfStatement))
2497 if (getLexer().isNot(AsmToken::Comma))
2498 return TokError("unexpected token in directive");
2507 /// parseDirectiveZero
2508 /// ::= .zero expression
2509 bool AsmParser::parseDirectiveZero() {
2510 checkForValidSection();
2513 if (parseAbsoluteExpression(NumBytes))
2517 if (getLexer().is(AsmToken::Comma)) {
2519 if (parseAbsoluteExpression(Val))
2523 if (getLexer().isNot(AsmToken::EndOfStatement))
2524 return TokError("unexpected token in '.zero' directive");
2528 getStreamer().EmitFill(NumBytes, Val);
2533 /// parseDirectiveFill
2534 /// ::= .fill expression [ , expression [ , expression ] ]
2535 bool AsmParser::parseDirectiveFill() {
2536 checkForValidSection();
2538 SMLoc RepeatLoc = getLexer().getLoc();
2540 if (parseAbsoluteExpression(NumValues))
2543 if (NumValues < 0) {
2545 "'.fill' directive with negative repeat count has no effect");
2549 int64_t FillSize = 1;
2550 int64_t FillExpr = 0;
2552 SMLoc SizeLoc, ExprLoc;
2553 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2554 if (getLexer().isNot(AsmToken::Comma))
2555 return TokError("unexpected token in '.fill' directive");
2558 SizeLoc = getLexer().getLoc();
2559 if (parseAbsoluteExpression(FillSize))
2562 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2563 if (getLexer().isNot(AsmToken::Comma))
2564 return TokError("unexpected token in '.fill' directive");
2567 ExprLoc = getLexer().getLoc();
2568 if (parseAbsoluteExpression(FillExpr))
2571 if (getLexer().isNot(AsmToken::EndOfStatement))
2572 return TokError("unexpected token in '.fill' directive");
2579 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2583 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2587 if (!isUInt<32>(FillExpr) && FillSize > 4)
2588 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2590 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2591 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2593 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2594 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2595 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2601 /// parseDirectiveOrg
2602 /// ::= .org expression [ , expression ]
2603 bool AsmParser::parseDirectiveOrg() {
2604 checkForValidSection();
2606 const MCExpr *Offset;
2607 SMLoc Loc = getTok().getLoc();
2608 if (parseExpression(Offset))
2611 // Parse optional fill expression.
2612 int64_t FillExpr = 0;
2613 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2614 if (getLexer().isNot(AsmToken::Comma))
2615 return TokError("unexpected token in '.org' directive");
2618 if (parseAbsoluteExpression(FillExpr))
2621 if (getLexer().isNot(AsmToken::EndOfStatement))
2622 return TokError("unexpected token in '.org' directive");
2627 // Only limited forms of relocatable expressions are accepted here, it
2628 // has to be relative to the current section. The streamer will return
2629 // 'true' if the expression wasn't evaluatable.
2630 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2631 return Error(Loc, "expected assembly-time absolute expression");
2636 /// parseDirectiveAlign
2637 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2638 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2639 checkForValidSection();
2641 SMLoc AlignmentLoc = getLexer().getLoc();
2643 if (parseAbsoluteExpression(Alignment))
2647 bool HasFillExpr = false;
2648 int64_t FillExpr = 0;
2649 int64_t MaxBytesToFill = 0;
2650 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2651 if (getLexer().isNot(AsmToken::Comma))
2652 return TokError("unexpected token in directive");
2655 // The fill expression can be omitted while specifying a maximum number of
2656 // alignment bytes, e.g:
2658 if (getLexer().isNot(AsmToken::Comma)) {
2660 if (parseAbsoluteExpression(FillExpr))
2664 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2665 if (getLexer().isNot(AsmToken::Comma))
2666 return TokError("unexpected token in directive");
2669 MaxBytesLoc = getLexer().getLoc();
2670 if (parseAbsoluteExpression(MaxBytesToFill))
2673 if (getLexer().isNot(AsmToken::EndOfStatement))
2674 return TokError("unexpected token in directive");
2683 // Compute alignment in bytes.
2685 // FIXME: Diagnose overflow.
2686 if (Alignment >= 32) {
2687 Error(AlignmentLoc, "invalid alignment value");
2691 Alignment = 1ULL << Alignment;
2693 // Reject alignments that aren't a power of two, for gas compatibility.
2694 if (!isPowerOf2_64(Alignment))
2695 Error(AlignmentLoc, "alignment must be a power of 2");
2698 // Diagnose non-sensical max bytes to align.
2699 if (MaxBytesLoc.isValid()) {
2700 if (MaxBytesToFill < 1) {
2701 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2702 "many bytes, ignoring maximum bytes expression");
2706 if (MaxBytesToFill >= Alignment) {
2707 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2713 // Check whether we should use optimal code alignment for this .align
2715 const MCSection *Section = getStreamer().getCurrentSection().first;
2716 assert(Section && "must have section to emit alignment");
2717 bool UseCodeAlign = Section->UseCodeAlign();
2718 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2719 ValueSize == 1 && UseCodeAlign) {
2720 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2722 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2723 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2730 /// parseDirectiveFile
2731 /// ::= .file [number] filename
2732 /// ::= .file number directory filename
2733 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2734 // FIXME: I'm not sure what this is.
2735 int64_t FileNumber = -1;
2736 SMLoc FileNumberLoc = getLexer().getLoc();
2737 if (getLexer().is(AsmToken::Integer)) {
2738 FileNumber = getTok().getIntVal();
2742 return TokError("file number less than one");
2745 if (getLexer().isNot(AsmToken::String))
2746 return TokError("unexpected token in '.file' directive");
2748 // Usually the directory and filename together, otherwise just the directory.
2749 // Allow the strings to have escaped octal character sequence.
2750 std::string Path = getTok().getString();
2751 if (parseEscapedString(Path))
2755 StringRef Directory;
2757 std::string FilenameData;
2758 if (getLexer().is(AsmToken::String)) {
2759 if (FileNumber == -1)
2760 return TokError("explicit path specified, but no file number");
2761 if (parseEscapedString(FilenameData))
2763 Filename = FilenameData;
2770 if (getLexer().isNot(AsmToken::EndOfStatement))
2771 return TokError("unexpected token in '.file' directive");
2773 if (FileNumber == -1)
2774 getStreamer().EmitFileDirective(Filename);
2776 if (getContext().getGenDwarfForAssembly() == true)
2778 "input can't have .file dwarf directives when -g is "
2779 "used to generate dwarf debug info for assembly code");
2781 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2783 Error(FileNumberLoc, "file number already allocated");
2789 /// parseDirectiveLine
2790 /// ::= .line [number]
2791 bool AsmParser::parseDirectiveLine() {
2792 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2793 if (getLexer().isNot(AsmToken::Integer))
2794 return TokError("unexpected token in '.line' directive");
2796 int64_t LineNumber = getTok().getIntVal();
2800 // FIXME: Do something with the .line.
2803 if (getLexer().isNot(AsmToken::EndOfStatement))
2804 return TokError("unexpected token in '.line' directive");
2809 /// parseDirectiveLoc
2810 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2811 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2812 /// The first number is a file number, must have been previously assigned with
2813 /// a .file directive, the second number is the line number and optionally the
2814 /// third number is a column position (zero if not specified). The remaining
2815 /// optional items are .loc sub-directives.
2816 bool AsmParser::parseDirectiveLoc() {
2817 if (getLexer().isNot(AsmToken::Integer))
2818 return TokError("unexpected token in '.loc' directive");
2819 int64_t FileNumber = getTok().getIntVal();
2821 return TokError("file number less than one in '.loc' directive");
2822 if (!getContext().isValidDwarfFileNumber(FileNumber))
2823 return TokError("unassigned file number in '.loc' directive");
2826 int64_t LineNumber = 0;
2827 if (getLexer().is(AsmToken::Integer)) {
2828 LineNumber = getTok().getIntVal();
2830 return TokError("line number less than zero in '.loc' directive");
2834 int64_t ColumnPos = 0;
2835 if (getLexer().is(AsmToken::Integer)) {
2836 ColumnPos = getTok().getIntVal();
2838 return TokError("column position less than zero in '.loc' directive");
2842 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2844 int64_t Discriminator = 0;
2845 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2847 if (getLexer().is(AsmToken::EndOfStatement))
2851 SMLoc Loc = getTok().getLoc();
2852 if (parseIdentifier(Name))
2853 return TokError("unexpected token in '.loc' directive");
2855 if (Name == "basic_block")
2856 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2857 else if (Name == "prologue_end")
2858 Flags |= DWARF2_FLAG_PROLOGUE_END;
2859 else if (Name == "epilogue_begin")
2860 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2861 else if (Name == "is_stmt") {
2862 Loc = getTok().getLoc();
2863 const MCExpr *Value;
2864 if (parseExpression(Value))
2866 // The expression must be the constant 0 or 1.
2867 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2868 int Value = MCE->getValue();
2870 Flags &= ~DWARF2_FLAG_IS_STMT;
2871 else if (Value == 1)
2872 Flags |= DWARF2_FLAG_IS_STMT;
2874 return Error(Loc, "is_stmt value not 0 or 1");
2876 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2878 } else if (Name == "isa") {
2879 Loc = getTok().getLoc();
2880 const MCExpr *Value;
2881 if (parseExpression(Value))
2883 // The expression must be a constant greater or equal to 0.
2884 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2885 int Value = MCE->getValue();
2887 return Error(Loc, "isa number less than zero");
2890 return Error(Loc, "isa number not a constant value");
2892 } else if (Name == "discriminator") {
2893 if (parseAbsoluteExpression(Discriminator))
2896 return Error(Loc, "unknown sub-directive in '.loc' directive");
2899 if (getLexer().is(AsmToken::EndOfStatement))
2904 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2905 Isa, Discriminator, StringRef());
2910 /// parseDirectiveStabs
2911 /// ::= .stabs string, number, number, number
2912 bool AsmParser::parseDirectiveStabs() {
2913 return TokError("unsupported directive '.stabs'");
2916 /// parseDirectiveCFISections
2917 /// ::= .cfi_sections section [, section]
2918 bool AsmParser::parseDirectiveCFISections() {
2923 if (parseIdentifier(Name))
2924 return TokError("Expected an identifier");
2926 if (Name == ".eh_frame")
2928 else if (Name == ".debug_frame")
2931 if (getLexer().is(AsmToken::Comma)) {
2934 if (parseIdentifier(Name))
2935 return TokError("Expected an identifier");
2937 if (Name == ".eh_frame")
2939 else if (Name == ".debug_frame")
2943 getStreamer().EmitCFISections(EH, Debug);
2947 /// parseDirectiveCFIStartProc
2948 /// ::= .cfi_startproc [simple]
2949 bool AsmParser::parseDirectiveCFIStartProc() {
2951 if (getLexer().isNot(AsmToken::EndOfStatement))
2952 if (parseIdentifier(Simple) || Simple != "simple")
2953 return TokError("unexpected token in .cfi_startproc directive");
2955 getStreamer().EmitCFIStartProc(!Simple.empty());
2959 /// parseDirectiveCFIEndProc
2960 /// ::= .cfi_endproc
2961 bool AsmParser::parseDirectiveCFIEndProc() {
2962 getStreamer().EmitCFIEndProc();
2966 /// \brief parse register name or number.
2967 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2968 SMLoc DirectiveLoc) {
2971 if (getLexer().isNot(AsmToken::Integer)) {
2972 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2974 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2976 return parseAbsoluteExpression(Register);
2981 /// parseDirectiveCFIDefCfa
2982 /// ::= .cfi_def_cfa register, offset
2983 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2984 int64_t Register = 0;
2985 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2988 if (getLexer().isNot(AsmToken::Comma))
2989 return TokError("unexpected token in directive");
2993 if (parseAbsoluteExpression(Offset))
2996 getStreamer().EmitCFIDefCfa(Register, Offset);
3000 /// parseDirectiveCFIDefCfaOffset
3001 /// ::= .cfi_def_cfa_offset offset
3002 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3004 if (parseAbsoluteExpression(Offset))
3007 getStreamer().EmitCFIDefCfaOffset(Offset);
3011 /// parseDirectiveCFIRegister
3012 /// ::= .cfi_register register, register
3013 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3014 int64_t Register1 = 0;
3015 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3018 if (getLexer().isNot(AsmToken::Comma))
3019 return TokError("unexpected token in directive");
3022 int64_t Register2 = 0;
3023 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3026 getStreamer().EmitCFIRegister(Register1, Register2);
3030 /// parseDirectiveCFIWindowSave
3031 /// ::= .cfi_window_save
3032 bool AsmParser::parseDirectiveCFIWindowSave() {
3033 getStreamer().EmitCFIWindowSave();
3037 /// parseDirectiveCFIAdjustCfaOffset
3038 /// ::= .cfi_adjust_cfa_offset adjustment
3039 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3040 int64_t Adjustment = 0;
3041 if (parseAbsoluteExpression(Adjustment))
3044 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3048 /// parseDirectiveCFIDefCfaRegister
3049 /// ::= .cfi_def_cfa_register register
3050 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3051 int64_t Register = 0;
3052 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3055 getStreamer().EmitCFIDefCfaRegister(Register);
3059 /// parseDirectiveCFIOffset
3060 /// ::= .cfi_offset register, offset
3061 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3062 int64_t Register = 0;
3065 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3068 if (getLexer().isNot(AsmToken::Comma))
3069 return TokError("unexpected token in directive");
3072 if (parseAbsoluteExpression(Offset))
3075 getStreamer().EmitCFIOffset(Register, Offset);
3079 /// parseDirectiveCFIRelOffset
3080 /// ::= .cfi_rel_offset register, offset
3081 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3082 int64_t Register = 0;
3084 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3087 if (getLexer().isNot(AsmToken::Comma))
3088 return TokError("unexpected token in directive");
3092 if (parseAbsoluteExpression(Offset))
3095 getStreamer().EmitCFIRelOffset(Register, Offset);
3099 static bool isValidEncoding(int64_t Encoding) {
3100 if (Encoding & ~0xff)
3103 if (Encoding == dwarf::DW_EH_PE_omit)
3106 const unsigned Format = Encoding & 0xf;
3107 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3108 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3109 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3110 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3113 const unsigned Application = Encoding & 0x70;
3114 if (Application != dwarf::DW_EH_PE_absptr &&
3115 Application != dwarf::DW_EH_PE_pcrel)
3121 /// parseDirectiveCFIPersonalityOrLsda
3122 /// IsPersonality true for cfi_personality, false for cfi_lsda
3123 /// ::= .cfi_personality encoding, [symbol_name]
3124 /// ::= .cfi_lsda encoding, [symbol_name]
3125 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3126 int64_t Encoding = 0;
3127 if (parseAbsoluteExpression(Encoding))
3129 if (Encoding == dwarf::DW_EH_PE_omit)
3132 if (!isValidEncoding(Encoding))
3133 return TokError("unsupported encoding.");
3135 if (getLexer().isNot(AsmToken::Comma))
3136 return TokError("unexpected token in directive");
3140 if (parseIdentifier(Name))
3141 return TokError("expected identifier in directive");
3143 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3146 getStreamer().EmitCFIPersonality(Sym, Encoding);
3148 getStreamer().EmitCFILsda(Sym, Encoding);
3152 /// parseDirectiveCFIRememberState
3153 /// ::= .cfi_remember_state
3154 bool AsmParser::parseDirectiveCFIRememberState() {
3155 getStreamer().EmitCFIRememberState();
3159 /// parseDirectiveCFIRestoreState
3160 /// ::= .cfi_remember_state
3161 bool AsmParser::parseDirectiveCFIRestoreState() {
3162 getStreamer().EmitCFIRestoreState();
3166 /// parseDirectiveCFISameValue
3167 /// ::= .cfi_same_value register
3168 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3169 int64_t Register = 0;
3171 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3174 getStreamer().EmitCFISameValue(Register);
3178 /// parseDirectiveCFIRestore
3179 /// ::= .cfi_restore register
3180 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3181 int64_t Register = 0;
3182 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3185 getStreamer().EmitCFIRestore(Register);
3189 /// parseDirectiveCFIEscape
3190 /// ::= .cfi_escape expression[,...]
3191 bool AsmParser::parseDirectiveCFIEscape() {
3194 if (parseAbsoluteExpression(CurrValue))
3197 Values.push_back((uint8_t)CurrValue);
3199 while (getLexer().is(AsmToken::Comma)) {
3202 if (parseAbsoluteExpression(CurrValue))
3205 Values.push_back((uint8_t)CurrValue);
3208 getStreamer().EmitCFIEscape(Values);
3212 /// parseDirectiveCFISignalFrame
3213 /// ::= .cfi_signal_frame
3214 bool AsmParser::parseDirectiveCFISignalFrame() {
3215 if (getLexer().isNot(AsmToken::EndOfStatement))
3216 return Error(getLexer().getLoc(),
3217 "unexpected token in '.cfi_signal_frame'");
3219 getStreamer().EmitCFISignalFrame();
3223 /// parseDirectiveCFIUndefined
3224 /// ::= .cfi_undefined register
3225 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3226 int64_t Register = 0;
3228 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3231 getStreamer().EmitCFIUndefined(Register);
3235 /// parseDirectiveMacrosOnOff
3238 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3239 if (getLexer().isNot(AsmToken::EndOfStatement))
3240 return Error(getLexer().getLoc(),
3241 "unexpected token in '" + Directive + "' directive");
3243 setMacrosEnabled(Directive == ".macros_on");
3247 /// parseDirectiveMacro
3248 /// ::= .macro name[,] [parameters]
3249 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3251 if (parseIdentifier(Name))
3252 return TokError("expected identifier in '.macro' directive");
3254 if (getLexer().is(AsmToken::Comma))
3257 MCAsmMacroParameters Parameters;
3258 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3260 if (Parameters.size() && Parameters.back().Vararg)
3261 return Error(Lexer.getLoc(),
3262 "Vararg parameter '" + Parameters.back().Name +
3263 "' should be last one in the list of parameters.");
3265 MCAsmMacroParameter Parameter;
3266 if (parseIdentifier(Parameter.Name))
3267 return TokError("expected identifier in '.macro' directive");
3269 if (Lexer.is(AsmToken::Colon)) {
3270 Lex(); // consume ':'
3273 StringRef Qualifier;
3275 QualLoc = Lexer.getLoc();
3276 if (parseIdentifier(Qualifier))
3277 return Error(QualLoc, "missing parameter qualifier for "
3278 "'" + Parameter.Name + "' in macro '" + Name + "'");
3280 if (Qualifier == "req")
3281 Parameter.Required = true;
3282 else if (Qualifier == "vararg" && !IsDarwin)
3283 Parameter.Vararg = true;
3285 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3286 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3289 if (getLexer().is(AsmToken::Equal)) {
3294 ParamLoc = Lexer.getLoc();
3295 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3298 if (Parameter.Required)
3299 Warning(ParamLoc, "pointless default value for required parameter "
3300 "'" + Parameter.Name + "' in macro '" + Name + "'");
3303 Parameters.push_back(Parameter);
3305 if (getLexer().is(AsmToken::Comma))
3309 // Eat the end of statement.
3312 AsmToken EndToken, StartToken = getTok();
3313 unsigned MacroDepth = 0;
3315 // Lex the macro definition.
3317 // Check whether we have reached the end of the file.
3318 if (getLexer().is(AsmToken::Eof))
3319 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3321 // Otherwise, check whether we have reach the .endmacro.
3322 if (getLexer().is(AsmToken::Identifier)) {
3323 if (getTok().getIdentifier() == ".endm" ||
3324 getTok().getIdentifier() == ".endmacro") {
3325 if (MacroDepth == 0) { // Outermost macro.
3326 EndToken = getTok();
3328 if (getLexer().isNot(AsmToken::EndOfStatement))
3329 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3333 // Otherwise we just found the end of an inner macro.
3336 } else if (getTok().getIdentifier() == ".macro") {
3337 // We allow nested macros. Those aren't instantiated until the outermost
3338 // macro is expanded so just ignore them for now.
3343 // Otherwise, scan til the end of the statement.
3344 eatToEndOfStatement();
3347 if (lookupMacro(Name)) {
3348 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3351 const char *BodyStart = StartToken.getLoc().getPointer();
3352 const char *BodyEnd = EndToken.getLoc().getPointer();
3353 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3354 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3355 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3359 /// checkForBadMacro
3361 /// With the support added for named parameters there may be code out there that
3362 /// is transitioning from positional parameters. In versions of gas that did
3363 /// not support named parameters they would be ignored on the macro definition.
3364 /// But to support both styles of parameters this is not possible so if a macro
3365 /// definition has named parameters but does not use them and has what appears
3366 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3367 /// warning that the positional parameter found in body which have no effect.
3368 /// Hoping the developer will either remove the named parameters from the macro
3369 /// definition so the positional parameters get used if that was what was
3370 /// intended or change the macro to use the named parameters. It is possible
3371 /// this warning will trigger when the none of the named parameters are used
3372 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3373 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3375 ArrayRef<MCAsmMacroParameter> Parameters) {
3376 // If this macro is not defined with named parameters the warning we are
3377 // checking for here doesn't apply.
3378 unsigned NParameters = Parameters.size();
3379 if (NParameters == 0)
3382 bool NamedParametersFound = false;
3383 bool PositionalParametersFound = false;
3385 // Look at the body of the macro for use of both the named parameters and what
3386 // are likely to be positional parameters. This is what expandMacro() is
3387 // doing when it finds the parameters in the body.
3388 while (!Body.empty()) {
3389 // Scan for the next possible parameter.
3390 std::size_t End = Body.size(), Pos = 0;
3391 for (; Pos != End; ++Pos) {
3392 // Check for a substitution or escape.
3393 // This macro is defined with parameters, look for \foo, \bar, etc.
3394 if (Body[Pos] == '\\' && Pos + 1 != End)
3397 // This macro should have parameters, but look for $0, $1, ..., $n too.
3398 if (Body[Pos] != '$' || Pos + 1 == End)
3400 char Next = Body[Pos + 1];
3401 if (Next == '$' || Next == 'n' ||
3402 isdigit(static_cast<unsigned char>(Next)))
3406 // Check if we reached the end.
3410 if (Body[Pos] == '$') {
3411 switch (Body[Pos + 1]) {
3416 // $n => number of arguments
3418 PositionalParametersFound = true;
3421 // $[0-9] => argument
3423 PositionalParametersFound = true;
3429 unsigned I = Pos + 1;
3430 while (isIdentifierChar(Body[I]) && I + 1 != End)
3433 const char *Begin = Body.data() + Pos + 1;
3434 StringRef Argument(Begin, I - (Pos + 1));
3436 for (; Index < NParameters; ++Index)
3437 if (Parameters[Index].Name == Argument)
3440 if (Index == NParameters) {
3441 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3447 NamedParametersFound = true;
3448 Pos += 1 + Argument.size();
3451 // Update the scan point.
3452 Body = Body.substr(Pos);
3455 if (!NamedParametersFound && PositionalParametersFound)
3456 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3457 "used in macro body, possible positional parameter "
3458 "found in body which will have no effect");
3461 /// parseDirectiveEndMacro
3464 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3465 if (getLexer().isNot(AsmToken::EndOfStatement))
3466 return TokError("unexpected token in '" + Directive + "' directive");
3468 // If we are inside a macro instantiation, terminate the current
3470 if (isInsideMacroInstantiation()) {
3475 // Otherwise, this .endmacro is a stray entry in the file; well formed
3476 // .endmacro directives are handled during the macro definition parsing.
3477 return TokError("unexpected '" + Directive + "' in file, "
3478 "no current macro definition");
3481 /// parseDirectivePurgeMacro
3483 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3485 if (parseIdentifier(Name))
3486 return TokError("expected identifier in '.purgem' directive");
3488 if (getLexer().isNot(AsmToken::EndOfStatement))
3489 return TokError("unexpected token in '.purgem' directive");
3491 if (!lookupMacro(Name))
3492 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3494 undefineMacro(Name);
3498 /// parseDirectiveBundleAlignMode
3499 /// ::= {.bundle_align_mode} expression
3500 bool AsmParser::parseDirectiveBundleAlignMode() {
3501 checkForValidSection();
3503 // Expect a single argument: an expression that evaluates to a constant
3504 // in the inclusive range 0-30.
3505 SMLoc ExprLoc = getLexer().getLoc();
3506 int64_t AlignSizePow2;
3507 if (parseAbsoluteExpression(AlignSizePow2))
3509 else if (getLexer().isNot(AsmToken::EndOfStatement))
3510 return TokError("unexpected token after expression in"
3511 " '.bundle_align_mode' directive");
3512 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3513 return Error(ExprLoc,
3514 "invalid bundle alignment size (expected between 0 and 30)");
3518 // Because of AlignSizePow2's verified range we can safely truncate it to
3520 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3524 /// parseDirectiveBundleLock
3525 /// ::= {.bundle_lock} [align_to_end]
3526 bool AsmParser::parseDirectiveBundleLock() {
3527 checkForValidSection();
3528 bool AlignToEnd = false;
3530 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3532 SMLoc Loc = getTok().getLoc();
3533 const char *kInvalidOptionError =
3534 "invalid option for '.bundle_lock' directive";
3536 if (parseIdentifier(Option))
3537 return Error(Loc, kInvalidOptionError);
3539 if (Option != "align_to_end")
3540 return Error(Loc, kInvalidOptionError);
3541 else if (getLexer().isNot(AsmToken::EndOfStatement))
3543 "unexpected token after '.bundle_lock' directive option");
3549 getStreamer().EmitBundleLock(AlignToEnd);
3553 /// parseDirectiveBundleLock
3554 /// ::= {.bundle_lock}
3555 bool AsmParser::parseDirectiveBundleUnlock() {
3556 checkForValidSection();
3558 if (getLexer().isNot(AsmToken::EndOfStatement))
3559 return TokError("unexpected token in '.bundle_unlock' directive");
3562 getStreamer().EmitBundleUnlock();
3566 /// parseDirectiveSpace
3567 /// ::= (.skip | .space) expression [ , expression ]
3568 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3569 checkForValidSection();
3572 if (parseAbsoluteExpression(NumBytes))
3575 int64_t FillExpr = 0;
3576 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3577 if (getLexer().isNot(AsmToken::Comma))
3578 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3581 if (parseAbsoluteExpression(FillExpr))
3584 if (getLexer().isNot(AsmToken::EndOfStatement))
3585 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3591 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3594 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3595 getStreamer().EmitFill(NumBytes, FillExpr);
3600 /// parseDirectiveLEB128
3601 /// ::= (.sleb128 | .uleb128) expression
3602 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3603 checkForValidSection();
3604 const MCExpr *Value;
3606 if (parseExpression(Value))
3609 if (getLexer().isNot(AsmToken::EndOfStatement))
3610 return TokError("unexpected token in directive");
3613 getStreamer().EmitSLEB128Value(Value);
3615 getStreamer().EmitULEB128Value(Value);
3620 /// parseDirectiveSymbolAttribute
3621 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3622 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3623 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3626 SMLoc Loc = getTok().getLoc();
3628 if (parseIdentifier(Name))
3629 return Error(Loc, "expected identifier in directive");
3631 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3633 // Assembler local symbols don't make any sense here. Complain loudly.
3634 if (Sym->isTemporary())
3635 return Error(Loc, "non-local symbol required in directive");
3637 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3638 return Error(Loc, "unable to emit symbol attribute");
3640 if (getLexer().is(AsmToken::EndOfStatement))
3643 if (getLexer().isNot(AsmToken::Comma))
3644 return TokError("unexpected token in directive");
3653 /// parseDirectiveComm
3654 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3655 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3656 checkForValidSection();
3658 SMLoc IDLoc = getLexer().getLoc();
3660 if (parseIdentifier(Name))
3661 return TokError("expected identifier in directive");
3663 // Handle the identifier as the key symbol.
3664 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3666 if (getLexer().isNot(AsmToken::Comma))
3667 return TokError("unexpected token in directive");
3671 SMLoc SizeLoc = getLexer().getLoc();
3672 if (parseAbsoluteExpression(Size))
3675 int64_t Pow2Alignment = 0;
3676 SMLoc Pow2AlignmentLoc;
3677 if (getLexer().is(AsmToken::Comma)) {
3679 Pow2AlignmentLoc = getLexer().getLoc();
3680 if (parseAbsoluteExpression(Pow2Alignment))
3683 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3684 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3685 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3687 // If this target takes alignments in bytes (not log) validate and convert.
3688 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3689 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3690 if (!isPowerOf2_64(Pow2Alignment))
3691 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3692 Pow2Alignment = Log2_64(Pow2Alignment);
3696 if (getLexer().isNot(AsmToken::EndOfStatement))
3697 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3701 // NOTE: a size of zero for a .comm should create a undefined symbol
3702 // but a size of .lcomm creates a bss symbol of size zero.
3704 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3705 "be less than zero");
3707 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3708 // may internally end up wanting an alignment in bytes.
3709 // FIXME: Diagnose overflow.
3710 if (Pow2Alignment < 0)
3711 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3712 "alignment, can't be less than zero");
3714 if (!Sym->isUndefined())
3715 return Error(IDLoc, "invalid symbol redefinition");
3717 // Create the Symbol as a common or local common with Size and Pow2Alignment
3719 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3723 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3727 /// parseDirectiveAbort
3728 /// ::= .abort [... message ...]
3729 bool AsmParser::parseDirectiveAbort() {
3730 // FIXME: Use loc from directive.
3731 SMLoc Loc = getLexer().getLoc();
3733 StringRef Str = parseStringToEndOfStatement();
3734 if (getLexer().isNot(AsmToken::EndOfStatement))
3735 return TokError("unexpected token in '.abort' directive");
3740 Error(Loc, ".abort detected. Assembly stopping.");
3742 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3743 // FIXME: Actually abort assembly here.
3748 /// parseDirectiveInclude
3749 /// ::= .include "filename"
3750 bool AsmParser::parseDirectiveInclude() {
3751 if (getLexer().isNot(AsmToken::String))
3752 return TokError("expected string in '.include' directive");
3754 // Allow the strings to have escaped octal character sequence.
3755 std::string Filename;
3756 if (parseEscapedString(Filename))
3758 SMLoc IncludeLoc = getLexer().getLoc();
3761 if (getLexer().isNot(AsmToken::EndOfStatement))
3762 return TokError("unexpected token in '.include' directive");
3764 // Attempt to switch the lexer to the included file before consuming the end
3765 // of statement to avoid losing it when we switch.
3766 if (enterIncludeFile(Filename)) {
3767 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3774 /// parseDirectiveIncbin
3775 /// ::= .incbin "filename"
3776 bool AsmParser::parseDirectiveIncbin() {
3777 if (getLexer().isNot(AsmToken::String))
3778 return TokError("expected string in '.incbin' directive");
3780 // Allow the strings to have escaped octal character sequence.
3781 std::string Filename;
3782 if (parseEscapedString(Filename))
3784 SMLoc IncbinLoc = getLexer().getLoc();
3787 if (getLexer().isNot(AsmToken::EndOfStatement))
3788 return TokError("unexpected token in '.incbin' directive");
3790 // Attempt to process the included file.
3791 if (processIncbinFile(Filename)) {
3792 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3799 /// parseDirectiveIf
3800 /// ::= .if expression
3801 /// ::= .ifne expression
3802 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3803 TheCondStack.push_back(TheCondState);
3804 TheCondState.TheCond = AsmCond::IfCond;
3805 if (TheCondState.Ignore) {
3806 eatToEndOfStatement();
3809 if (parseAbsoluteExpression(ExprValue))
3812 if (getLexer().isNot(AsmToken::EndOfStatement))
3813 return TokError("unexpected token in '.if' directive");
3817 TheCondState.CondMet = ExprValue;
3818 TheCondState.Ignore = !TheCondState.CondMet;
3824 /// parseDirectiveIfb
3826 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3827 TheCondStack.push_back(TheCondState);
3828 TheCondState.TheCond = AsmCond::IfCond;
3830 if (TheCondState.Ignore) {
3831 eatToEndOfStatement();
3833 StringRef Str = parseStringToEndOfStatement();
3835 if (getLexer().isNot(AsmToken::EndOfStatement))
3836 return TokError("unexpected token in '.ifb' directive");
3840 TheCondState.CondMet = ExpectBlank == Str.empty();
3841 TheCondState.Ignore = !TheCondState.CondMet;
3847 /// parseDirectiveIfc
3848 /// ::= .ifc string1, string2
3849 /// ::= .ifnc string1, string2
3850 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3851 TheCondStack.push_back(TheCondState);
3852 TheCondState.TheCond = AsmCond::IfCond;
3854 if (TheCondState.Ignore) {
3855 eatToEndOfStatement();
3857 StringRef Str1 = parseStringToComma();
3859 if (getLexer().isNot(AsmToken::Comma))
3860 return TokError("unexpected token in '.ifc' directive");
3864 StringRef Str2 = parseStringToEndOfStatement();
3866 if (getLexer().isNot(AsmToken::EndOfStatement))
3867 return TokError("unexpected token in '.ifc' directive");
3871 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3872 TheCondState.Ignore = !TheCondState.CondMet;
3878 /// parseDirectiveIfeqs
3879 /// ::= .ifeqs string1, string2
3880 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc) {
3881 if (Lexer.isNot(AsmToken::String)) {
3882 TokError("expected string parameter for '.ifeqs' directive");
3883 eatToEndOfStatement();
3887 StringRef String1 = getTok().getStringContents();
3890 if (Lexer.isNot(AsmToken::Comma)) {
3891 TokError("expected comma after first string for '.ifeqs' directive");
3892 eatToEndOfStatement();
3898 if (Lexer.isNot(AsmToken::String)) {
3899 TokError("expected string parameter for '.ifeqs' directive");
3900 eatToEndOfStatement();
3904 StringRef String2 = getTok().getStringContents();
3907 TheCondStack.push_back(TheCondState);
3908 TheCondState.TheCond = AsmCond::IfCond;
3909 TheCondState.CondMet = String1 == String2;
3910 TheCondState.Ignore = !TheCondState.CondMet;
3915 /// parseDirectiveIfdef
3916 /// ::= .ifdef symbol
3917 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3919 TheCondStack.push_back(TheCondState);
3920 TheCondState.TheCond = AsmCond::IfCond;
3922 if (TheCondState.Ignore) {
3923 eatToEndOfStatement();
3925 if (parseIdentifier(Name))
3926 return TokError("expected identifier after '.ifdef'");
3930 MCSymbol *Sym = getContext().LookupSymbol(Name);
3933 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3935 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3936 TheCondState.Ignore = !TheCondState.CondMet;
3942 /// parseDirectiveElseIf
3943 /// ::= .elseif expression
3944 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3945 if (TheCondState.TheCond != AsmCond::IfCond &&
3946 TheCondState.TheCond != AsmCond::ElseIfCond)
3947 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3949 TheCondState.TheCond = AsmCond::ElseIfCond;
3951 bool LastIgnoreState = false;
3952 if (!TheCondStack.empty())
3953 LastIgnoreState = TheCondStack.back().Ignore;
3954 if (LastIgnoreState || TheCondState.CondMet) {
3955 TheCondState.Ignore = true;
3956 eatToEndOfStatement();
3959 if (parseAbsoluteExpression(ExprValue))
3962 if (getLexer().isNot(AsmToken::EndOfStatement))
3963 return TokError("unexpected token in '.elseif' directive");
3966 TheCondState.CondMet = ExprValue;
3967 TheCondState.Ignore = !TheCondState.CondMet;
3973 /// parseDirectiveElse
3975 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3976 if (getLexer().isNot(AsmToken::EndOfStatement))
3977 return TokError("unexpected token in '.else' directive");
3981 if (TheCondState.TheCond != AsmCond::IfCond &&
3982 TheCondState.TheCond != AsmCond::ElseIfCond)
3983 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3985 TheCondState.TheCond = AsmCond::ElseCond;
3986 bool LastIgnoreState = false;
3987 if (!TheCondStack.empty())
3988 LastIgnoreState = TheCondStack.back().Ignore;
3989 if (LastIgnoreState || TheCondState.CondMet)
3990 TheCondState.Ignore = true;
3992 TheCondState.Ignore = false;
3997 /// parseDirectiveEnd
3999 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4000 if (getLexer().isNot(AsmToken::EndOfStatement))
4001 return TokError("unexpected token in '.end' directive");
4005 while (Lexer.isNot(AsmToken::Eof))
4011 /// parseDirectiveError
4013 /// ::= .error [string]
4014 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4015 if (!TheCondStack.empty()) {
4016 if (TheCondStack.back().Ignore) {
4017 eatToEndOfStatement();
4023 return Error(L, ".err encountered");
4025 StringRef Message = ".error directive invoked in source file";
4026 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4027 if (Lexer.isNot(AsmToken::String)) {
4028 TokError(".error argument must be a string");
4029 eatToEndOfStatement();
4033 Message = getTok().getStringContents();
4041 /// parseDirectiveEndIf
4043 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4044 if (getLexer().isNot(AsmToken::EndOfStatement))
4045 return TokError("unexpected token in '.endif' directive");
4049 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4050 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4052 if (!TheCondStack.empty()) {
4053 TheCondState = TheCondStack.back();
4054 TheCondStack.pop_back();
4060 void AsmParser::initializeDirectiveKindMap() {
4061 DirectiveKindMap[".set"] = DK_SET;
4062 DirectiveKindMap[".equ"] = DK_EQU;
4063 DirectiveKindMap[".equiv"] = DK_EQUIV;
4064 DirectiveKindMap[".ascii"] = DK_ASCII;
4065 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4066 DirectiveKindMap[".string"] = DK_STRING;
4067 DirectiveKindMap[".byte"] = DK_BYTE;
4068 DirectiveKindMap[".short"] = DK_SHORT;
4069 DirectiveKindMap[".value"] = DK_VALUE;
4070 DirectiveKindMap[".2byte"] = DK_2BYTE;
4071 DirectiveKindMap[".long"] = DK_LONG;
4072 DirectiveKindMap[".int"] = DK_INT;
4073 DirectiveKindMap[".4byte"] = DK_4BYTE;
4074 DirectiveKindMap[".quad"] = DK_QUAD;
4075 DirectiveKindMap[".8byte"] = DK_8BYTE;
4076 DirectiveKindMap[".octa"] = DK_OCTA;
4077 DirectiveKindMap[".single"] = DK_SINGLE;
4078 DirectiveKindMap[".float"] = DK_FLOAT;
4079 DirectiveKindMap[".double"] = DK_DOUBLE;
4080 DirectiveKindMap[".align"] = DK_ALIGN;
4081 DirectiveKindMap[".align32"] = DK_ALIGN32;
4082 DirectiveKindMap[".balign"] = DK_BALIGN;
4083 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4084 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4085 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4086 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4087 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4088 DirectiveKindMap[".org"] = DK_ORG;
4089 DirectiveKindMap[".fill"] = DK_FILL;
4090 DirectiveKindMap[".zero"] = DK_ZERO;
4091 DirectiveKindMap[".extern"] = DK_EXTERN;
4092 DirectiveKindMap[".globl"] = DK_GLOBL;
4093 DirectiveKindMap[".global"] = DK_GLOBAL;
4094 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4095 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4096 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4097 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4098 DirectiveKindMap[".reference"] = DK_REFERENCE;
4099 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4100 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4101 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4102 DirectiveKindMap[".comm"] = DK_COMM;
4103 DirectiveKindMap[".common"] = DK_COMMON;
4104 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4105 DirectiveKindMap[".abort"] = DK_ABORT;
4106 DirectiveKindMap[".include"] = DK_INCLUDE;
4107 DirectiveKindMap[".incbin"] = DK_INCBIN;
4108 DirectiveKindMap[".code16"] = DK_CODE16;
4109 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4110 DirectiveKindMap[".rept"] = DK_REPT;
4111 DirectiveKindMap[".rep"] = DK_REPT;
4112 DirectiveKindMap[".irp"] = DK_IRP;
4113 DirectiveKindMap[".irpc"] = DK_IRPC;
4114 DirectiveKindMap[".endr"] = DK_ENDR;
4115 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4116 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4117 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4118 DirectiveKindMap[".if"] = DK_IF;
4119 DirectiveKindMap[".ifne"] = DK_IFNE;
4120 DirectiveKindMap[".ifb"] = DK_IFB;
4121 DirectiveKindMap[".ifnb"] = DK_IFNB;
4122 DirectiveKindMap[".ifc"] = DK_IFC;
4123 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4124 DirectiveKindMap[".ifnc"] = DK_IFNC;
4125 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4126 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4127 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4128 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4129 DirectiveKindMap[".else"] = DK_ELSE;
4130 DirectiveKindMap[".end"] = DK_END;
4131 DirectiveKindMap[".endif"] = DK_ENDIF;
4132 DirectiveKindMap[".skip"] = DK_SKIP;
4133 DirectiveKindMap[".space"] = DK_SPACE;
4134 DirectiveKindMap[".file"] = DK_FILE;
4135 DirectiveKindMap[".line"] = DK_LINE;
4136 DirectiveKindMap[".loc"] = DK_LOC;
4137 DirectiveKindMap[".stabs"] = DK_STABS;
4138 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4139 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4140 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4141 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4142 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4143 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4144 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4145 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4146 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4147 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4148 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4149 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4150 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4151 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4152 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4153 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4154 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4155 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4156 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4157 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4158 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4159 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4160 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4161 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4162 DirectiveKindMap[".macro"] = DK_MACRO;
4163 DirectiveKindMap[".endm"] = DK_ENDM;
4164 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4165 DirectiveKindMap[".purgem"] = DK_PURGEM;
4166 DirectiveKindMap[".err"] = DK_ERR;
4167 DirectiveKindMap[".error"] = DK_ERROR;
4170 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4171 AsmToken EndToken, StartToken = getTok();
4173 unsigned NestLevel = 0;
4175 // Check whether we have reached the end of the file.
4176 if (getLexer().is(AsmToken::Eof)) {
4177 Error(DirectiveLoc, "no matching '.endr' in definition");
4181 if (Lexer.is(AsmToken::Identifier) &&
4182 (getTok().getIdentifier() == ".rept")) {
4186 // Otherwise, check whether we have reached the .endr.
4187 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4188 if (NestLevel == 0) {
4189 EndToken = getTok();
4191 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4192 TokError("unexpected token in '.endr' directive");
4200 // Otherwise, scan till the end of the statement.
4201 eatToEndOfStatement();
4204 const char *BodyStart = StartToken.getLoc().getPointer();
4205 const char *BodyEnd = EndToken.getLoc().getPointer();
4206 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4208 // We Are Anonymous.
4209 MacroLikeBodies.push_back(MCAsmMacro(StringRef(), Body, None));
4210 return &MacroLikeBodies.back();
4213 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4214 raw_svector_ostream &OS) {
4217 MemoryBuffer *Instantiation =
4218 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4220 // Create the macro instantiation object and add to the current macro
4221 // instantiation stack.
4222 MacroInstantiation *MI = new MacroInstantiation(
4223 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
4224 ActiveMacros.push_back(MI);
4226 // Jump to the macro instantiation and prime the lexer.
4227 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
4228 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
4232 /// parseDirectiveRept
4233 /// ::= .rep | .rept count
4234 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4235 const MCExpr *CountExpr;
4236 SMLoc CountLoc = getTok().getLoc();
4237 if (parseExpression(CountExpr))
4241 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4242 eatToEndOfStatement();
4243 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4247 return Error(CountLoc, "Count is negative");
4249 if (Lexer.isNot(AsmToken::EndOfStatement))
4250 return TokError("unexpected token in '" + Dir + "' directive");
4252 // Eat the end of statement.
4255 // Lex the rept definition.
4256 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4260 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4261 // to hold the macro body with substitutions.
4262 SmallString<256> Buf;
4263 raw_svector_ostream OS(Buf);
4265 if (expandMacro(OS, M->Body, None, None, getTok().getLoc()))
4268 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4273 /// parseDirectiveIrp
4274 /// ::= .irp symbol,values
4275 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4276 MCAsmMacroParameter Parameter;
4278 if (parseIdentifier(Parameter.Name))
4279 return TokError("expected identifier in '.irp' directive");
4281 if (Lexer.isNot(AsmToken::Comma))
4282 return TokError("expected comma in '.irp' directive");
4286 MCAsmMacroArguments A;
4287 if (parseMacroArguments(0, A))
4290 // Eat the end of statement.
4293 // Lex the irp definition.
4294 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4298 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4299 // to hold the macro body with substitutions.
4300 SmallString<256> Buf;
4301 raw_svector_ostream OS(Buf);
4303 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4304 if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc()))
4308 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4313 /// parseDirectiveIrpc
4314 /// ::= .irpc symbol,values
4315 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4316 MCAsmMacroParameter Parameter;
4318 if (parseIdentifier(Parameter.Name))
4319 return TokError("expected identifier in '.irpc' directive");
4321 if (Lexer.isNot(AsmToken::Comma))
4322 return TokError("expected comma in '.irpc' directive");
4326 MCAsmMacroArguments A;
4327 if (parseMacroArguments(0, A))
4330 if (A.size() != 1 || A.front().size() != 1)
4331 return TokError("unexpected token in '.irpc' directive");
4333 // Eat the end of statement.
4336 // Lex the irpc definition.
4337 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4341 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4342 // to hold the macro body with substitutions.
4343 SmallString<256> Buf;
4344 raw_svector_ostream OS(Buf);
4346 StringRef Values = A.front().front().getString();
4347 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4348 MCAsmMacroArgument Arg;
4349 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4351 if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc()))
4355 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4360 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4361 if (ActiveMacros.empty())
4362 return TokError("unmatched '.endr' directive");
4364 // The only .repl that should get here are the ones created by
4365 // instantiateMacroLikeBody.
4366 assert(getLexer().is(AsmToken::EndOfStatement));
4372 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4374 const MCExpr *Value;
4375 SMLoc ExprLoc = getLexer().getLoc();
4376 if (parseExpression(Value))
4378 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4380 return Error(ExprLoc, "unexpected expression in _emit");
4381 uint64_t IntValue = MCE->getValue();
4382 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4383 return Error(ExprLoc, "literal value out of range for directive");
4385 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4389 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4390 const MCExpr *Value;
4391 SMLoc ExprLoc = getLexer().getLoc();
4392 if (parseExpression(Value))
4394 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4396 return Error(ExprLoc, "unexpected expression in align");
4397 uint64_t IntValue = MCE->getValue();
4398 if (!isPowerOf2_64(IntValue))
4399 return Error(ExprLoc, "literal value not a power of two greater then zero");
4401 Info.AsmRewrites->push_back(
4402 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4406 // We are comparing pointers, but the pointers are relative to a single string.
4407 // Thus, this should always be deterministic.
4408 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4409 const AsmRewrite *AsmRewriteB) {
4410 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4412 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4415 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4416 // rewrite to the same location. Make sure the SizeDirective rewrite is
4417 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4418 // ensures the sort algorithm is stable.
4419 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4420 AsmRewritePrecedence[AsmRewriteB->Kind])
4423 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4424 AsmRewritePrecedence[AsmRewriteB->Kind])
4426 llvm_unreachable("Unstable rewrite sort.");
4429 bool AsmParser::parseMSInlineAsm(
4430 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4431 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4432 SmallVectorImpl<std::string> &Constraints,
4433 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4434 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4435 SmallVector<void *, 4> InputDecls;
4436 SmallVector<void *, 4> OutputDecls;
4437 SmallVector<bool, 4> InputDeclsAddressOf;
4438 SmallVector<bool, 4> OutputDeclsAddressOf;
4439 SmallVector<std::string, 4> InputConstraints;
4440 SmallVector<std::string, 4> OutputConstraints;
4441 SmallVector<unsigned, 4> ClobberRegs;
4443 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4448 // While we have input, parse each statement.
4449 unsigned InputIdx = 0;
4450 unsigned OutputIdx = 0;
4451 while (getLexer().isNot(AsmToken::Eof)) {
4452 ParseStatementInfo Info(&AsmStrRewrites);
4453 if (parseStatement(Info))
4456 if (Info.ParseError)
4459 if (Info.Opcode == ~0U)
4462 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4464 // Build the list of clobbers, outputs and inputs.
4465 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4466 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4469 if (Operand->isImm())
4472 // Register operand.
4473 if (Operand->isReg() && !Operand->needAddressOf()) {
4474 unsigned NumDefs = Desc.getNumDefs();
4476 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4477 ClobberRegs.push_back(Operand->getReg());
4481 // Expr/Input or Output.
4482 StringRef SymName = Operand->getSymName();
4483 if (SymName.empty())
4486 void *OpDecl = Operand->getOpDecl();
4490 bool isOutput = (i == 1) && Desc.mayStore();
4491 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4494 OutputDecls.push_back(OpDecl);
4495 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4496 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4497 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4499 InputDecls.push_back(OpDecl);
4500 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4501 InputConstraints.push_back(Operand->getConstraint().str());
4502 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4506 // Consider implicit defs to be clobbers. Think of cpuid and push.
4507 const uint16_t *ImpDefs = Desc.getImplicitDefs();
4508 for (unsigned I = 0, E = Desc.getNumImplicitDefs(); I != E; ++I)
4509 ClobberRegs.push_back(ImpDefs[I]);
4512 // Set the number of Outputs and Inputs.
4513 NumOutputs = OutputDecls.size();
4514 NumInputs = InputDecls.size();
4516 // Set the unique clobbers.
4517 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4518 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4520 Clobbers.assign(ClobberRegs.size(), std::string());
4521 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4522 raw_string_ostream OS(Clobbers[I]);
4523 IP->printRegName(OS, ClobberRegs[I]);
4526 // Merge the various outputs and inputs. Output are expected first.
4527 if (NumOutputs || NumInputs) {
4528 unsigned NumExprs = NumOutputs + NumInputs;
4529 OpDecls.resize(NumExprs);
4530 Constraints.resize(NumExprs);
4531 for (unsigned i = 0; i < NumOutputs; ++i) {
4532 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4533 Constraints[i] = OutputConstraints[i];
4535 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4536 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4537 Constraints[j] = InputConstraints[i];
4541 // Build the IR assembly string.
4542 std::string AsmStringIR;
4543 raw_string_ostream OS(AsmStringIR);
4544 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4545 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4546 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4547 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4548 E = AsmStrRewrites.end();
4550 AsmRewriteKind Kind = (*I).Kind;
4551 if (Kind == AOK_Delete)
4554 const char *Loc = (*I).Loc.getPointer();
4555 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4557 // Emit everything up to the immediate/expression.
4558 unsigned Len = Loc - AsmStart;
4560 OS << StringRef(AsmStart, Len);
4562 // Skip the original expression.
4563 if (Kind == AOK_Skip) {
4564 AsmStart = Loc + (*I).Len;
4568 unsigned AdditionalSkip = 0;
4569 // Rewrite expressions in $N notation.
4574 OS << "$$" << (*I).Val;
4580 OS << '$' << InputIdx++;
4583 OS << '$' << OutputIdx++;
4585 case AOK_SizeDirective:
4588 case 8: OS << "byte ptr "; break;
4589 case 16: OS << "word ptr "; break;
4590 case 32: OS << "dword ptr "; break;
4591 case 64: OS << "qword ptr "; break;
4592 case 80: OS << "xword ptr "; break;
4593 case 128: OS << "xmmword ptr "; break;
4594 case 256: OS << "ymmword ptr "; break;
4601 unsigned Val = (*I).Val;
4602 OS << ".align " << Val;
4604 // Skip the original immediate.
4605 assert(Val < 10 && "Expected alignment less then 2^10.");
4606 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4609 case AOK_DotOperator:
4610 // Insert the dot if the user omitted it.
4612 if (AsmStringIR.back() != '.')
4618 // Skip the original expression.
4619 AsmStart = Loc + (*I).Len + AdditionalSkip;
4622 // Emit the remainder of the asm string.
4623 if (AsmStart != AsmEnd)
4624 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4626 AsmString = OS.str();
4630 /// \brief Create an MCAsmParser instance.
4631 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4632 MCStreamer &Out, const MCAsmInfo &MAI) {
4633 return new AsmParser(SM, C, Out, MAI);