1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCParser/AsmCond.h"
27 #include "llvm/MC/MCParser/AsmLexer.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCTargetAsmParser.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/raw_ostream.h"
48 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
51 /// \brief Helper types for tracking macro definitions.
52 typedef std::vector<AsmToken> MCAsmMacroArgument;
53 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
55 struct MCAsmMacroParameter {
57 MCAsmMacroArgument Value;
61 MCAsmMacroParameter() : Required(false), Vararg(false) {}
64 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
69 MCAsmMacroParameters Parameters;
72 MCAsmMacro(StringRef N, StringRef B, ArrayRef<MCAsmMacroParameter> P) :
73 Name(N), Body(B), Parameters(P) {}
76 /// \brief Helper class for storing information about an active macro
78 struct MacroInstantiation {
79 /// The location of the instantiation.
80 SMLoc InstantiationLoc;
82 /// The buffer where parsing should resume upon instantiation completion.
85 /// The location where parsing should resume upon instantiation completion.
88 /// The depth of TheCondStack at the start of the instantiation.
89 size_t CondStackDepth;
92 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
95 struct ParseStatementInfo {
96 /// \brief The parsed operands from the last parsed statement.
97 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
99 /// \brief The opcode from the last parsed instruction.
102 /// \brief Was there an error parsing the inline assembly?
105 SmallVectorImpl<AsmRewrite> *AsmRewrites;
107 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
108 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
109 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
112 /// \brief The concrete assembly parser instance.
113 class AsmParser : public MCAsmParser {
114 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
115 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
120 const MCAsmInfo &MAI;
122 SourceMgr::DiagHandlerTy SavedDiagHandler;
123 void *SavedDiagContext;
124 MCAsmParserExtension *PlatformParser;
126 /// This is the current buffer index we're lexing from as managed by the
127 /// SourceMgr object.
130 AsmCond TheCondState;
131 std::vector<AsmCond> TheCondStack;
133 /// \brief maps directive names to handler methods in parser
134 /// extensions. Extensions register themselves in this map by calling
135 /// addDirectiveHandler.
136 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
138 /// \brief Map of currently defined macros.
139 StringMap<MCAsmMacro*> MacroMap;
141 /// \brief Stack of active macro instantiations.
142 std::vector<MacroInstantiation*> ActiveMacros;
144 /// \brief List of bodies of anonymous macros.
145 std::deque<MCAsmMacro> MacroLikeBodies;
147 /// Boolean tracking whether macro substitution is enabled.
148 unsigned MacrosEnabledFlag : 1;
150 /// Flag tracking whether any errors have been encountered.
151 unsigned HadError : 1;
153 /// The values from the last parsed cpp hash file line comment if any.
154 StringRef CppHashFilename;
155 int64_t CppHashLineNumber;
158 /// When generating dwarf for assembly source files we need to calculate the
159 /// logical line number based on the last parsed cpp hash file line comment
160 /// and current line. Since this is slow and messes up the SourceMgr's
161 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
162 SMLoc LastQueryIDLoc;
163 unsigned LastQueryBuffer;
164 unsigned LastQueryLine;
166 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
167 unsigned AssemblerDialect;
169 /// \brief is Darwin compatibility enabled?
172 /// \brief Are we parsing ms-style inline assembly?
173 bool ParsingInlineAsm;
176 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
177 const MCAsmInfo &MAI);
178 virtual ~AsmParser();
180 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
182 void addDirectiveHandler(StringRef Directive,
183 ExtensionDirectiveHandler Handler) override {
184 ExtensionDirectiveMap[Directive] = Handler;
188 /// @name MCAsmParser Interface
191 SourceMgr &getSourceManager() override { return SrcMgr; }
192 MCAsmLexer &getLexer() override { return Lexer; }
193 MCContext &getContext() override { return Ctx; }
194 MCStreamer &getStreamer() override { return Out; }
195 unsigned getAssemblerDialect() override {
196 if (AssemblerDialect == ~0U)
197 return MAI.getAssemblerDialect();
199 return AssemblerDialect;
201 void setAssemblerDialect(unsigned i) override {
202 AssemblerDialect = i;
205 void Note(SMLoc L, const Twine &Msg,
206 ArrayRef<SMRange> Ranges = None) override;
207 bool Warning(SMLoc L, const Twine &Msg,
208 ArrayRef<SMRange> Ranges = None) override;
209 bool Error(SMLoc L, const Twine &Msg,
210 ArrayRef<SMRange> Ranges = None) override;
212 const AsmToken &Lex() override;
214 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
215 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
217 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
218 unsigned &NumOutputs, unsigned &NumInputs,
219 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
220 SmallVectorImpl<std::string> &Constraints,
221 SmallVectorImpl<std::string> &Clobbers,
222 const MCInstrInfo *MII, const MCInstPrinter *IP,
223 MCAsmParserSemaCallback &SI) override;
225 bool parseExpression(const MCExpr *&Res);
226 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
227 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
228 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
229 bool parseAbsoluteExpression(int64_t &Res) override;
231 /// \brief Parse an identifier or string (as a quoted identifier)
232 /// and set \p Res to the identifier contents.
233 bool parseIdentifier(StringRef &Res) override;
234 void eatToEndOfStatement() override;
236 void checkForValidSection() override;
241 bool parseStatement(ParseStatementInfo &Info);
242 void eatToEndOfLine();
243 bool parseCppHashLineFilenameComment(const SMLoc &L);
245 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
246 ArrayRef<MCAsmMacroParameter> Parameters);
247 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
248 ArrayRef<MCAsmMacroParameter> Parameters,
249 ArrayRef<MCAsmMacroArgument> A,
252 /// \brief Are macros enabled in the parser?
253 bool areMacrosEnabled() {return MacrosEnabledFlag;}
255 /// \brief Control a flag in the parser that enables or disables macros.
256 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
258 /// \brief Lookup a previously defined macro.
259 /// \param Name Macro name.
260 /// \returns Pointer to macro. NULL if no such macro was defined.
261 const MCAsmMacro* lookupMacro(StringRef Name);
263 /// \brief Define a new macro with the given name and information.
264 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
266 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
267 void undefineMacro(StringRef Name);
269 /// \brief Are we inside a macro instantiation?
270 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
272 /// \brief Handle entry to macro instantiation.
274 /// \param M The macro.
275 /// \param NameLoc Instantiation location.
276 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
278 /// \brief Handle exit from macro instantiation.
279 void handleMacroExit();
281 /// \brief Extract AsmTokens for a macro argument.
282 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
284 /// \brief Parse all macro arguments for a given macro.
285 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
287 void printMacroInstantiations();
288 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
289 ArrayRef<SMRange> Ranges = None) const {
290 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
292 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
294 /// \brief Enter the specified file. This returns true on failure.
295 bool enterIncludeFile(const std::string &Filename);
297 /// \brief Process the specified file for the .incbin directive.
298 /// This returns true on failure.
299 bool processIncbinFile(const std::string &Filename);
301 /// \brief Reset the current lexer position to that given by \p Loc. The
302 /// current token is not set; clients should ensure Lex() is called
305 /// \param InBuffer If not 0, should be the known buffer id that contains the
307 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
309 /// \brief Parse up to the end of statement and a return the contents from the
310 /// current token until the end of the statement; the current token on exit
311 /// will be either the EndOfStatement or EOF.
312 StringRef parseStringToEndOfStatement() override;
314 /// \brief Parse until the end of a statement or a comma is encountered,
315 /// return the contents from the current token up to the end or comma.
316 StringRef parseStringToComma();
318 bool parseAssignment(StringRef Name, bool allow_redef,
319 bool NoDeadStrip = false);
321 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
322 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
323 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
325 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
327 // Generic (target and platform independent) directive parsing.
329 DK_NO_DIRECTIVE, // Placeholder
330 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
331 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
332 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
333 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
334 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
335 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
336 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
337 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
338 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
339 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
340 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
341 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
342 DK_ELSEIF, DK_ELSE, DK_ENDIF,
343 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
344 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
345 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
346 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
347 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
348 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
349 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
350 DK_MACROS_ON, DK_MACROS_OFF,
351 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
352 DK_SLEB128, DK_ULEB128,
353 DK_ERR, DK_ERROR, DK_WARNING,
357 /// \brief Maps directive name --> DirectiveKind enum, for
358 /// directives parsed by this class.
359 StringMap<DirectiveKind> DirectiveKindMap;
361 // ".ascii", ".asciz", ".string"
362 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
363 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
364 bool parseDirectiveOctaValue(); // ".octa"
365 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
366 bool parseDirectiveFill(); // ".fill"
367 bool parseDirectiveZero(); // ".zero"
368 // ".set", ".equ", ".equiv"
369 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
370 bool parseDirectiveOrg(); // ".org"
371 // ".align{,32}", ".p2align{,w,l}"
372 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
374 // ".file", ".line", ".loc", ".stabs"
375 bool parseDirectiveFile(SMLoc DirectiveLoc);
376 bool parseDirectiveLine();
377 bool parseDirectiveLoc();
378 bool parseDirectiveStabs();
381 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
382 bool parseDirectiveCFIWindowSave();
383 bool parseDirectiveCFISections();
384 bool parseDirectiveCFIStartProc();
385 bool parseDirectiveCFIEndProc();
386 bool parseDirectiveCFIDefCfaOffset();
387 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
388 bool parseDirectiveCFIAdjustCfaOffset();
389 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
390 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
391 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
392 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
393 bool parseDirectiveCFIRememberState();
394 bool parseDirectiveCFIRestoreState();
395 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
396 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
397 bool parseDirectiveCFIEscape();
398 bool parseDirectiveCFISignalFrame();
399 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
402 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
403 bool parseDirectiveExitMacro(StringRef Directive);
404 bool parseDirectiveEndMacro(StringRef Directive);
405 bool parseDirectiveMacro(SMLoc DirectiveLoc);
406 bool parseDirectiveMacrosOnOff(StringRef Directive);
408 // ".bundle_align_mode"
409 bool parseDirectiveBundleAlignMode();
411 bool parseDirectiveBundleLock();
413 bool parseDirectiveBundleUnlock();
416 bool parseDirectiveSpace(StringRef IDVal);
418 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
419 bool parseDirectiveLEB128(bool Signed);
421 /// \brief Parse a directive like ".globl" which
422 /// accepts a single symbol (which should be a label or an external).
423 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
425 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
427 bool parseDirectiveAbort(); // ".abort"
428 bool parseDirectiveInclude(); // ".include"
429 bool parseDirectiveIncbin(); // ".incbin"
431 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
432 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
433 // ".ifb" or ".ifnb", depending on ExpectBlank.
434 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
435 // ".ifc" or ".ifnc", depending on ExpectEqual.
436 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
438 bool parseDirectiveIfeqs(SMLoc DirectiveLoc);
439 // ".ifdef" or ".ifndef", depending on expect_defined
440 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
441 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
442 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
443 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
444 bool parseEscapedString(std::string &Data) override;
446 const MCExpr *applyModifierToExpr(const MCExpr *E,
447 MCSymbolRefExpr::VariantKind Variant);
449 // Macro-like directives
450 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
451 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
452 raw_svector_ostream &OS);
453 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
454 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
455 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
456 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
458 // "_emit" or "__emit"
459 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
463 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
466 bool parseDirectiveEnd(SMLoc DirectiveLoc);
468 // ".err" or ".error"
469 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
472 bool parseDirectiveWarning(SMLoc DirectiveLoc);
474 void initializeDirectiveKindMap();
480 extern MCAsmParserExtension *createDarwinAsmParser();
481 extern MCAsmParserExtension *createELFAsmParser();
482 extern MCAsmParserExtension *createCOFFAsmParser();
486 enum { DEFAULT_ADDRSPACE = 0 };
488 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
489 const MCAsmInfo &_MAI)
490 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
491 PlatformParser(nullptr), CurBuffer(_SM.getMainFileID()),
492 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
493 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
494 // Save the old handler.
495 SavedDiagHandler = SrcMgr.getDiagHandler();
496 SavedDiagContext = SrcMgr.getDiagContext();
497 // Set our own handler which calls the saved handler.
498 SrcMgr.setDiagHandler(DiagHandler, this);
499 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
501 // Initialize the platform / file format parser.
502 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
503 case MCObjectFileInfo::IsCOFF:
504 PlatformParser = createCOFFAsmParser();
505 PlatformParser->Initialize(*this);
507 case MCObjectFileInfo::IsMachO:
508 PlatformParser = createDarwinAsmParser();
509 PlatformParser->Initialize(*this);
512 case MCObjectFileInfo::IsELF:
513 PlatformParser = createELFAsmParser();
514 PlatformParser->Initialize(*this);
518 initializeDirectiveKindMap();
521 AsmParser::~AsmParser() {
522 assert((HadError || ActiveMacros.empty()) &&
523 "Unexpected active macro instantiation!");
525 // Destroy any macros.
526 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
529 delete it->getValue();
531 delete PlatformParser;
534 void AsmParser::printMacroInstantiations() {
535 // Print the active macro instantiation stack.
536 for (std::vector<MacroInstantiation *>::const_reverse_iterator
537 it = ActiveMacros.rbegin(),
538 ie = ActiveMacros.rend();
540 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
541 "while in macro instantiation");
544 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
545 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
546 printMacroInstantiations();
549 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
550 if (getTargetParser().getTargetOptions().MCFatalWarnings)
551 return Error(L, Msg, Ranges);
552 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
553 printMacroInstantiations();
557 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
559 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
560 printMacroInstantiations();
564 bool AsmParser::enterIncludeFile(const std::string &Filename) {
565 std::string IncludedFile;
567 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
572 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
576 /// Process the specified .incbin file by searching for it in the include paths
577 /// then just emitting the byte contents of the file to the streamer. This
578 /// returns true on failure.
579 bool AsmParser::processIncbinFile(const std::string &Filename) {
580 std::string IncludedFile;
582 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
586 // Pick up the bytes from the file and emit them.
587 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
591 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
592 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
593 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
597 const AsmToken &AsmParser::Lex() {
598 const AsmToken *tok = &Lexer.Lex();
600 if (tok->is(AsmToken::Eof)) {
601 // If this is the end of an included file, pop the parent file off the
603 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
604 if (ParentIncludeLoc != SMLoc()) {
605 jumpToLoc(ParentIncludeLoc);
610 if (tok->is(AsmToken::Error))
611 Error(Lexer.getErrLoc(), Lexer.getErr());
616 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
617 // Create the initial section, if requested.
618 if (!NoInitialTextSection)
625 AsmCond StartingCondState = TheCondState;
627 // If we are generating dwarf for assembly source files save the initial text
628 // section and generate a .file directive.
629 if (getContext().getGenDwarfForAssembly()) {
630 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
631 getStreamer().EmitLabel(SectionStartSym);
632 auto InsertResult = getContext().addGenDwarfSection(
633 getStreamer().getCurrentSection().first);
634 assert(InsertResult.second && ".text section should not have debug info yet");
635 InsertResult.first->second.first = SectionStartSym;
636 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
637 0, StringRef(), getContext().getMainFileName()));
640 // While we have input, parse each statement.
641 while (Lexer.isNot(AsmToken::Eof)) {
642 ParseStatementInfo Info;
643 if (!parseStatement(Info))
646 // We had an error, validate that one was emitted and recover by skipping to
648 assert(HadError && "Parse statement returned an error, but none emitted!");
649 eatToEndOfStatement();
652 if (TheCondState.TheCond != StartingCondState.TheCond ||
653 TheCondState.Ignore != StartingCondState.Ignore)
654 return TokError("unmatched .ifs or .elses");
656 // Check to see there are no empty DwarfFile slots.
657 const auto &LineTables = getContext().getMCDwarfLineTables();
658 if (!LineTables.empty()) {
660 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
661 if (File.Name.empty() && Index != 0)
662 TokError("unassigned file number: " + Twine(Index) +
663 " for .file directives");
668 // Check to see that all assembler local symbols were actually defined.
669 // Targets that don't do subsections via symbols may not want this, though,
670 // so conservatively exclude them. Only do this if we're finalizing, though,
671 // as otherwise we won't necessarilly have seen everything yet.
672 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
673 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
674 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
677 MCSymbol *Sym = i->getValue();
678 // Variable symbols may not be marked as defined, so check those
679 // explicitly. If we know it's a variable, we have a definition for
680 // the purposes of this check.
681 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
682 // FIXME: We would really like to refer back to where the symbol was
683 // first referenced for a source location. We need to add something
684 // to track that. Currently, we just point to the end of the file.
686 getLexer().getLoc(), SourceMgr::DK_Error,
687 "assembler local symbol '" + Sym->getName() + "' not defined");
691 // Finalize the output stream if there are no errors and if the client wants
693 if (!HadError && !NoFinalize)
699 void AsmParser::checkForValidSection() {
700 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
701 TokError("expected section directive before assembly directive");
706 /// \brief Throw away the rest of the line for testing purposes.
707 void AsmParser::eatToEndOfStatement() {
708 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
712 if (Lexer.is(AsmToken::EndOfStatement))
716 StringRef AsmParser::parseStringToEndOfStatement() {
717 const char *Start = getTok().getLoc().getPointer();
719 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
722 const char *End = getTok().getLoc().getPointer();
723 return StringRef(Start, End - Start);
726 StringRef AsmParser::parseStringToComma() {
727 const char *Start = getTok().getLoc().getPointer();
729 while (Lexer.isNot(AsmToken::EndOfStatement) &&
730 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
733 const char *End = getTok().getLoc().getPointer();
734 return StringRef(Start, End - Start);
737 /// \brief Parse a paren expression and return it.
738 /// NOTE: This assumes the leading '(' has already been consumed.
740 /// parenexpr ::= expr)
742 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
743 if (parseExpression(Res))
745 if (Lexer.isNot(AsmToken::RParen))
746 return TokError("expected ')' in parentheses expression");
747 EndLoc = Lexer.getTok().getEndLoc();
752 /// \brief Parse a bracket expression and return it.
753 /// NOTE: This assumes the leading '[' has already been consumed.
755 /// bracketexpr ::= expr]
757 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
758 if (parseExpression(Res))
760 if (Lexer.isNot(AsmToken::RBrac))
761 return TokError("expected ']' in brackets expression");
762 EndLoc = Lexer.getTok().getEndLoc();
767 /// \brief Parse a primary expression and return it.
768 /// primaryexpr ::= (parenexpr
769 /// primaryexpr ::= symbol
770 /// primaryexpr ::= number
771 /// primaryexpr ::= '.'
772 /// primaryexpr ::= ~,+,- primaryexpr
773 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
774 SMLoc FirstTokenLoc = getLexer().getLoc();
775 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
776 switch (FirstTokenKind) {
778 return TokError("unknown token in expression");
779 // If we have an error assume that we've already handled it.
780 case AsmToken::Error:
782 case AsmToken::Exclaim:
783 Lex(); // Eat the operator.
784 if (parsePrimaryExpr(Res, EndLoc))
786 Res = MCUnaryExpr::CreateLNot(Res, getContext());
788 case AsmToken::Dollar:
790 case AsmToken::String:
791 case AsmToken::Identifier: {
792 StringRef Identifier;
793 if (parseIdentifier(Identifier)) {
794 if (FirstTokenKind == AsmToken::Dollar) {
795 if (Lexer.getMAI().getDollarIsPC()) {
796 // This is a '$' reference, which references the current PC. Emit a
797 // temporary label to the streamer and refer to it.
798 MCSymbol *Sym = Ctx.CreateTempSymbol();
800 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
802 EndLoc = FirstTokenLoc;
805 return Error(FirstTokenLoc, "invalid token in expression");
808 // Parse symbol variant
809 std::pair<StringRef, StringRef> Split;
810 if (!MAI.useParensForSymbolVariant()) {
811 if (FirstTokenKind == AsmToken::String) {
812 if (Lexer.is(AsmToken::At)) {
813 Lexer.Lex(); // eat @
814 SMLoc AtLoc = getLexer().getLoc();
816 if (parseIdentifier(VName))
817 return Error(AtLoc, "expected symbol variant after '@'");
819 Split = std::make_pair(Identifier, VName);
822 Split = Identifier.split('@');
824 } else if (Lexer.is(AsmToken::LParen)) {
825 Lexer.Lex(); // eat (
827 parseIdentifier(VName);
828 if (Lexer.isNot(AsmToken::RParen)) {
829 return Error(Lexer.getTok().getLoc(),
830 "unexpected token in variant, expected ')'");
832 Lexer.Lex(); // eat )
833 Split = std::make_pair(Identifier, VName);
836 EndLoc = SMLoc::getFromPointer(Identifier.end());
838 // This is a symbol reference.
839 StringRef SymbolName = Identifier;
840 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
842 // Lookup the symbol variant if used.
843 if (Split.second.size()) {
844 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
845 if (Variant != MCSymbolRefExpr::VK_Invalid) {
846 SymbolName = Split.first;
847 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
848 Variant = MCSymbolRefExpr::VK_None;
850 return Error(SMLoc::getFromPointer(Split.second.begin()),
851 "invalid variant '" + Split.second + "'");
855 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
857 // If this is an absolute variable reference, substitute it now to preserve
858 // semantics in the face of reassignment.
859 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
861 return Error(EndLoc, "unexpected modifier on variable reference");
863 Res = Sym->getVariableValue();
867 // Otherwise create a symbol ref.
868 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
871 case AsmToken::BigNum:
872 return TokError("literal value out of range for directive");
873 case AsmToken::Integer: {
874 SMLoc Loc = getTok().getLoc();
875 int64_t IntVal = getTok().getIntVal();
876 Res = MCConstantExpr::Create(IntVal, getContext());
877 EndLoc = Lexer.getTok().getEndLoc();
879 // Look for 'b' or 'f' following an Integer as a directional label
880 if (Lexer.getKind() == AsmToken::Identifier) {
881 StringRef IDVal = getTok().getString();
882 // Lookup the symbol variant if used.
883 std::pair<StringRef, StringRef> Split = IDVal.split('@');
884 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
885 if (Split.first.size() != IDVal.size()) {
886 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
887 if (Variant == MCSymbolRefExpr::VK_Invalid)
888 return TokError("invalid variant '" + Split.second + "'");
891 if (IDVal == "f" || IDVal == "b") {
893 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "b");
894 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
895 if (IDVal == "b" && Sym->isUndefined())
896 return Error(Loc, "invalid reference to undefined symbol");
897 EndLoc = Lexer.getTok().getEndLoc();
898 Lex(); // Eat identifier.
903 case AsmToken::Real: {
904 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
905 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
906 Res = MCConstantExpr::Create(IntVal, getContext());
907 EndLoc = Lexer.getTok().getEndLoc();
911 case AsmToken::Dot: {
912 // This is a '.' reference, which references the current PC. Emit a
913 // temporary label to the streamer and refer to it.
914 MCSymbol *Sym = Ctx.CreateTempSymbol();
916 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
917 EndLoc = Lexer.getTok().getEndLoc();
918 Lex(); // Eat identifier.
921 case AsmToken::LParen:
922 Lex(); // Eat the '('.
923 return parseParenExpr(Res, EndLoc);
924 case AsmToken::LBrac:
925 if (!PlatformParser->HasBracketExpressions())
926 return TokError("brackets expression not supported on this target");
927 Lex(); // Eat the '['.
928 return parseBracketExpr(Res, EndLoc);
929 case AsmToken::Minus:
930 Lex(); // Eat the operator.
931 if (parsePrimaryExpr(Res, EndLoc))
933 Res = MCUnaryExpr::CreateMinus(Res, getContext());
936 Lex(); // Eat the operator.
937 if (parsePrimaryExpr(Res, EndLoc))
939 Res = MCUnaryExpr::CreatePlus(Res, getContext());
941 case AsmToken::Tilde:
942 Lex(); // Eat the operator.
943 if (parsePrimaryExpr(Res, EndLoc))
945 Res = MCUnaryExpr::CreateNot(Res, getContext());
950 bool AsmParser::parseExpression(const MCExpr *&Res) {
952 return parseExpression(Res, EndLoc);
956 AsmParser::applyModifierToExpr(const MCExpr *E,
957 MCSymbolRefExpr::VariantKind Variant) {
958 // Ask the target implementation about this expression first.
959 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
962 // Recurse over the given expression, rebuilding it to apply the given variant
963 // if there is exactly one symbol.
964 switch (E->getKind()) {
966 case MCExpr::Constant:
969 case MCExpr::SymbolRef: {
970 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
972 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
973 TokError("invalid variant on expression '" + getTok().getIdentifier() +
974 "' (already modified)");
978 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
981 case MCExpr::Unary: {
982 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
983 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
986 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
989 case MCExpr::Binary: {
990 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
991 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
992 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1002 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
1006 llvm_unreachable("Invalid expression kind!");
1009 /// \brief Parse an expression and return it.
1011 /// expr ::= expr &&,|| expr -> lowest.
1012 /// expr ::= expr |,^,&,! expr
1013 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1014 /// expr ::= expr <<,>> expr
1015 /// expr ::= expr +,- expr
1016 /// expr ::= expr *,/,% expr -> highest.
1017 /// expr ::= primaryexpr
1019 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1020 // Parse the expression.
1022 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1025 // As a special case, we support 'a op b @ modifier' by rewriting the
1026 // expression to include the modifier. This is inefficient, but in general we
1027 // expect users to use 'a@modifier op b'.
1028 if (Lexer.getKind() == AsmToken::At) {
1031 if (Lexer.isNot(AsmToken::Identifier))
1032 return TokError("unexpected symbol modifier following '@'");
1034 MCSymbolRefExpr::VariantKind Variant =
1035 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1036 if (Variant == MCSymbolRefExpr::VK_Invalid)
1037 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1039 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1041 return TokError("invalid modifier '" + getTok().getIdentifier() +
1042 "' (no symbols present)");
1049 // Try to constant fold it up front, if possible.
1051 if (Res->EvaluateAsAbsolute(Value))
1052 Res = MCConstantExpr::Create(Value, getContext());
1057 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1059 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1062 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1065 SMLoc StartLoc = Lexer.getLoc();
1066 if (parseExpression(Expr))
1069 if (!Expr->EvaluateAsAbsolute(Res))
1070 return Error(StartLoc, "expected absolute expression");
1075 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1076 MCBinaryExpr::Opcode &Kind) {
1079 return 0; // not a binop.
1081 // Lowest Precedence: &&, ||
1082 case AsmToken::AmpAmp:
1083 Kind = MCBinaryExpr::LAnd;
1085 case AsmToken::PipePipe:
1086 Kind = MCBinaryExpr::LOr;
1089 // Low Precedence: |, &, ^
1091 // FIXME: gas seems to support '!' as an infix operator?
1092 case AsmToken::Pipe:
1093 Kind = MCBinaryExpr::Or;
1095 case AsmToken::Caret:
1096 Kind = MCBinaryExpr::Xor;
1099 Kind = MCBinaryExpr::And;
1102 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1103 case AsmToken::EqualEqual:
1104 Kind = MCBinaryExpr::EQ;
1106 case AsmToken::ExclaimEqual:
1107 case AsmToken::LessGreater:
1108 Kind = MCBinaryExpr::NE;
1110 case AsmToken::Less:
1111 Kind = MCBinaryExpr::LT;
1113 case AsmToken::LessEqual:
1114 Kind = MCBinaryExpr::LTE;
1116 case AsmToken::Greater:
1117 Kind = MCBinaryExpr::GT;
1119 case AsmToken::GreaterEqual:
1120 Kind = MCBinaryExpr::GTE;
1123 // Intermediate Precedence: <<, >>
1124 case AsmToken::LessLess:
1125 Kind = MCBinaryExpr::Shl;
1127 case AsmToken::GreaterGreater:
1128 Kind = MCBinaryExpr::Shr;
1131 // High Intermediate Precedence: +, -
1132 case AsmToken::Plus:
1133 Kind = MCBinaryExpr::Add;
1135 case AsmToken::Minus:
1136 Kind = MCBinaryExpr::Sub;
1139 // Highest Precedence: *, /, %
1140 case AsmToken::Star:
1141 Kind = MCBinaryExpr::Mul;
1143 case AsmToken::Slash:
1144 Kind = MCBinaryExpr::Div;
1146 case AsmToken::Percent:
1147 Kind = MCBinaryExpr::Mod;
1152 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1153 /// Res contains the LHS of the expression on input.
1154 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1157 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1158 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1160 // If the next token is lower precedence than we are allowed to eat, return
1161 // successfully with what we ate already.
1162 if (TokPrec < Precedence)
1167 // Eat the next primary expression.
1169 if (parsePrimaryExpr(RHS, EndLoc))
1172 // If BinOp binds less tightly with RHS than the operator after RHS, let
1173 // the pending operator take RHS as its LHS.
1174 MCBinaryExpr::Opcode Dummy;
1175 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1176 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1179 // Merge LHS and RHS according to operator.
1180 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1185 /// ::= EndOfStatement
1186 /// ::= Label* Directive ...Operands... EndOfStatement
1187 /// ::= Label* Identifier OperandList* EndOfStatement
1188 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1189 if (Lexer.is(AsmToken::EndOfStatement)) {
1195 // Statements always start with an identifier or are a full line comment.
1196 AsmToken ID = getTok();
1197 SMLoc IDLoc = ID.getLoc();
1199 int64_t LocalLabelVal = -1;
1200 // A full line comment is a '#' as the first token.
1201 if (Lexer.is(AsmToken::Hash))
1202 return parseCppHashLineFilenameComment(IDLoc);
1204 // Allow an integer followed by a ':' as a directional local label.
1205 if (Lexer.is(AsmToken::Integer)) {
1206 LocalLabelVal = getTok().getIntVal();
1207 if (LocalLabelVal < 0) {
1208 if (!TheCondState.Ignore)
1209 return TokError("unexpected token at start of statement");
1212 IDVal = getTok().getString();
1213 Lex(); // Consume the integer token to be used as an identifier token.
1214 if (Lexer.getKind() != AsmToken::Colon) {
1215 if (!TheCondState.Ignore)
1216 return TokError("unexpected token at start of statement");
1219 } else if (Lexer.is(AsmToken::Dot)) {
1220 // Treat '.' as a valid identifier in this context.
1223 } else if (parseIdentifier(IDVal)) {
1224 if (!TheCondState.Ignore)
1225 return TokError("unexpected token at start of statement");
1229 // Handle conditional assembly here before checking for skipping. We
1230 // have to do this so that .endif isn't skipped in a ".if 0" block for
1232 StringMap<DirectiveKind>::const_iterator DirKindIt =
1233 DirectiveKindMap.find(IDVal);
1234 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1236 : DirKindIt->getValue();
1247 return parseDirectiveIf(IDLoc, DirKind);
1249 return parseDirectiveIfb(IDLoc, true);
1251 return parseDirectiveIfb(IDLoc, false);
1253 return parseDirectiveIfc(IDLoc, true);
1255 return parseDirectiveIfeqs(IDLoc);
1257 return parseDirectiveIfc(IDLoc, false);
1259 return parseDirectiveIfdef(IDLoc, true);
1262 return parseDirectiveIfdef(IDLoc, false);
1264 return parseDirectiveElseIf(IDLoc);
1266 return parseDirectiveElse(IDLoc);
1268 return parseDirectiveEndIf(IDLoc);
1271 // Ignore the statement if in the middle of inactive conditional
1273 if (TheCondState.Ignore) {
1274 eatToEndOfStatement();
1278 // FIXME: Recurse on local labels?
1280 // See what kind of statement we have.
1281 switch (Lexer.getKind()) {
1282 case AsmToken::Colon: {
1283 checkForValidSection();
1285 // identifier ':' -> Label.
1288 // Diagnose attempt to use '.' as a label.
1290 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1292 // Diagnose attempt to use a variable as a label.
1294 // FIXME: Diagnostics. Note the location of the definition as a label.
1295 // FIXME: This doesn't diagnose assignment to a symbol which has been
1296 // implicitly marked as external.
1298 if (LocalLabelVal == -1)
1299 Sym = getContext().GetOrCreateSymbol(IDVal);
1301 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1302 if (!Sym->isUndefined() || Sym->isVariable())
1303 return Error(IDLoc, "invalid symbol redefinition");
1306 if (!ParsingInlineAsm)
1309 // If we are generating dwarf for assembly source files then gather the
1310 // info to make a dwarf label entry for this label if needed.
1311 if (getContext().getGenDwarfForAssembly())
1312 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1315 getTargetParser().onLabelParsed(Sym);
1317 // Consume any end of statement token, if present, to avoid spurious
1318 // AddBlankLine calls().
1319 if (Lexer.is(AsmToken::EndOfStatement)) {
1321 if (Lexer.is(AsmToken::Eof))
1328 case AsmToken::Equal:
1329 // identifier '=' ... -> assignment statement
1332 return parseAssignment(IDVal, true);
1334 default: // Normal instruction or directive.
1338 // If macros are enabled, check to see if this is a macro instantiation.
1339 if (areMacrosEnabled())
1340 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1341 return handleMacroEntry(M, IDLoc);
1344 // Otherwise, we have a normal instruction or directive.
1346 // Directives start with "."
1347 if (IDVal[0] == '.' && IDVal != ".") {
1348 // There are several entities interested in parsing directives:
1350 // 1. The target-specific assembly parser. Some directives are target
1351 // specific or may potentially behave differently on certain targets.
1352 // 2. Asm parser extensions. For example, platform-specific parsers
1353 // (like the ELF parser) register themselves as extensions.
1354 // 3. The generic directive parser implemented by this class. These are
1355 // all the directives that behave in a target and platform independent
1356 // manner, or at least have a default behavior that's shared between
1357 // all targets and platforms.
1359 // First query the target-specific parser. It will return 'true' if it
1360 // isn't interested in this directive.
1361 if (!getTargetParser().ParseDirective(ID))
1364 // Next, check the extension directive map to see if any extension has
1365 // registered itself to parse this directive.
1366 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1367 ExtensionDirectiveMap.lookup(IDVal);
1369 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1371 // Finally, if no one else is interested in this directive, it must be
1372 // generic and familiar to this class.
1378 return parseDirectiveSet(IDVal, true);
1380 return parseDirectiveSet(IDVal, false);
1382 return parseDirectiveAscii(IDVal, false);
1385 return parseDirectiveAscii(IDVal, true);
1387 return parseDirectiveValue(1);
1391 return parseDirectiveValue(2);
1395 return parseDirectiveValue(4);
1398 return parseDirectiveValue(8);
1400 return parseDirectiveOctaValue();
1403 return parseDirectiveRealValue(APFloat::IEEEsingle);
1405 return parseDirectiveRealValue(APFloat::IEEEdouble);
1407 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1408 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1411 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1412 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1415 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1417 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1419 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1421 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1423 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1425 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1427 return parseDirectiveOrg();
1429 return parseDirectiveFill();
1431 return parseDirectiveZero();
1433 eatToEndOfStatement(); // .extern is the default, ignore it.
1437 return parseDirectiveSymbolAttribute(MCSA_Global);
1438 case DK_LAZY_REFERENCE:
1439 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1440 case DK_NO_DEAD_STRIP:
1441 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1442 case DK_SYMBOL_RESOLVER:
1443 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1444 case DK_PRIVATE_EXTERN:
1445 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1447 return parseDirectiveSymbolAttribute(MCSA_Reference);
1448 case DK_WEAK_DEFINITION:
1449 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1450 case DK_WEAK_REFERENCE:
1451 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1452 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1453 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1456 return parseDirectiveComm(/*IsLocal=*/false);
1458 return parseDirectiveComm(/*IsLocal=*/true);
1460 return parseDirectiveAbort();
1462 return parseDirectiveInclude();
1464 return parseDirectiveIncbin();
1467 return TokError(Twine(IDVal) + " not supported yet");
1469 return parseDirectiveRept(IDLoc, IDVal);
1471 return parseDirectiveIrp(IDLoc);
1473 return parseDirectiveIrpc(IDLoc);
1475 return parseDirectiveEndr(IDLoc);
1476 case DK_BUNDLE_ALIGN_MODE:
1477 return parseDirectiveBundleAlignMode();
1478 case DK_BUNDLE_LOCK:
1479 return parseDirectiveBundleLock();
1480 case DK_BUNDLE_UNLOCK:
1481 return parseDirectiveBundleUnlock();
1483 return parseDirectiveLEB128(true);
1485 return parseDirectiveLEB128(false);
1488 return parseDirectiveSpace(IDVal);
1490 return parseDirectiveFile(IDLoc);
1492 return parseDirectiveLine();
1494 return parseDirectiveLoc();
1496 return parseDirectiveStabs();
1497 case DK_CFI_SECTIONS:
1498 return parseDirectiveCFISections();
1499 case DK_CFI_STARTPROC:
1500 return parseDirectiveCFIStartProc();
1501 case DK_CFI_ENDPROC:
1502 return parseDirectiveCFIEndProc();
1503 case DK_CFI_DEF_CFA:
1504 return parseDirectiveCFIDefCfa(IDLoc);
1505 case DK_CFI_DEF_CFA_OFFSET:
1506 return parseDirectiveCFIDefCfaOffset();
1507 case DK_CFI_ADJUST_CFA_OFFSET:
1508 return parseDirectiveCFIAdjustCfaOffset();
1509 case DK_CFI_DEF_CFA_REGISTER:
1510 return parseDirectiveCFIDefCfaRegister(IDLoc);
1512 return parseDirectiveCFIOffset(IDLoc);
1513 case DK_CFI_REL_OFFSET:
1514 return parseDirectiveCFIRelOffset(IDLoc);
1515 case DK_CFI_PERSONALITY:
1516 return parseDirectiveCFIPersonalityOrLsda(true);
1518 return parseDirectiveCFIPersonalityOrLsda(false);
1519 case DK_CFI_REMEMBER_STATE:
1520 return parseDirectiveCFIRememberState();
1521 case DK_CFI_RESTORE_STATE:
1522 return parseDirectiveCFIRestoreState();
1523 case DK_CFI_SAME_VALUE:
1524 return parseDirectiveCFISameValue(IDLoc);
1525 case DK_CFI_RESTORE:
1526 return parseDirectiveCFIRestore(IDLoc);
1528 return parseDirectiveCFIEscape();
1529 case DK_CFI_SIGNAL_FRAME:
1530 return parseDirectiveCFISignalFrame();
1531 case DK_CFI_UNDEFINED:
1532 return parseDirectiveCFIUndefined(IDLoc);
1533 case DK_CFI_REGISTER:
1534 return parseDirectiveCFIRegister(IDLoc);
1535 case DK_CFI_WINDOW_SAVE:
1536 return parseDirectiveCFIWindowSave();
1539 return parseDirectiveMacrosOnOff(IDVal);
1541 return parseDirectiveMacro(IDLoc);
1543 return parseDirectiveExitMacro(IDVal);
1546 return parseDirectiveEndMacro(IDVal);
1548 return parseDirectivePurgeMacro(IDLoc);
1550 return parseDirectiveEnd(IDLoc);
1552 return parseDirectiveError(IDLoc, false);
1554 return parseDirectiveError(IDLoc, true);
1556 return parseDirectiveWarning(IDLoc);
1559 return Error(IDLoc, "unknown directive");
1562 // __asm _emit or __asm __emit
1563 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1564 IDVal == "_EMIT" || IDVal == "__EMIT"))
1565 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1568 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1569 return parseDirectiveMSAlign(IDLoc, Info);
1571 checkForValidSection();
1573 // Canonicalize the opcode to lower case.
1574 std::string OpcodeStr = IDVal.lower();
1575 ParseInstructionInfo IInfo(Info.AsmRewrites);
1576 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1577 Info.ParsedOperands);
1578 Info.ParseError = HadError;
1580 // Dump the parsed representation, if requested.
1581 if (getShowParsedOperands()) {
1582 SmallString<256> Str;
1583 raw_svector_ostream OS(Str);
1584 OS << "parsed instruction: [";
1585 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1588 Info.ParsedOperands[i]->print(OS);
1592 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1595 // If we are generating dwarf for the current section then generate a .loc
1596 // directive for the instruction.
1597 if (!HadError && getContext().getGenDwarfForAssembly() &&
1598 getContext().getGenDwarfSectionSyms().count(
1599 getStreamer().getCurrentSection().first)) {
1601 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1603 // If we previously parsed a cpp hash file line comment then make sure the
1604 // current Dwarf File is for the CppHashFilename if not then emit the
1605 // Dwarf File table for it and adjust the line number for the .loc.
1606 if (CppHashFilename.size() != 0) {
1607 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1608 0, StringRef(), CppHashFilename);
1609 getContext().setGenDwarfFileNumber(FileNumber);
1611 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1612 // cache with the different Loc from the call above we save the last
1613 // info we queried here with SrcMgr.FindLineNumber().
1614 unsigned CppHashLocLineNo;
1615 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1616 CppHashLocLineNo = LastQueryLine;
1618 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1619 LastQueryLine = CppHashLocLineNo;
1620 LastQueryIDLoc = CppHashLoc;
1621 LastQueryBuffer = CppHashBuf;
1623 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1626 getStreamer().EmitDwarfLocDirective(
1627 getContext().getGenDwarfFileNumber(), Line, 0,
1628 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1632 // If parsing succeeded, match the instruction.
1635 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1636 Info.ParsedOperands, Out,
1637 ErrorInfo, ParsingInlineAsm);
1640 // Don't skip the rest of the line, the instruction parser is responsible for
1645 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1646 /// since they may not be able to be tokenized to get to the end of line token.
1647 void AsmParser::eatToEndOfLine() {
1648 if (!Lexer.is(AsmToken::EndOfStatement))
1649 Lexer.LexUntilEndOfLine();
1654 /// parseCppHashLineFilenameComment as this:
1655 /// ::= # number "filename"
1656 /// or just as a full line comment if it doesn't have a number and a string.
1657 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1658 Lex(); // Eat the hash token.
1660 if (getLexer().isNot(AsmToken::Integer)) {
1661 // Consume the line since in cases it is not a well-formed line directive,
1662 // as if were simply a full line comment.
1667 int64_t LineNumber = getTok().getIntVal();
1670 if (getLexer().isNot(AsmToken::String)) {
1675 StringRef Filename = getTok().getString();
1676 // Get rid of the enclosing quotes.
1677 Filename = Filename.substr(1, Filename.size() - 2);
1679 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1681 CppHashFilename = Filename;
1682 CppHashLineNumber = LineNumber;
1683 CppHashBuf = CurBuffer;
1685 // Ignore any trailing characters, they're just comment.
1690 /// \brief will use the last parsed cpp hash line filename comment
1691 /// for the Filename and LineNo if any in the diagnostic.
1692 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1693 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1694 raw_ostream &OS = errs();
1696 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1697 const SMLoc &DiagLoc = Diag.getLoc();
1698 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1699 unsigned CppHashBuf =
1700 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1702 // Like SourceMgr::printMessage() we need to print the include stack if any
1703 // before printing the message.
1704 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1705 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1706 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
1707 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1708 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1711 // If we have not parsed a cpp hash line filename comment or the source
1712 // manager changed or buffer changed (like in a nested include) then just
1713 // print the normal diagnostic using its Filename and LineNo.
1714 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1715 DiagBuf != CppHashBuf) {
1716 if (Parser->SavedDiagHandler)
1717 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1719 Diag.print(nullptr, OS);
1723 // Use the CppHashFilename and calculate a line number based on the
1724 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1726 const std::string &Filename = Parser->CppHashFilename;
1728 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1729 int CppHashLocLineNo =
1730 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1732 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1734 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1735 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1736 Diag.getLineContents(), Diag.getRanges());
1738 if (Parser->SavedDiagHandler)
1739 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1741 NewDiag.print(nullptr, OS);
1744 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1745 // difference being that that function accepts '@' as part of identifiers and
1746 // we can't do that. AsmLexer.cpp should probably be changed to handle
1747 // '@' as a special case when needed.
1748 static bool isIdentifierChar(char c) {
1749 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1753 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1754 ArrayRef<MCAsmMacroParameter> Parameters,
1755 ArrayRef<MCAsmMacroArgument> A, const SMLoc &L) {
1756 unsigned NParameters = Parameters.size();
1757 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1758 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1759 return Error(L, "Wrong number of arguments");
1761 // A macro without parameters is handled differently on Darwin:
1762 // gas accepts no arguments and does no substitutions
1763 while (!Body.empty()) {
1764 // Scan for the next substitution.
1765 std::size_t End = Body.size(), Pos = 0;
1766 for (; Pos != End; ++Pos) {
1767 // Check for a substitution or escape.
1768 if (IsDarwin && !NParameters) {
1769 // This macro has no parameters, look for $0, $1, etc.
1770 if (Body[Pos] != '$' || Pos + 1 == End)
1773 char Next = Body[Pos + 1];
1774 if (Next == '$' || Next == 'n' ||
1775 isdigit(static_cast<unsigned char>(Next)))
1778 // This macro has parameters, look for \foo, \bar, etc.
1779 if (Body[Pos] == '\\' && Pos + 1 != End)
1785 OS << Body.slice(0, Pos);
1787 // Check if we reached the end.
1791 if (IsDarwin && !NParameters) {
1792 switch (Body[Pos + 1]) {
1798 // $n => number of arguments
1803 // $[0-9] => argument
1805 // Missing arguments are ignored.
1806 unsigned Index = Body[Pos + 1] - '0';
1807 if (Index >= A.size())
1810 // Otherwise substitute with the token values, with spaces eliminated.
1811 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1812 ie = A[Index].end();
1814 OS << it->getString();
1820 unsigned I = Pos + 1;
1821 while (isIdentifierChar(Body[I]) && I + 1 != End)
1824 const char *Begin = Body.data() + Pos + 1;
1825 StringRef Argument(Begin, I - (Pos + 1));
1827 for (; Index < NParameters; ++Index)
1828 if (Parameters[Index].Name == Argument)
1831 if (Index == NParameters) {
1832 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1835 OS << '\\' << Argument;
1839 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1840 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1841 ie = A[Index].end();
1843 // We expect no quotes around the string's contents when
1844 // parsing for varargs.
1845 if (it->getKind() != AsmToken::String || VarargParameter)
1846 OS << it->getString();
1848 OS << it->getStringContents();
1850 Pos += 1 + Argument.size();
1853 // Update the scan point.
1854 Body = Body.substr(Pos);
1860 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
1861 size_t CondStackDepth)
1862 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
1863 CondStackDepth(CondStackDepth) {}
1865 static bool isOperator(AsmToken::TokenKind kind) {
1869 case AsmToken::Plus:
1870 case AsmToken::Minus:
1871 case AsmToken::Tilde:
1872 case AsmToken::Slash:
1873 case AsmToken::Star:
1875 case AsmToken::Equal:
1876 case AsmToken::EqualEqual:
1877 case AsmToken::Pipe:
1878 case AsmToken::PipePipe:
1879 case AsmToken::Caret:
1881 case AsmToken::AmpAmp:
1882 case AsmToken::Exclaim:
1883 case AsmToken::ExclaimEqual:
1884 case AsmToken::Percent:
1885 case AsmToken::Less:
1886 case AsmToken::LessEqual:
1887 case AsmToken::LessLess:
1888 case AsmToken::LessGreater:
1889 case AsmToken::Greater:
1890 case AsmToken::GreaterEqual:
1891 case AsmToken::GreaterGreater:
1897 class AsmLexerSkipSpaceRAII {
1899 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1900 Lexer.setSkipSpace(SkipSpace);
1903 ~AsmLexerSkipSpaceRAII() {
1904 Lexer.setSkipSpace(true);
1912 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1915 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1916 StringRef Str = parseStringToEndOfStatement();
1917 MA.push_back(AsmToken(AsmToken::String, Str));
1922 unsigned ParenLevel = 0;
1923 unsigned AddTokens = 0;
1925 // Darwin doesn't use spaces to delmit arguments.
1926 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1929 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1930 return TokError("unexpected token in macro instantiation");
1932 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1935 if (Lexer.is(AsmToken::Space)) {
1936 Lex(); // Eat spaces
1938 // Spaces can delimit parameters, but could also be part an expression.
1939 // If the token after a space is an operator, add the token and the next
1940 // one into this argument
1942 if (isOperator(Lexer.getKind())) {
1943 // Check to see whether the token is used as an operator,
1944 // or part of an identifier
1945 const char *NextChar = getTok().getEndLoc().getPointer();
1946 if (*NextChar == ' ')
1950 if (!AddTokens && ParenLevel == 0) {
1956 // handleMacroEntry relies on not advancing the lexer here
1957 // to be able to fill in the remaining default parameter values
1958 if (Lexer.is(AsmToken::EndOfStatement))
1961 // Adjust the current parentheses level.
1962 if (Lexer.is(AsmToken::LParen))
1964 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1967 // Append the token to the current argument list.
1968 MA.push_back(getTok());
1974 if (ParenLevel != 0)
1975 return TokError("unbalanced parentheses in macro argument");
1979 // Parse the macro instantiation arguments.
1980 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1981 MCAsmMacroArguments &A) {
1982 const unsigned NParameters = M ? M->Parameters.size() : 0;
1983 bool NamedParametersFound = false;
1984 SmallVector<SMLoc, 4> FALocs;
1986 A.resize(NParameters);
1987 FALocs.resize(NParameters);
1989 // Parse two kinds of macro invocations:
1990 // - macros defined without any parameters accept an arbitrary number of them
1991 // - macros defined with parameters accept at most that many of them
1992 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
1993 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1995 SMLoc IDLoc = Lexer.getLoc();
1996 MCAsmMacroParameter FA;
1998 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
1999 if (parseIdentifier(FA.Name)) {
2000 Error(IDLoc, "invalid argument identifier for formal argument");
2001 eatToEndOfStatement();
2005 if (!Lexer.is(AsmToken::Equal)) {
2006 TokError("expected '=' after formal parameter identifier");
2007 eatToEndOfStatement();
2012 NamedParametersFound = true;
2015 if (NamedParametersFound && FA.Name.empty()) {
2016 Error(IDLoc, "cannot mix positional and keyword arguments");
2017 eatToEndOfStatement();
2021 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2022 if (parseMacroArgument(FA.Value, Vararg))
2025 unsigned PI = Parameter;
2026 if (!FA.Name.empty()) {
2028 for (FAI = 0; FAI < NParameters; ++FAI)
2029 if (M->Parameters[FAI].Name == FA.Name)
2032 if (FAI >= NParameters) {
2033 assert(M && "expected macro to be defined");
2035 "parameter named '" + FA.Name + "' does not exist for macro '" +
2042 if (!FA.Value.empty()) {
2047 if (FALocs.size() <= PI)
2048 FALocs.resize(PI + 1);
2050 FALocs[PI] = Lexer.getLoc();
2053 // At the end of the statement, fill in remaining arguments that have
2054 // default values. If there aren't any, then the next argument is
2055 // required but missing
2056 if (Lexer.is(AsmToken::EndOfStatement)) {
2057 bool Failure = false;
2058 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2059 if (A[FAI].empty()) {
2060 if (M->Parameters[FAI].Required) {
2061 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2062 "missing value for required parameter "
2063 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2067 if (!M->Parameters[FAI].Value.empty())
2068 A[FAI] = M->Parameters[FAI].Value;
2074 if (Lexer.is(AsmToken::Comma))
2078 return TokError("too many positional arguments");
2081 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2082 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2083 return (I == MacroMap.end()) ? nullptr : I->getValue();
2086 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
2087 MacroMap[Name] = new MCAsmMacro(Macro);
2090 void AsmParser::undefineMacro(StringRef Name) {
2091 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2092 if (I != MacroMap.end()) {
2093 delete I->getValue();
2098 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2099 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2100 // this, although we should protect against infinite loops.
2101 if (ActiveMacros.size() == 20)
2102 return TokError("macros cannot be nested more than 20 levels deep");
2104 MCAsmMacroArguments A;
2105 if (parseMacroArguments(M, A))
2108 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2109 // to hold the macro body with substitutions.
2110 SmallString<256> Buf;
2111 StringRef Body = M->Body;
2112 raw_svector_ostream OS(Buf);
2114 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2117 // We include the .endmacro in the buffer as our cue to exit the macro
2119 OS << ".endmacro\n";
2121 std::unique_ptr<MemoryBuffer> Instantiation =
2122 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2124 // Create the macro instantiation object and add to the current macro
2125 // instantiation stack.
2126 MacroInstantiation *MI = new MacroInstantiation(
2127 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2128 ActiveMacros.push_back(MI);
2130 // Jump to the macro instantiation and prime the lexer.
2131 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2132 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2138 void AsmParser::handleMacroExit() {
2139 // Jump to the EndOfStatement we should return to, and consume it.
2140 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2143 // Pop the instantiation entry.
2144 delete ActiveMacros.back();
2145 ActiveMacros.pop_back();
2148 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2149 switch (Value->getKind()) {
2150 case MCExpr::Binary: {
2151 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2152 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2154 case MCExpr::Target:
2155 case MCExpr::Constant:
2157 case MCExpr::SymbolRef: {
2159 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2161 return isUsedIn(Sym, S.getVariableValue());
2165 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2168 llvm_unreachable("Unknown expr kind!");
2171 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2173 // FIXME: Use better location, we should use proper tokens.
2174 SMLoc EqualLoc = Lexer.getLoc();
2176 const MCExpr *Value;
2177 if (parseExpression(Value))
2180 // Note: we don't count b as used in "a = b". This is to allow
2184 if (Lexer.isNot(AsmToken::EndOfStatement))
2185 return TokError("unexpected token in assignment");
2187 // Eat the end of statement marker.
2190 // Validate that the LHS is allowed to be a variable (either it has not been
2191 // used as a symbol, or it is an absolute symbol).
2192 MCSymbol *Sym = getContext().LookupSymbol(Name);
2194 // Diagnose assignment to a label.
2196 // FIXME: Diagnostics. Note the location of the definition as a label.
2197 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2198 if (isUsedIn(Sym, Value))
2199 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2200 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2201 ; // Allow redefinitions of undefined symbols only used in directives.
2202 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2203 ; // Allow redefinitions of variables that haven't yet been used.
2204 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2205 return Error(EqualLoc, "redefinition of '" + Name + "'");
2206 else if (!Sym->isVariable())
2207 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2208 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2209 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2212 // Don't count these checks as uses.
2213 Sym->setUsed(false);
2214 } else if (Name == ".") {
2215 if (Out.EmitValueToOffset(Value, 0)) {
2216 Error(EqualLoc, "expected absolute expression");
2217 eatToEndOfStatement();
2221 Sym = getContext().GetOrCreateSymbol(Name);
2223 // Do the assignment.
2224 Out.EmitAssignment(Sym, Value);
2226 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2231 /// parseIdentifier:
2234 bool AsmParser::parseIdentifier(StringRef &Res) {
2235 // The assembler has relaxed rules for accepting identifiers, in particular we
2236 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2237 // separate tokens. At this level, we have already lexed so we cannot (currently)
2238 // handle this as a context dependent token, instead we detect adjacent tokens
2239 // and return the combined identifier.
2240 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2241 SMLoc PrefixLoc = getLexer().getLoc();
2243 // Consume the prefix character, and check for a following identifier.
2245 if (Lexer.isNot(AsmToken::Identifier))
2248 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2249 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2252 // Construct the joined identifier and consume the token.
2254 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2259 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2262 Res = getTok().getIdentifier();
2264 Lex(); // Consume the identifier token.
2269 /// parseDirectiveSet:
2270 /// ::= .equ identifier ',' expression
2271 /// ::= .equiv identifier ',' expression
2272 /// ::= .set identifier ',' expression
2273 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2276 if (parseIdentifier(Name))
2277 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2279 if (getLexer().isNot(AsmToken::Comma))
2280 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2283 return parseAssignment(Name, allow_redef, true);
2286 bool AsmParser::parseEscapedString(std::string &Data) {
2287 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2290 StringRef Str = getTok().getStringContents();
2291 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2292 if (Str[i] != '\\') {
2297 // Recognize escaped characters. Note that this escape semantics currently
2298 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2301 return TokError("unexpected backslash at end of string");
2303 // Recognize octal sequences.
2304 if ((unsigned)(Str[i] - '0') <= 7) {
2305 // Consume up to three octal characters.
2306 unsigned Value = Str[i] - '0';
2308 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2310 Value = Value * 8 + (Str[i] - '0');
2312 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2314 Value = Value * 8 + (Str[i] - '0');
2319 return TokError("invalid octal escape sequence (out of range)");
2321 Data += (unsigned char)Value;
2325 // Otherwise recognize individual escapes.
2328 // Just reject invalid escape sequences for now.
2329 return TokError("invalid escape sequence (unrecognized character)");
2331 case 'b': Data += '\b'; break;
2332 case 'f': Data += '\f'; break;
2333 case 'n': Data += '\n'; break;
2334 case 'r': Data += '\r'; break;
2335 case 't': Data += '\t'; break;
2336 case '"': Data += '"'; break;
2337 case '\\': Data += '\\'; break;
2344 /// parseDirectiveAscii:
2345 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2346 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2347 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2348 checkForValidSection();
2351 if (getLexer().isNot(AsmToken::String))
2352 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2355 if (parseEscapedString(Data))
2358 getStreamer().EmitBytes(Data);
2360 getStreamer().EmitBytes(StringRef("\0", 1));
2364 if (getLexer().is(AsmToken::EndOfStatement))
2367 if (getLexer().isNot(AsmToken::Comma))
2368 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2377 /// parseDirectiveValue
2378 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2379 bool AsmParser::parseDirectiveValue(unsigned Size) {
2380 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2381 checkForValidSection();
2384 const MCExpr *Value;
2385 SMLoc ExprLoc = getLexer().getLoc();
2386 if (parseExpression(Value))
2389 // Special case constant expressions to match code generator.
2390 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2391 assert(Size <= 8 && "Invalid size");
2392 uint64_t IntValue = MCE->getValue();
2393 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2394 return Error(ExprLoc, "literal value out of range for directive");
2395 getStreamer().EmitIntValue(IntValue, Size);
2397 getStreamer().EmitValue(Value, Size, ExprLoc);
2399 if (getLexer().is(AsmToken::EndOfStatement))
2402 // FIXME: Improve diagnostic.
2403 if (getLexer().isNot(AsmToken::Comma))
2404 return TokError("unexpected token in directive");
2413 /// ParseDirectiveOctaValue
2414 /// ::= .octa [ hexconstant (, hexconstant)* ]
2415 bool AsmParser::parseDirectiveOctaValue() {
2416 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2417 checkForValidSection();
2420 if (Lexer.getKind() == AsmToken::Error)
2422 if (Lexer.getKind() != AsmToken::Integer &&
2423 Lexer.getKind() != AsmToken::BigNum)
2424 return TokError("unknown token in expression");
2426 SMLoc ExprLoc = getLexer().getLoc();
2427 APInt IntValue = getTok().getAPIntVal();
2431 if (IntValue.isIntN(64)) {
2433 lo = IntValue.getZExtValue();
2434 } else if (IntValue.isIntN(128)) {
2435 // It might actually have more than 128 bits, but the top ones are zero.
2436 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2437 lo = IntValue.getLoBits(64).getZExtValue();
2439 return Error(ExprLoc, "literal value out of range for directive");
2441 if (MAI.isLittleEndian()) {
2442 getStreamer().EmitIntValue(lo, 8);
2443 getStreamer().EmitIntValue(hi, 8);
2445 getStreamer().EmitIntValue(hi, 8);
2446 getStreamer().EmitIntValue(lo, 8);
2449 if (getLexer().is(AsmToken::EndOfStatement))
2452 // FIXME: Improve diagnostic.
2453 if (getLexer().isNot(AsmToken::Comma))
2454 return TokError("unexpected token in directive");
2463 /// parseDirectiveRealValue
2464 /// ::= (.single | .double) [ expression (, expression)* ]
2465 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2466 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2467 checkForValidSection();
2470 // We don't truly support arithmetic on floating point expressions, so we
2471 // have to manually parse unary prefixes.
2473 if (getLexer().is(AsmToken::Minus)) {
2476 } else if (getLexer().is(AsmToken::Plus))
2479 if (getLexer().isNot(AsmToken::Integer) &&
2480 getLexer().isNot(AsmToken::Real) &&
2481 getLexer().isNot(AsmToken::Identifier))
2482 return TokError("unexpected token in directive");
2484 // Convert to an APFloat.
2485 APFloat Value(Semantics);
2486 StringRef IDVal = getTok().getString();
2487 if (getLexer().is(AsmToken::Identifier)) {
2488 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2489 Value = APFloat::getInf(Semantics);
2490 else if (!IDVal.compare_lower("nan"))
2491 Value = APFloat::getNaN(Semantics, false, ~0);
2493 return TokError("invalid floating point literal");
2494 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2495 APFloat::opInvalidOp)
2496 return TokError("invalid floating point literal");
2500 // Consume the numeric token.
2503 // Emit the value as an integer.
2504 APInt AsInt = Value.bitcastToAPInt();
2505 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2506 AsInt.getBitWidth() / 8);
2508 if (getLexer().is(AsmToken::EndOfStatement))
2511 if (getLexer().isNot(AsmToken::Comma))
2512 return TokError("unexpected token in directive");
2521 /// parseDirectiveZero
2522 /// ::= .zero expression
2523 bool AsmParser::parseDirectiveZero() {
2524 checkForValidSection();
2527 if (parseAbsoluteExpression(NumBytes))
2531 if (getLexer().is(AsmToken::Comma)) {
2533 if (parseAbsoluteExpression(Val))
2537 if (getLexer().isNot(AsmToken::EndOfStatement))
2538 return TokError("unexpected token in '.zero' directive");
2542 getStreamer().EmitFill(NumBytes, Val);
2547 /// parseDirectiveFill
2548 /// ::= .fill expression [ , expression [ , expression ] ]
2549 bool AsmParser::parseDirectiveFill() {
2550 checkForValidSection();
2552 SMLoc RepeatLoc = getLexer().getLoc();
2554 if (parseAbsoluteExpression(NumValues))
2557 if (NumValues < 0) {
2559 "'.fill' directive with negative repeat count has no effect");
2563 int64_t FillSize = 1;
2564 int64_t FillExpr = 0;
2566 SMLoc SizeLoc, ExprLoc;
2567 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2568 if (getLexer().isNot(AsmToken::Comma))
2569 return TokError("unexpected token in '.fill' directive");
2572 SizeLoc = getLexer().getLoc();
2573 if (parseAbsoluteExpression(FillSize))
2576 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2577 if (getLexer().isNot(AsmToken::Comma))
2578 return TokError("unexpected token in '.fill' directive");
2581 ExprLoc = getLexer().getLoc();
2582 if (parseAbsoluteExpression(FillExpr))
2585 if (getLexer().isNot(AsmToken::EndOfStatement))
2586 return TokError("unexpected token in '.fill' directive");
2593 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2597 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2601 if (!isUInt<32>(FillExpr) && FillSize > 4)
2602 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2604 if (NumValues > 0) {
2605 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2606 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2607 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2608 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2609 if (NonZeroFillSize < FillSize)
2610 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2617 /// parseDirectiveOrg
2618 /// ::= .org expression [ , expression ]
2619 bool AsmParser::parseDirectiveOrg() {
2620 checkForValidSection();
2622 const MCExpr *Offset;
2623 SMLoc Loc = getTok().getLoc();
2624 if (parseExpression(Offset))
2627 // Parse optional fill expression.
2628 int64_t FillExpr = 0;
2629 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2630 if (getLexer().isNot(AsmToken::Comma))
2631 return TokError("unexpected token in '.org' directive");
2634 if (parseAbsoluteExpression(FillExpr))
2637 if (getLexer().isNot(AsmToken::EndOfStatement))
2638 return TokError("unexpected token in '.org' directive");
2643 // Only limited forms of relocatable expressions are accepted here, it
2644 // has to be relative to the current section. The streamer will return
2645 // 'true' if the expression wasn't evaluatable.
2646 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2647 return Error(Loc, "expected assembly-time absolute expression");
2652 /// parseDirectiveAlign
2653 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2654 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2655 checkForValidSection();
2657 SMLoc AlignmentLoc = getLexer().getLoc();
2659 if (parseAbsoluteExpression(Alignment))
2663 bool HasFillExpr = false;
2664 int64_t FillExpr = 0;
2665 int64_t MaxBytesToFill = 0;
2666 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2667 if (getLexer().isNot(AsmToken::Comma))
2668 return TokError("unexpected token in directive");
2671 // The fill expression can be omitted while specifying a maximum number of
2672 // alignment bytes, e.g:
2674 if (getLexer().isNot(AsmToken::Comma)) {
2676 if (parseAbsoluteExpression(FillExpr))
2680 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2681 if (getLexer().isNot(AsmToken::Comma))
2682 return TokError("unexpected token in directive");
2685 MaxBytesLoc = getLexer().getLoc();
2686 if (parseAbsoluteExpression(MaxBytesToFill))
2689 if (getLexer().isNot(AsmToken::EndOfStatement))
2690 return TokError("unexpected token in directive");
2699 // Compute alignment in bytes.
2701 // FIXME: Diagnose overflow.
2702 if (Alignment >= 32) {
2703 Error(AlignmentLoc, "invalid alignment value");
2707 Alignment = 1ULL << Alignment;
2709 // Reject alignments that aren't a power of two, for gas compatibility.
2710 if (!isPowerOf2_64(Alignment))
2711 Error(AlignmentLoc, "alignment must be a power of 2");
2714 // Diagnose non-sensical max bytes to align.
2715 if (MaxBytesLoc.isValid()) {
2716 if (MaxBytesToFill < 1) {
2717 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2718 "many bytes, ignoring maximum bytes expression");
2722 if (MaxBytesToFill >= Alignment) {
2723 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2729 // Check whether we should use optimal code alignment for this .align
2731 const MCSection *Section = getStreamer().getCurrentSection().first;
2732 assert(Section && "must have section to emit alignment");
2733 bool UseCodeAlign = Section->UseCodeAlign();
2734 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2735 ValueSize == 1 && UseCodeAlign) {
2736 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2738 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2739 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2746 /// parseDirectiveFile
2747 /// ::= .file [number] filename
2748 /// ::= .file number directory filename
2749 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2750 // FIXME: I'm not sure what this is.
2751 int64_t FileNumber = -1;
2752 SMLoc FileNumberLoc = getLexer().getLoc();
2753 if (getLexer().is(AsmToken::Integer)) {
2754 FileNumber = getTok().getIntVal();
2758 return TokError("file number less than one");
2761 if (getLexer().isNot(AsmToken::String))
2762 return TokError("unexpected token in '.file' directive");
2764 // Usually the directory and filename together, otherwise just the directory.
2765 // Allow the strings to have escaped octal character sequence.
2766 std::string Path = getTok().getString();
2767 if (parseEscapedString(Path))
2771 StringRef Directory;
2773 std::string FilenameData;
2774 if (getLexer().is(AsmToken::String)) {
2775 if (FileNumber == -1)
2776 return TokError("explicit path specified, but no file number");
2777 if (parseEscapedString(FilenameData))
2779 Filename = FilenameData;
2786 if (getLexer().isNot(AsmToken::EndOfStatement))
2787 return TokError("unexpected token in '.file' directive");
2789 if (FileNumber == -1)
2790 getStreamer().EmitFileDirective(Filename);
2792 if (getContext().getGenDwarfForAssembly() == true)
2794 "input can't have .file dwarf directives when -g is "
2795 "used to generate dwarf debug info for assembly code");
2797 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2799 Error(FileNumberLoc, "file number already allocated");
2805 /// parseDirectiveLine
2806 /// ::= .line [number]
2807 bool AsmParser::parseDirectiveLine() {
2808 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2809 if (getLexer().isNot(AsmToken::Integer))
2810 return TokError("unexpected token in '.line' directive");
2812 int64_t LineNumber = getTok().getIntVal();
2816 // FIXME: Do something with the .line.
2819 if (getLexer().isNot(AsmToken::EndOfStatement))
2820 return TokError("unexpected token in '.line' directive");
2825 /// parseDirectiveLoc
2826 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2827 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2828 /// The first number is a file number, must have been previously assigned with
2829 /// a .file directive, the second number is the line number and optionally the
2830 /// third number is a column position (zero if not specified). The remaining
2831 /// optional items are .loc sub-directives.
2832 bool AsmParser::parseDirectiveLoc() {
2833 if (getLexer().isNot(AsmToken::Integer))
2834 return TokError("unexpected token in '.loc' directive");
2835 int64_t FileNumber = getTok().getIntVal();
2837 return TokError("file number less than one in '.loc' directive");
2838 if (!getContext().isValidDwarfFileNumber(FileNumber))
2839 return TokError("unassigned file number in '.loc' directive");
2842 int64_t LineNumber = 0;
2843 if (getLexer().is(AsmToken::Integer)) {
2844 LineNumber = getTok().getIntVal();
2846 return TokError("line number less than zero in '.loc' directive");
2850 int64_t ColumnPos = 0;
2851 if (getLexer().is(AsmToken::Integer)) {
2852 ColumnPos = getTok().getIntVal();
2854 return TokError("column position less than zero in '.loc' directive");
2858 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2860 int64_t Discriminator = 0;
2861 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2863 if (getLexer().is(AsmToken::EndOfStatement))
2867 SMLoc Loc = getTok().getLoc();
2868 if (parseIdentifier(Name))
2869 return TokError("unexpected token in '.loc' directive");
2871 if (Name == "basic_block")
2872 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2873 else if (Name == "prologue_end")
2874 Flags |= DWARF2_FLAG_PROLOGUE_END;
2875 else if (Name == "epilogue_begin")
2876 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2877 else if (Name == "is_stmt") {
2878 Loc = getTok().getLoc();
2879 const MCExpr *Value;
2880 if (parseExpression(Value))
2882 // The expression must be the constant 0 or 1.
2883 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2884 int Value = MCE->getValue();
2886 Flags &= ~DWARF2_FLAG_IS_STMT;
2887 else if (Value == 1)
2888 Flags |= DWARF2_FLAG_IS_STMT;
2890 return Error(Loc, "is_stmt value not 0 or 1");
2892 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2894 } else if (Name == "isa") {
2895 Loc = getTok().getLoc();
2896 const MCExpr *Value;
2897 if (parseExpression(Value))
2899 // The expression must be a constant greater or equal to 0.
2900 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2901 int Value = MCE->getValue();
2903 return Error(Loc, "isa number less than zero");
2906 return Error(Loc, "isa number not a constant value");
2908 } else if (Name == "discriminator") {
2909 if (parseAbsoluteExpression(Discriminator))
2912 return Error(Loc, "unknown sub-directive in '.loc' directive");
2915 if (getLexer().is(AsmToken::EndOfStatement))
2920 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2921 Isa, Discriminator, StringRef());
2926 /// parseDirectiveStabs
2927 /// ::= .stabs string, number, number, number
2928 bool AsmParser::parseDirectiveStabs() {
2929 return TokError("unsupported directive '.stabs'");
2932 /// parseDirectiveCFISections
2933 /// ::= .cfi_sections section [, section]
2934 bool AsmParser::parseDirectiveCFISections() {
2939 if (parseIdentifier(Name))
2940 return TokError("Expected an identifier");
2942 if (Name == ".eh_frame")
2944 else if (Name == ".debug_frame")
2947 if (getLexer().is(AsmToken::Comma)) {
2950 if (parseIdentifier(Name))
2951 return TokError("Expected an identifier");
2953 if (Name == ".eh_frame")
2955 else if (Name == ".debug_frame")
2959 getStreamer().EmitCFISections(EH, Debug);
2963 /// parseDirectiveCFIStartProc
2964 /// ::= .cfi_startproc [simple]
2965 bool AsmParser::parseDirectiveCFIStartProc() {
2967 if (getLexer().isNot(AsmToken::EndOfStatement))
2968 if (parseIdentifier(Simple) || Simple != "simple")
2969 return TokError("unexpected token in .cfi_startproc directive");
2971 getStreamer().EmitCFIStartProc(!Simple.empty());
2975 /// parseDirectiveCFIEndProc
2976 /// ::= .cfi_endproc
2977 bool AsmParser::parseDirectiveCFIEndProc() {
2978 getStreamer().EmitCFIEndProc();
2982 /// \brief parse register name or number.
2983 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2984 SMLoc DirectiveLoc) {
2987 if (getLexer().isNot(AsmToken::Integer)) {
2988 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2990 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2992 return parseAbsoluteExpression(Register);
2997 /// parseDirectiveCFIDefCfa
2998 /// ::= .cfi_def_cfa register, offset
2999 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3000 int64_t Register = 0;
3001 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3004 if (getLexer().isNot(AsmToken::Comma))
3005 return TokError("unexpected token in directive");
3009 if (parseAbsoluteExpression(Offset))
3012 getStreamer().EmitCFIDefCfa(Register, Offset);
3016 /// parseDirectiveCFIDefCfaOffset
3017 /// ::= .cfi_def_cfa_offset offset
3018 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3020 if (parseAbsoluteExpression(Offset))
3023 getStreamer().EmitCFIDefCfaOffset(Offset);
3027 /// parseDirectiveCFIRegister
3028 /// ::= .cfi_register register, register
3029 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3030 int64_t Register1 = 0;
3031 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3034 if (getLexer().isNot(AsmToken::Comma))
3035 return TokError("unexpected token in directive");
3038 int64_t Register2 = 0;
3039 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3042 getStreamer().EmitCFIRegister(Register1, Register2);
3046 /// parseDirectiveCFIWindowSave
3047 /// ::= .cfi_window_save
3048 bool AsmParser::parseDirectiveCFIWindowSave() {
3049 getStreamer().EmitCFIWindowSave();
3053 /// parseDirectiveCFIAdjustCfaOffset
3054 /// ::= .cfi_adjust_cfa_offset adjustment
3055 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3056 int64_t Adjustment = 0;
3057 if (parseAbsoluteExpression(Adjustment))
3060 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3064 /// parseDirectiveCFIDefCfaRegister
3065 /// ::= .cfi_def_cfa_register register
3066 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3067 int64_t Register = 0;
3068 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3071 getStreamer().EmitCFIDefCfaRegister(Register);
3075 /// parseDirectiveCFIOffset
3076 /// ::= .cfi_offset register, offset
3077 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3078 int64_t Register = 0;
3081 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3084 if (getLexer().isNot(AsmToken::Comma))
3085 return TokError("unexpected token in directive");
3088 if (parseAbsoluteExpression(Offset))
3091 getStreamer().EmitCFIOffset(Register, Offset);
3095 /// parseDirectiveCFIRelOffset
3096 /// ::= .cfi_rel_offset register, offset
3097 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3098 int64_t Register = 0;
3100 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3103 if (getLexer().isNot(AsmToken::Comma))
3104 return TokError("unexpected token in directive");
3108 if (parseAbsoluteExpression(Offset))
3111 getStreamer().EmitCFIRelOffset(Register, Offset);
3115 static bool isValidEncoding(int64_t Encoding) {
3116 if (Encoding & ~0xff)
3119 if (Encoding == dwarf::DW_EH_PE_omit)
3122 const unsigned Format = Encoding & 0xf;
3123 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3124 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3125 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3126 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3129 const unsigned Application = Encoding & 0x70;
3130 if (Application != dwarf::DW_EH_PE_absptr &&
3131 Application != dwarf::DW_EH_PE_pcrel)
3137 /// parseDirectiveCFIPersonalityOrLsda
3138 /// IsPersonality true for cfi_personality, false for cfi_lsda
3139 /// ::= .cfi_personality encoding, [symbol_name]
3140 /// ::= .cfi_lsda encoding, [symbol_name]
3141 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3142 int64_t Encoding = 0;
3143 if (parseAbsoluteExpression(Encoding))
3145 if (Encoding == dwarf::DW_EH_PE_omit)
3148 if (!isValidEncoding(Encoding))
3149 return TokError("unsupported encoding.");
3151 if (getLexer().isNot(AsmToken::Comma))
3152 return TokError("unexpected token in directive");
3156 if (parseIdentifier(Name))
3157 return TokError("expected identifier in directive");
3159 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3162 getStreamer().EmitCFIPersonality(Sym, Encoding);
3164 getStreamer().EmitCFILsda(Sym, Encoding);
3168 /// parseDirectiveCFIRememberState
3169 /// ::= .cfi_remember_state
3170 bool AsmParser::parseDirectiveCFIRememberState() {
3171 getStreamer().EmitCFIRememberState();
3175 /// parseDirectiveCFIRestoreState
3176 /// ::= .cfi_remember_state
3177 bool AsmParser::parseDirectiveCFIRestoreState() {
3178 getStreamer().EmitCFIRestoreState();
3182 /// parseDirectiveCFISameValue
3183 /// ::= .cfi_same_value register
3184 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3185 int64_t Register = 0;
3187 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3190 getStreamer().EmitCFISameValue(Register);
3194 /// parseDirectiveCFIRestore
3195 /// ::= .cfi_restore register
3196 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3197 int64_t Register = 0;
3198 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3201 getStreamer().EmitCFIRestore(Register);
3205 /// parseDirectiveCFIEscape
3206 /// ::= .cfi_escape expression[,...]
3207 bool AsmParser::parseDirectiveCFIEscape() {
3210 if (parseAbsoluteExpression(CurrValue))
3213 Values.push_back((uint8_t)CurrValue);
3215 while (getLexer().is(AsmToken::Comma)) {
3218 if (parseAbsoluteExpression(CurrValue))
3221 Values.push_back((uint8_t)CurrValue);
3224 getStreamer().EmitCFIEscape(Values);
3228 /// parseDirectiveCFISignalFrame
3229 /// ::= .cfi_signal_frame
3230 bool AsmParser::parseDirectiveCFISignalFrame() {
3231 if (getLexer().isNot(AsmToken::EndOfStatement))
3232 return Error(getLexer().getLoc(),
3233 "unexpected token in '.cfi_signal_frame'");
3235 getStreamer().EmitCFISignalFrame();
3239 /// parseDirectiveCFIUndefined
3240 /// ::= .cfi_undefined register
3241 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3242 int64_t Register = 0;
3244 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3247 getStreamer().EmitCFIUndefined(Register);
3251 /// parseDirectiveMacrosOnOff
3254 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3255 if (getLexer().isNot(AsmToken::EndOfStatement))
3256 return Error(getLexer().getLoc(),
3257 "unexpected token in '" + Directive + "' directive");
3259 setMacrosEnabled(Directive == ".macros_on");
3263 /// parseDirectiveMacro
3264 /// ::= .macro name[,] [parameters]
3265 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3267 if (parseIdentifier(Name))
3268 return TokError("expected identifier in '.macro' directive");
3270 if (getLexer().is(AsmToken::Comma))
3273 MCAsmMacroParameters Parameters;
3274 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3276 if (Parameters.size() && Parameters.back().Vararg)
3277 return Error(Lexer.getLoc(),
3278 "Vararg parameter '" + Parameters.back().Name +
3279 "' should be last one in the list of parameters.");
3281 MCAsmMacroParameter Parameter;
3282 if (parseIdentifier(Parameter.Name))
3283 return TokError("expected identifier in '.macro' directive");
3285 if (Lexer.is(AsmToken::Colon)) {
3286 Lex(); // consume ':'
3289 StringRef Qualifier;
3291 QualLoc = Lexer.getLoc();
3292 if (parseIdentifier(Qualifier))
3293 return Error(QualLoc, "missing parameter qualifier for "
3294 "'" + Parameter.Name + "' in macro '" + Name + "'");
3296 if (Qualifier == "req")
3297 Parameter.Required = true;
3298 else if (Qualifier == "vararg")
3299 Parameter.Vararg = true;
3301 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3302 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3305 if (getLexer().is(AsmToken::Equal)) {
3310 ParamLoc = Lexer.getLoc();
3311 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3314 if (Parameter.Required)
3315 Warning(ParamLoc, "pointless default value for required parameter "
3316 "'" + Parameter.Name + "' in macro '" + Name + "'");
3319 Parameters.push_back(Parameter);
3321 if (getLexer().is(AsmToken::Comma))
3325 // Eat the end of statement.
3328 AsmToken EndToken, StartToken = getTok();
3329 unsigned MacroDepth = 0;
3331 // Lex the macro definition.
3333 // Check whether we have reached the end of the file.
3334 if (getLexer().is(AsmToken::Eof))
3335 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3337 // Otherwise, check whether we have reach the .endmacro.
3338 if (getLexer().is(AsmToken::Identifier)) {
3339 if (getTok().getIdentifier() == ".endm" ||
3340 getTok().getIdentifier() == ".endmacro") {
3341 if (MacroDepth == 0) { // Outermost macro.
3342 EndToken = getTok();
3344 if (getLexer().isNot(AsmToken::EndOfStatement))
3345 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3349 // Otherwise we just found the end of an inner macro.
3352 } else if (getTok().getIdentifier() == ".macro") {
3353 // We allow nested macros. Those aren't instantiated until the outermost
3354 // macro is expanded so just ignore them for now.
3359 // Otherwise, scan til the end of the statement.
3360 eatToEndOfStatement();
3363 if (lookupMacro(Name)) {
3364 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3367 const char *BodyStart = StartToken.getLoc().getPointer();
3368 const char *BodyEnd = EndToken.getLoc().getPointer();
3369 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3370 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3371 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3375 /// checkForBadMacro
3377 /// With the support added for named parameters there may be code out there that
3378 /// is transitioning from positional parameters. In versions of gas that did
3379 /// not support named parameters they would be ignored on the macro definition.
3380 /// But to support both styles of parameters this is not possible so if a macro
3381 /// definition has named parameters but does not use them and has what appears
3382 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3383 /// warning that the positional parameter found in body which have no effect.
3384 /// Hoping the developer will either remove the named parameters from the macro
3385 /// definition so the positional parameters get used if that was what was
3386 /// intended or change the macro to use the named parameters. It is possible
3387 /// this warning will trigger when the none of the named parameters are used
3388 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3389 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3391 ArrayRef<MCAsmMacroParameter> Parameters) {
3392 // If this macro is not defined with named parameters the warning we are
3393 // checking for here doesn't apply.
3394 unsigned NParameters = Parameters.size();
3395 if (NParameters == 0)
3398 bool NamedParametersFound = false;
3399 bool PositionalParametersFound = false;
3401 // Look at the body of the macro for use of both the named parameters and what
3402 // are likely to be positional parameters. This is what expandMacro() is
3403 // doing when it finds the parameters in the body.
3404 while (!Body.empty()) {
3405 // Scan for the next possible parameter.
3406 std::size_t End = Body.size(), Pos = 0;
3407 for (; Pos != End; ++Pos) {
3408 // Check for a substitution or escape.
3409 // This macro is defined with parameters, look for \foo, \bar, etc.
3410 if (Body[Pos] == '\\' && Pos + 1 != End)
3413 // This macro should have parameters, but look for $0, $1, ..., $n too.
3414 if (Body[Pos] != '$' || Pos + 1 == End)
3416 char Next = Body[Pos + 1];
3417 if (Next == '$' || Next == 'n' ||
3418 isdigit(static_cast<unsigned char>(Next)))
3422 // Check if we reached the end.
3426 if (Body[Pos] == '$') {
3427 switch (Body[Pos + 1]) {
3432 // $n => number of arguments
3434 PositionalParametersFound = true;
3437 // $[0-9] => argument
3439 PositionalParametersFound = true;
3445 unsigned I = Pos + 1;
3446 while (isIdentifierChar(Body[I]) && I + 1 != End)
3449 const char *Begin = Body.data() + Pos + 1;
3450 StringRef Argument(Begin, I - (Pos + 1));
3452 for (; Index < NParameters; ++Index)
3453 if (Parameters[Index].Name == Argument)
3456 if (Index == NParameters) {
3457 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3463 NamedParametersFound = true;
3464 Pos += 1 + Argument.size();
3467 // Update the scan point.
3468 Body = Body.substr(Pos);
3471 if (!NamedParametersFound && PositionalParametersFound)
3472 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3473 "used in macro body, possible positional parameter "
3474 "found in body which will have no effect");
3477 /// parseDirectiveExitMacro
3479 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3480 if (getLexer().isNot(AsmToken::EndOfStatement))
3481 return TokError("unexpected token in '" + Directive + "' directive");
3483 if (!isInsideMacroInstantiation())
3484 return TokError("unexpected '" + Directive + "' in file, "
3485 "no current macro definition");
3487 // Exit all conditionals that are active in the current macro.
3488 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3489 TheCondState = TheCondStack.back();
3490 TheCondStack.pop_back();
3497 /// parseDirectiveEndMacro
3500 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3501 if (getLexer().isNot(AsmToken::EndOfStatement))
3502 return TokError("unexpected token in '" + Directive + "' directive");
3504 // If we are inside a macro instantiation, terminate the current
3506 if (isInsideMacroInstantiation()) {
3511 // Otherwise, this .endmacro is a stray entry in the file; well formed
3512 // .endmacro directives are handled during the macro definition parsing.
3513 return TokError("unexpected '" + Directive + "' in file, "
3514 "no current macro definition");
3517 /// parseDirectivePurgeMacro
3519 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3521 if (parseIdentifier(Name))
3522 return TokError("expected identifier in '.purgem' directive");
3524 if (getLexer().isNot(AsmToken::EndOfStatement))
3525 return TokError("unexpected token in '.purgem' directive");
3527 if (!lookupMacro(Name))
3528 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3530 undefineMacro(Name);
3534 /// parseDirectiveBundleAlignMode
3535 /// ::= {.bundle_align_mode} expression
3536 bool AsmParser::parseDirectiveBundleAlignMode() {
3537 checkForValidSection();
3539 // Expect a single argument: an expression that evaluates to a constant
3540 // in the inclusive range 0-30.
3541 SMLoc ExprLoc = getLexer().getLoc();
3542 int64_t AlignSizePow2;
3543 if (parseAbsoluteExpression(AlignSizePow2))
3545 else if (getLexer().isNot(AsmToken::EndOfStatement))
3546 return TokError("unexpected token after expression in"
3547 " '.bundle_align_mode' directive");
3548 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3549 return Error(ExprLoc,
3550 "invalid bundle alignment size (expected between 0 and 30)");
3554 // Because of AlignSizePow2's verified range we can safely truncate it to
3556 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3560 /// parseDirectiveBundleLock
3561 /// ::= {.bundle_lock} [align_to_end]
3562 bool AsmParser::parseDirectiveBundleLock() {
3563 checkForValidSection();
3564 bool AlignToEnd = false;
3566 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3568 SMLoc Loc = getTok().getLoc();
3569 const char *kInvalidOptionError =
3570 "invalid option for '.bundle_lock' directive";
3572 if (parseIdentifier(Option))
3573 return Error(Loc, kInvalidOptionError);
3575 if (Option != "align_to_end")
3576 return Error(Loc, kInvalidOptionError);
3577 else if (getLexer().isNot(AsmToken::EndOfStatement))
3579 "unexpected token after '.bundle_lock' directive option");
3585 getStreamer().EmitBundleLock(AlignToEnd);
3589 /// parseDirectiveBundleLock
3590 /// ::= {.bundle_lock}
3591 bool AsmParser::parseDirectiveBundleUnlock() {
3592 checkForValidSection();
3594 if (getLexer().isNot(AsmToken::EndOfStatement))
3595 return TokError("unexpected token in '.bundle_unlock' directive");
3598 getStreamer().EmitBundleUnlock();
3602 /// parseDirectiveSpace
3603 /// ::= (.skip | .space) expression [ , expression ]
3604 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3605 checkForValidSection();
3608 if (parseAbsoluteExpression(NumBytes))
3611 int64_t FillExpr = 0;
3612 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3613 if (getLexer().isNot(AsmToken::Comma))
3614 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3617 if (parseAbsoluteExpression(FillExpr))
3620 if (getLexer().isNot(AsmToken::EndOfStatement))
3621 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3627 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3630 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3631 getStreamer().EmitFill(NumBytes, FillExpr);
3636 /// parseDirectiveLEB128
3637 /// ::= (.sleb128 | .uleb128) expression
3638 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3639 checkForValidSection();
3640 const MCExpr *Value;
3642 if (parseExpression(Value))
3645 if (getLexer().isNot(AsmToken::EndOfStatement))
3646 return TokError("unexpected token in directive");
3649 getStreamer().EmitSLEB128Value(Value);
3651 getStreamer().EmitULEB128Value(Value);
3656 /// parseDirectiveSymbolAttribute
3657 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3658 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3659 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3662 SMLoc Loc = getTok().getLoc();
3664 if (parseIdentifier(Name))
3665 return Error(Loc, "expected identifier in directive");
3667 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3669 // Assembler local symbols don't make any sense here. Complain loudly.
3670 if (Sym->isTemporary())
3671 return Error(Loc, "non-local symbol required in directive");
3673 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3674 return Error(Loc, "unable to emit symbol attribute");
3676 if (getLexer().is(AsmToken::EndOfStatement))
3679 if (getLexer().isNot(AsmToken::Comma))
3680 return TokError("unexpected token in directive");
3689 /// parseDirectiveComm
3690 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3691 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3692 checkForValidSection();
3694 SMLoc IDLoc = getLexer().getLoc();
3696 if (parseIdentifier(Name))
3697 return TokError("expected identifier in directive");
3699 // Handle the identifier as the key symbol.
3700 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3702 if (getLexer().isNot(AsmToken::Comma))
3703 return TokError("unexpected token in directive");
3707 SMLoc SizeLoc = getLexer().getLoc();
3708 if (parseAbsoluteExpression(Size))
3711 int64_t Pow2Alignment = 0;
3712 SMLoc Pow2AlignmentLoc;
3713 if (getLexer().is(AsmToken::Comma)) {
3715 Pow2AlignmentLoc = getLexer().getLoc();
3716 if (parseAbsoluteExpression(Pow2Alignment))
3719 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3720 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3721 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3723 // If this target takes alignments in bytes (not log) validate and convert.
3724 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3725 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3726 if (!isPowerOf2_64(Pow2Alignment))
3727 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3728 Pow2Alignment = Log2_64(Pow2Alignment);
3732 if (getLexer().isNot(AsmToken::EndOfStatement))
3733 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3737 // NOTE: a size of zero for a .comm should create a undefined symbol
3738 // but a size of .lcomm creates a bss symbol of size zero.
3740 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3741 "be less than zero");
3743 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3744 // may internally end up wanting an alignment in bytes.
3745 // FIXME: Diagnose overflow.
3746 if (Pow2Alignment < 0)
3747 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3748 "alignment, can't be less than zero");
3750 if (!Sym->isUndefined())
3751 return Error(IDLoc, "invalid symbol redefinition");
3753 // Create the Symbol as a common or local common with Size and Pow2Alignment
3755 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3759 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3763 /// parseDirectiveAbort
3764 /// ::= .abort [... message ...]
3765 bool AsmParser::parseDirectiveAbort() {
3766 // FIXME: Use loc from directive.
3767 SMLoc Loc = getLexer().getLoc();
3769 StringRef Str = parseStringToEndOfStatement();
3770 if (getLexer().isNot(AsmToken::EndOfStatement))
3771 return TokError("unexpected token in '.abort' directive");
3776 Error(Loc, ".abort detected. Assembly stopping.");
3778 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3779 // FIXME: Actually abort assembly here.
3784 /// parseDirectiveInclude
3785 /// ::= .include "filename"
3786 bool AsmParser::parseDirectiveInclude() {
3787 if (getLexer().isNot(AsmToken::String))
3788 return TokError("expected string in '.include' directive");
3790 // Allow the strings to have escaped octal character sequence.
3791 std::string Filename;
3792 if (parseEscapedString(Filename))
3794 SMLoc IncludeLoc = getLexer().getLoc();
3797 if (getLexer().isNot(AsmToken::EndOfStatement))
3798 return TokError("unexpected token in '.include' directive");
3800 // Attempt to switch the lexer to the included file before consuming the end
3801 // of statement to avoid losing it when we switch.
3802 if (enterIncludeFile(Filename)) {
3803 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3810 /// parseDirectiveIncbin
3811 /// ::= .incbin "filename"
3812 bool AsmParser::parseDirectiveIncbin() {
3813 if (getLexer().isNot(AsmToken::String))
3814 return TokError("expected string in '.incbin' directive");
3816 // Allow the strings to have escaped octal character sequence.
3817 std::string Filename;
3818 if (parseEscapedString(Filename))
3820 SMLoc IncbinLoc = getLexer().getLoc();
3823 if (getLexer().isNot(AsmToken::EndOfStatement))
3824 return TokError("unexpected token in '.incbin' directive");
3826 // Attempt to process the included file.
3827 if (processIncbinFile(Filename)) {
3828 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3835 /// parseDirectiveIf
3836 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
3837 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
3838 TheCondStack.push_back(TheCondState);
3839 TheCondState.TheCond = AsmCond::IfCond;
3840 if (TheCondState.Ignore) {
3841 eatToEndOfStatement();
3844 if (parseAbsoluteExpression(ExprValue))
3847 if (getLexer().isNot(AsmToken::EndOfStatement))
3848 return TokError("unexpected token in '.if' directive");
3854 llvm_unreachable("unsupported directive");
3859 ExprValue = ExprValue == 0;
3862 ExprValue = ExprValue >= 0;
3865 ExprValue = ExprValue > 0;
3868 ExprValue = ExprValue <= 0;
3871 ExprValue = ExprValue < 0;
3875 TheCondState.CondMet = ExprValue;
3876 TheCondState.Ignore = !TheCondState.CondMet;
3882 /// parseDirectiveIfb
3884 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3885 TheCondStack.push_back(TheCondState);
3886 TheCondState.TheCond = AsmCond::IfCond;
3888 if (TheCondState.Ignore) {
3889 eatToEndOfStatement();
3891 StringRef Str = parseStringToEndOfStatement();
3893 if (getLexer().isNot(AsmToken::EndOfStatement))
3894 return TokError("unexpected token in '.ifb' directive");
3898 TheCondState.CondMet = ExpectBlank == Str.empty();
3899 TheCondState.Ignore = !TheCondState.CondMet;
3905 /// parseDirectiveIfc
3906 /// ::= .ifc string1, string2
3907 /// ::= .ifnc string1, string2
3908 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3909 TheCondStack.push_back(TheCondState);
3910 TheCondState.TheCond = AsmCond::IfCond;
3912 if (TheCondState.Ignore) {
3913 eatToEndOfStatement();
3915 StringRef Str1 = parseStringToComma();
3917 if (getLexer().isNot(AsmToken::Comma))
3918 return TokError("unexpected token in '.ifc' directive");
3922 StringRef Str2 = parseStringToEndOfStatement();
3924 if (getLexer().isNot(AsmToken::EndOfStatement))
3925 return TokError("unexpected token in '.ifc' directive");
3929 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3930 TheCondState.Ignore = !TheCondState.CondMet;
3936 /// parseDirectiveIfeqs
3937 /// ::= .ifeqs string1, string2
3938 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc) {
3939 if (Lexer.isNot(AsmToken::String)) {
3940 TokError("expected string parameter for '.ifeqs' directive");
3941 eatToEndOfStatement();
3945 StringRef String1 = getTok().getStringContents();
3948 if (Lexer.isNot(AsmToken::Comma)) {
3949 TokError("expected comma after first string for '.ifeqs' directive");
3950 eatToEndOfStatement();
3956 if (Lexer.isNot(AsmToken::String)) {
3957 TokError("expected string parameter for '.ifeqs' directive");
3958 eatToEndOfStatement();
3962 StringRef String2 = getTok().getStringContents();
3965 TheCondStack.push_back(TheCondState);
3966 TheCondState.TheCond = AsmCond::IfCond;
3967 TheCondState.CondMet = String1 == String2;
3968 TheCondState.Ignore = !TheCondState.CondMet;
3973 /// parseDirectiveIfdef
3974 /// ::= .ifdef symbol
3975 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3977 TheCondStack.push_back(TheCondState);
3978 TheCondState.TheCond = AsmCond::IfCond;
3980 if (TheCondState.Ignore) {
3981 eatToEndOfStatement();
3983 if (parseIdentifier(Name))
3984 return TokError("expected identifier after '.ifdef'");
3988 MCSymbol *Sym = getContext().LookupSymbol(Name);
3991 TheCondState.CondMet = (Sym && !Sym->isUndefined());
3993 TheCondState.CondMet = (!Sym || Sym->isUndefined());
3994 TheCondState.Ignore = !TheCondState.CondMet;
4000 /// parseDirectiveElseIf
4001 /// ::= .elseif expression
4002 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4003 if (TheCondState.TheCond != AsmCond::IfCond &&
4004 TheCondState.TheCond != AsmCond::ElseIfCond)
4005 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4007 TheCondState.TheCond = AsmCond::ElseIfCond;
4009 bool LastIgnoreState = false;
4010 if (!TheCondStack.empty())
4011 LastIgnoreState = TheCondStack.back().Ignore;
4012 if (LastIgnoreState || TheCondState.CondMet) {
4013 TheCondState.Ignore = true;
4014 eatToEndOfStatement();
4017 if (parseAbsoluteExpression(ExprValue))
4020 if (getLexer().isNot(AsmToken::EndOfStatement))
4021 return TokError("unexpected token in '.elseif' directive");
4024 TheCondState.CondMet = ExprValue;
4025 TheCondState.Ignore = !TheCondState.CondMet;
4031 /// parseDirectiveElse
4033 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4034 if (getLexer().isNot(AsmToken::EndOfStatement))
4035 return TokError("unexpected token in '.else' directive");
4039 if (TheCondState.TheCond != AsmCond::IfCond &&
4040 TheCondState.TheCond != AsmCond::ElseIfCond)
4041 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4043 TheCondState.TheCond = AsmCond::ElseCond;
4044 bool LastIgnoreState = false;
4045 if (!TheCondStack.empty())
4046 LastIgnoreState = TheCondStack.back().Ignore;
4047 if (LastIgnoreState || TheCondState.CondMet)
4048 TheCondState.Ignore = true;
4050 TheCondState.Ignore = false;
4055 /// parseDirectiveEnd
4057 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4058 if (getLexer().isNot(AsmToken::EndOfStatement))
4059 return TokError("unexpected token in '.end' directive");
4063 while (Lexer.isNot(AsmToken::Eof))
4069 /// parseDirectiveError
4071 /// ::= .error [string]
4072 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4073 if (!TheCondStack.empty()) {
4074 if (TheCondStack.back().Ignore) {
4075 eatToEndOfStatement();
4081 return Error(L, ".err encountered");
4083 StringRef Message = ".error directive invoked in source file";
4084 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4085 if (Lexer.isNot(AsmToken::String)) {
4086 TokError(".error argument must be a string");
4087 eatToEndOfStatement();
4091 Message = getTok().getStringContents();
4099 /// parseDirectiveWarning
4100 /// ::= .warning [string]
4101 bool AsmParser::parseDirectiveWarning(SMLoc L) {
4102 if (!TheCondStack.empty()) {
4103 if (TheCondStack.back().Ignore) {
4104 eatToEndOfStatement();
4109 StringRef Message = ".warning directive invoked in source file";
4110 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4111 if (Lexer.isNot(AsmToken::String)) {
4112 TokError(".warning argument must be a string");
4113 eatToEndOfStatement();
4117 Message = getTok().getStringContents();
4121 Warning(L, Message);
4125 /// parseDirectiveEndIf
4127 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4128 if (getLexer().isNot(AsmToken::EndOfStatement))
4129 return TokError("unexpected token in '.endif' directive");
4133 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4134 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4136 if (!TheCondStack.empty()) {
4137 TheCondState = TheCondStack.back();
4138 TheCondStack.pop_back();
4144 void AsmParser::initializeDirectiveKindMap() {
4145 DirectiveKindMap[".set"] = DK_SET;
4146 DirectiveKindMap[".equ"] = DK_EQU;
4147 DirectiveKindMap[".equiv"] = DK_EQUIV;
4148 DirectiveKindMap[".ascii"] = DK_ASCII;
4149 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4150 DirectiveKindMap[".string"] = DK_STRING;
4151 DirectiveKindMap[".byte"] = DK_BYTE;
4152 DirectiveKindMap[".short"] = DK_SHORT;
4153 DirectiveKindMap[".value"] = DK_VALUE;
4154 DirectiveKindMap[".2byte"] = DK_2BYTE;
4155 DirectiveKindMap[".long"] = DK_LONG;
4156 DirectiveKindMap[".int"] = DK_INT;
4157 DirectiveKindMap[".4byte"] = DK_4BYTE;
4158 DirectiveKindMap[".quad"] = DK_QUAD;
4159 DirectiveKindMap[".8byte"] = DK_8BYTE;
4160 DirectiveKindMap[".octa"] = DK_OCTA;
4161 DirectiveKindMap[".single"] = DK_SINGLE;
4162 DirectiveKindMap[".float"] = DK_FLOAT;
4163 DirectiveKindMap[".double"] = DK_DOUBLE;
4164 DirectiveKindMap[".align"] = DK_ALIGN;
4165 DirectiveKindMap[".align32"] = DK_ALIGN32;
4166 DirectiveKindMap[".balign"] = DK_BALIGN;
4167 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4168 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4169 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4170 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4171 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4172 DirectiveKindMap[".org"] = DK_ORG;
4173 DirectiveKindMap[".fill"] = DK_FILL;
4174 DirectiveKindMap[".zero"] = DK_ZERO;
4175 DirectiveKindMap[".extern"] = DK_EXTERN;
4176 DirectiveKindMap[".globl"] = DK_GLOBL;
4177 DirectiveKindMap[".global"] = DK_GLOBAL;
4178 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4179 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4180 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4181 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4182 DirectiveKindMap[".reference"] = DK_REFERENCE;
4183 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4184 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4185 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4186 DirectiveKindMap[".comm"] = DK_COMM;
4187 DirectiveKindMap[".common"] = DK_COMMON;
4188 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4189 DirectiveKindMap[".abort"] = DK_ABORT;
4190 DirectiveKindMap[".include"] = DK_INCLUDE;
4191 DirectiveKindMap[".incbin"] = DK_INCBIN;
4192 DirectiveKindMap[".code16"] = DK_CODE16;
4193 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4194 DirectiveKindMap[".rept"] = DK_REPT;
4195 DirectiveKindMap[".rep"] = DK_REPT;
4196 DirectiveKindMap[".irp"] = DK_IRP;
4197 DirectiveKindMap[".irpc"] = DK_IRPC;
4198 DirectiveKindMap[".endr"] = DK_ENDR;
4199 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4200 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4201 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4202 DirectiveKindMap[".if"] = DK_IF;
4203 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4204 DirectiveKindMap[".ifge"] = DK_IFGE;
4205 DirectiveKindMap[".ifgt"] = DK_IFGT;
4206 DirectiveKindMap[".ifle"] = DK_IFLE;
4207 DirectiveKindMap[".iflt"] = DK_IFLT;
4208 DirectiveKindMap[".ifne"] = DK_IFNE;
4209 DirectiveKindMap[".ifb"] = DK_IFB;
4210 DirectiveKindMap[".ifnb"] = DK_IFNB;
4211 DirectiveKindMap[".ifc"] = DK_IFC;
4212 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4213 DirectiveKindMap[".ifnc"] = DK_IFNC;
4214 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4215 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4216 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4217 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4218 DirectiveKindMap[".else"] = DK_ELSE;
4219 DirectiveKindMap[".end"] = DK_END;
4220 DirectiveKindMap[".endif"] = DK_ENDIF;
4221 DirectiveKindMap[".skip"] = DK_SKIP;
4222 DirectiveKindMap[".space"] = DK_SPACE;
4223 DirectiveKindMap[".file"] = DK_FILE;
4224 DirectiveKindMap[".line"] = DK_LINE;
4225 DirectiveKindMap[".loc"] = DK_LOC;
4226 DirectiveKindMap[".stabs"] = DK_STABS;
4227 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4228 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4229 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4230 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4231 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4232 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4233 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4234 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4235 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4236 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4237 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4238 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4239 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4240 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4241 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4242 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4243 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4244 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4245 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4246 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4247 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4248 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4249 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4250 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4251 DirectiveKindMap[".macro"] = DK_MACRO;
4252 DirectiveKindMap[".exitm"] = DK_EXITM;
4253 DirectiveKindMap[".endm"] = DK_ENDM;
4254 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4255 DirectiveKindMap[".purgem"] = DK_PURGEM;
4256 DirectiveKindMap[".err"] = DK_ERR;
4257 DirectiveKindMap[".error"] = DK_ERROR;
4258 DirectiveKindMap[".warning"] = DK_WARNING;
4261 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4262 AsmToken EndToken, StartToken = getTok();
4264 unsigned NestLevel = 0;
4266 // Check whether we have reached the end of the file.
4267 if (getLexer().is(AsmToken::Eof)) {
4268 Error(DirectiveLoc, "no matching '.endr' in definition");
4272 if (Lexer.is(AsmToken::Identifier) &&
4273 (getTok().getIdentifier() == ".rept")) {
4277 // Otherwise, check whether we have reached the .endr.
4278 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4279 if (NestLevel == 0) {
4280 EndToken = getTok();
4282 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4283 TokError("unexpected token in '.endr' directive");
4291 // Otherwise, scan till the end of the statement.
4292 eatToEndOfStatement();
4295 const char *BodyStart = StartToken.getLoc().getPointer();
4296 const char *BodyEnd = EndToken.getLoc().getPointer();
4297 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4299 // We Are Anonymous.
4300 MacroLikeBodies.push_back(MCAsmMacro(StringRef(), Body, None));
4301 return &MacroLikeBodies.back();
4304 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4305 raw_svector_ostream &OS) {
4308 std::unique_ptr<MemoryBuffer> Instantiation =
4309 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4311 // Create the macro instantiation object and add to the current macro
4312 // instantiation stack.
4313 MacroInstantiation *MI = new MacroInstantiation(
4314 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
4315 ActiveMacros.push_back(MI);
4317 // Jump to the macro instantiation and prime the lexer.
4318 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
4319 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
4323 /// parseDirectiveRept
4324 /// ::= .rep | .rept count
4325 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4326 const MCExpr *CountExpr;
4327 SMLoc CountLoc = getTok().getLoc();
4328 if (parseExpression(CountExpr))
4332 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4333 eatToEndOfStatement();
4334 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4338 return Error(CountLoc, "Count is negative");
4340 if (Lexer.isNot(AsmToken::EndOfStatement))
4341 return TokError("unexpected token in '" + Dir + "' directive");
4343 // Eat the end of statement.
4346 // Lex the rept definition.
4347 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4351 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4352 // to hold the macro body with substitutions.
4353 SmallString<256> Buf;
4354 raw_svector_ostream OS(Buf);
4356 if (expandMacro(OS, M->Body, None, None, getTok().getLoc()))
4359 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4364 /// parseDirectiveIrp
4365 /// ::= .irp symbol,values
4366 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4367 MCAsmMacroParameter Parameter;
4369 if (parseIdentifier(Parameter.Name))
4370 return TokError("expected identifier in '.irp' directive");
4372 if (Lexer.isNot(AsmToken::Comma))
4373 return TokError("expected comma in '.irp' directive");
4377 MCAsmMacroArguments A;
4378 if (parseMacroArguments(nullptr, A))
4381 // Eat the end of statement.
4384 // Lex the irp definition.
4385 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4389 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4390 // to hold the macro body with substitutions.
4391 SmallString<256> Buf;
4392 raw_svector_ostream OS(Buf);
4394 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4395 if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc()))
4399 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4404 /// parseDirectiveIrpc
4405 /// ::= .irpc symbol,values
4406 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4407 MCAsmMacroParameter Parameter;
4409 if (parseIdentifier(Parameter.Name))
4410 return TokError("expected identifier in '.irpc' directive");
4412 if (Lexer.isNot(AsmToken::Comma))
4413 return TokError("expected comma in '.irpc' directive");
4417 MCAsmMacroArguments A;
4418 if (parseMacroArguments(nullptr, A))
4421 if (A.size() != 1 || A.front().size() != 1)
4422 return TokError("unexpected token in '.irpc' directive");
4424 // Eat the end of statement.
4427 // Lex the irpc definition.
4428 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4432 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4433 // to hold the macro body with substitutions.
4434 SmallString<256> Buf;
4435 raw_svector_ostream OS(Buf);
4437 StringRef Values = A.front().front().getString();
4438 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4439 MCAsmMacroArgument Arg;
4440 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4442 if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc()))
4446 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4451 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4452 if (ActiveMacros.empty())
4453 return TokError("unmatched '.endr' directive");
4455 // The only .repl that should get here are the ones created by
4456 // instantiateMacroLikeBody.
4457 assert(getLexer().is(AsmToken::EndOfStatement));
4463 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4465 const MCExpr *Value;
4466 SMLoc ExprLoc = getLexer().getLoc();
4467 if (parseExpression(Value))
4469 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4471 return Error(ExprLoc, "unexpected expression in _emit");
4472 uint64_t IntValue = MCE->getValue();
4473 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4474 return Error(ExprLoc, "literal value out of range for directive");
4476 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4480 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4481 const MCExpr *Value;
4482 SMLoc ExprLoc = getLexer().getLoc();
4483 if (parseExpression(Value))
4485 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4487 return Error(ExprLoc, "unexpected expression in align");
4488 uint64_t IntValue = MCE->getValue();
4489 if (!isPowerOf2_64(IntValue))
4490 return Error(ExprLoc, "literal value not a power of two greater then zero");
4492 Info.AsmRewrites->push_back(
4493 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4497 // We are comparing pointers, but the pointers are relative to a single string.
4498 // Thus, this should always be deterministic.
4499 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4500 const AsmRewrite *AsmRewriteB) {
4501 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4503 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4506 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4507 // rewrite to the same location. Make sure the SizeDirective rewrite is
4508 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4509 // ensures the sort algorithm is stable.
4510 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4511 AsmRewritePrecedence[AsmRewriteB->Kind])
4514 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4515 AsmRewritePrecedence[AsmRewriteB->Kind])
4517 llvm_unreachable("Unstable rewrite sort.");
4520 bool AsmParser::parseMSInlineAsm(
4521 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4522 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4523 SmallVectorImpl<std::string> &Constraints,
4524 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4525 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4526 SmallVector<void *, 4> InputDecls;
4527 SmallVector<void *, 4> OutputDecls;
4528 SmallVector<bool, 4> InputDeclsAddressOf;
4529 SmallVector<bool, 4> OutputDeclsAddressOf;
4530 SmallVector<std::string, 4> InputConstraints;
4531 SmallVector<std::string, 4> OutputConstraints;
4532 SmallVector<unsigned, 4> ClobberRegs;
4534 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4539 // While we have input, parse each statement.
4540 unsigned InputIdx = 0;
4541 unsigned OutputIdx = 0;
4542 while (getLexer().isNot(AsmToken::Eof)) {
4543 ParseStatementInfo Info(&AsmStrRewrites);
4544 if (parseStatement(Info))
4547 if (Info.ParseError)
4550 if (Info.Opcode == ~0U)
4553 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4555 // Build the list of clobbers, outputs and inputs.
4556 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4557 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4560 if (Operand.isImm())
4563 // Register operand.
4564 if (Operand.isReg() && !Operand.needAddressOf() &&
4565 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
4566 unsigned NumDefs = Desc.getNumDefs();
4568 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4569 ClobberRegs.push_back(Operand.getReg());
4573 // Expr/Input or Output.
4574 StringRef SymName = Operand.getSymName();
4575 if (SymName.empty())
4578 void *OpDecl = Operand.getOpDecl();
4582 bool isOutput = (i == 1) && Desc.mayStore();
4583 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4586 OutputDecls.push_back(OpDecl);
4587 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4588 OutputConstraints.push_back('=' + Operand.getConstraint().str());
4589 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4591 InputDecls.push_back(OpDecl);
4592 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4593 InputConstraints.push_back(Operand.getConstraint().str());
4594 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4598 // Consider implicit defs to be clobbers. Think of cpuid and push.
4599 ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
4600 Desc.getNumImplicitDefs());
4601 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
4604 // Set the number of Outputs and Inputs.
4605 NumOutputs = OutputDecls.size();
4606 NumInputs = InputDecls.size();
4608 // Set the unique clobbers.
4609 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4610 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4612 Clobbers.assign(ClobberRegs.size(), std::string());
4613 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4614 raw_string_ostream OS(Clobbers[I]);
4615 IP->printRegName(OS, ClobberRegs[I]);
4618 // Merge the various outputs and inputs. Output are expected first.
4619 if (NumOutputs || NumInputs) {
4620 unsigned NumExprs = NumOutputs + NumInputs;
4621 OpDecls.resize(NumExprs);
4622 Constraints.resize(NumExprs);
4623 for (unsigned i = 0; i < NumOutputs; ++i) {
4624 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4625 Constraints[i] = OutputConstraints[i];
4627 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4628 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4629 Constraints[j] = InputConstraints[i];
4633 // Build the IR assembly string.
4634 std::string AsmStringIR;
4635 raw_string_ostream OS(AsmStringIR);
4636 StringRef ASMString =
4637 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4638 const char *AsmStart = ASMString.begin();
4639 const char *AsmEnd = ASMString.end();
4640 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4641 for (const AsmRewrite &AR : AsmStrRewrites) {
4642 AsmRewriteKind Kind = AR.Kind;
4643 if (Kind == AOK_Delete)
4646 const char *Loc = AR.Loc.getPointer();
4647 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4649 // Emit everything up to the immediate/expression.
4650 if (unsigned Len = Loc - AsmStart)
4651 OS << StringRef(AsmStart, Len);
4653 // Skip the original expression.
4654 if (Kind == AOK_Skip) {
4655 AsmStart = Loc + AR.Len;
4659 unsigned AdditionalSkip = 0;
4660 // Rewrite expressions in $N notation.
4665 OS << "$$" << AR.Val;
4671 OS << '$' << InputIdx++;
4674 OS << '$' << OutputIdx++;
4676 case AOK_SizeDirective:
4679 case 8: OS << "byte ptr "; break;
4680 case 16: OS << "word ptr "; break;
4681 case 32: OS << "dword ptr "; break;
4682 case 64: OS << "qword ptr "; break;
4683 case 80: OS << "xword ptr "; break;
4684 case 128: OS << "xmmword ptr "; break;
4685 case 256: OS << "ymmword ptr "; break;
4692 unsigned Val = AR.Val;
4693 OS << ".align " << Val;
4695 // Skip the original immediate.
4696 assert(Val < 10 && "Expected alignment less then 2^10.");
4697 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4700 case AOK_DotOperator:
4701 // Insert the dot if the user omitted it.
4703 if (AsmStringIR.back() != '.')
4709 // Skip the original expression.
4710 AsmStart = Loc + AR.Len + AdditionalSkip;
4713 // Emit the remainder of the asm string.
4714 if (AsmStart != AsmEnd)
4715 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4717 AsmString = OS.str();
4721 /// \brief Create an MCAsmParser instance.
4722 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4723 MCStreamer &Out, const MCAsmInfo &MAI) {
4724 return new AsmParser(SM, C, Out, MAI);