1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCParser/AsmCond.h"
27 #include "llvm/MC/MCParser/AsmLexer.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCTargetAsmParser.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/raw_ostream.h"
48 FatalAssemblerWarnings("fatal-assembler-warnings",
49 cl::desc("Consider warnings as error"));
51 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
54 /// \brief Helper types for tracking macro definitions.
55 typedef std::vector<AsmToken> MCAsmMacroArgument;
56 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
58 struct MCAsmMacroParameter {
60 MCAsmMacroArgument Value;
63 MCAsmMacroParameter() : Required(false) { }
66 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
71 MCAsmMacroParameters Parameters;
74 MCAsmMacro(StringRef N, StringRef B, ArrayRef<MCAsmMacroParameter> P) :
75 Name(N), Body(B), Parameters(P) {}
78 /// \brief Helper class for storing information about an active macro
80 struct MacroInstantiation {
81 /// The macro being instantiated.
82 const MCAsmMacro *TheMacro;
84 /// The macro instantiation with substitutions.
85 MemoryBuffer *Instantiation;
87 /// The location of the instantiation.
88 SMLoc InstantiationLoc;
90 /// The buffer where parsing should resume upon instantiation completion.
93 /// The location where parsing should resume upon instantiation completion.
97 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
101 struct ParseStatementInfo {
102 /// \brief The parsed operands from the last parsed statement.
103 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
105 /// \brief The opcode from the last parsed instruction.
108 /// \brief Was there an error parsing the inline assembly?
111 SmallVectorImpl<AsmRewrite> *AsmRewrites;
113 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
114 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
115 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
117 ~ParseStatementInfo() {
118 // Free any parsed operands.
119 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
120 delete ParsedOperands[i];
121 ParsedOperands.clear();
125 /// \brief The concrete assembly parser instance.
126 class AsmParser : public MCAsmParser {
127 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
128 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
133 const MCAsmInfo &MAI;
135 SourceMgr::DiagHandlerTy SavedDiagHandler;
136 void *SavedDiagContext;
137 MCAsmParserExtension *PlatformParser;
139 /// This is the current buffer index we're lexing from as managed by the
140 /// SourceMgr object.
143 AsmCond TheCondState;
144 std::vector<AsmCond> TheCondStack;
146 /// \brief maps directive names to handler methods in parser
147 /// extensions. Extensions register themselves in this map by calling
148 /// addDirectiveHandler.
149 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
151 /// \brief Map of currently defined macros.
152 StringMap<MCAsmMacro*> MacroMap;
154 /// \brief Stack of active macro instantiations.
155 std::vector<MacroInstantiation*> ActiveMacros;
157 /// \brief List of bodies of anonymous macros.
158 std::deque<MCAsmMacro> MacroLikeBodies;
160 /// Boolean tracking whether macro substitution is enabled.
161 unsigned MacrosEnabledFlag : 1;
163 /// Flag tracking whether any errors have been encountered.
164 unsigned HadError : 1;
166 /// The values from the last parsed cpp hash file line comment if any.
167 StringRef CppHashFilename;
168 int64_t CppHashLineNumber;
171 /// When generating dwarf for assembly source files we need to calculate the
172 /// logical line number based on the last parsed cpp hash file line comment
173 /// and current line. Since this is slow and messes up the SourceMgr's
174 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
175 SMLoc LastQueryIDLoc;
177 unsigned LastQueryLine;
179 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
180 unsigned AssemblerDialect;
182 /// \brief is Darwin compatibility enabled?
185 /// \brief Are we parsing ms-style inline assembly?
186 bool ParsingInlineAsm;
189 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
190 const MCAsmInfo &MAI);
191 virtual ~AsmParser();
193 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
195 void addDirectiveHandler(StringRef Directive,
196 ExtensionDirectiveHandler Handler) override {
197 ExtensionDirectiveMap[Directive] = Handler;
201 /// @name MCAsmParser Interface
204 SourceMgr &getSourceManager() override { return SrcMgr; }
205 MCAsmLexer &getLexer() override { return Lexer; }
206 MCContext &getContext() override { return Ctx; }
207 MCStreamer &getStreamer() override { return Out; }
208 unsigned getAssemblerDialect() override {
209 if (AssemblerDialect == ~0U)
210 return MAI.getAssemblerDialect();
212 return AssemblerDialect;
214 void setAssemblerDialect(unsigned i) override {
215 AssemblerDialect = i;
218 void Note(SMLoc L, const Twine &Msg,
219 ArrayRef<SMRange> Ranges = None) override;
220 bool Warning(SMLoc L, const Twine &Msg,
221 ArrayRef<SMRange> Ranges = None) override;
222 bool Error(SMLoc L, const Twine &Msg,
223 ArrayRef<SMRange> Ranges = None) override;
225 const AsmToken &Lex() override;
227 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
228 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
230 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
231 unsigned &NumOutputs, unsigned &NumInputs,
232 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
233 SmallVectorImpl<std::string> &Constraints,
234 SmallVectorImpl<std::string> &Clobbers,
235 const MCInstrInfo *MII, const MCInstPrinter *IP,
236 MCAsmParserSemaCallback &SI) override;
238 bool parseExpression(const MCExpr *&Res);
239 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
240 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
241 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
242 bool parseAbsoluteExpression(int64_t &Res) override;
244 /// \brief Parse an identifier or string (as a quoted identifier)
245 /// and set \p Res to the identifier contents.
246 bool parseIdentifier(StringRef &Res) override;
247 void eatToEndOfStatement() override;
249 void checkForValidSection() override;
254 bool parseStatement(ParseStatementInfo &Info);
255 void eatToEndOfLine();
256 bool parseCppHashLineFilenameComment(const SMLoc &L);
258 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
259 ArrayRef<MCAsmMacroParameter> Parameters);
260 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
261 ArrayRef<MCAsmMacroParameter> Parameters,
262 ArrayRef<MCAsmMacroArgument> A,
265 /// \brief Are macros enabled in the parser?
266 bool areMacrosEnabled() {return MacrosEnabledFlag;}
268 /// \brief Control a flag in the parser that enables or disables macros.
269 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
271 /// \brief Lookup a previously defined macro.
272 /// \param Name Macro name.
273 /// \returns Pointer to macro. NULL if no such macro was defined.
274 const MCAsmMacro* lookupMacro(StringRef Name);
276 /// \brief Define a new macro with the given name and information.
277 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
279 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
280 void undefineMacro(StringRef Name);
282 /// \brief Are we inside a macro instantiation?
283 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
285 /// \brief Handle entry to macro instantiation.
287 /// \param M The macro.
288 /// \param NameLoc Instantiation location.
289 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
291 /// \brief Handle exit from macro instantiation.
292 void handleMacroExit();
294 /// \brief Extract AsmTokens for a macro argument.
295 bool parseMacroArgument(MCAsmMacroArgument &MA);
297 /// \brief Parse all macro arguments for a given macro.
298 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
300 void printMacroInstantiations();
301 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
302 ArrayRef<SMRange> Ranges = None) const {
303 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
305 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
307 /// \brief Enter the specified file. This returns true on failure.
308 bool enterIncludeFile(const std::string &Filename);
310 /// \brief Process the specified file for the .incbin directive.
311 /// This returns true on failure.
312 bool processIncbinFile(const std::string &Filename);
314 /// \brief Reset the current lexer position to that given by \p Loc. The
315 /// current token is not set; clients should ensure Lex() is called
318 /// \param InBuffer If not -1, should be the known buffer id that contains the
320 void jumpToLoc(SMLoc Loc, int InBuffer=-1);
322 /// \brief Parse up to the end of statement and a return the contents from the
323 /// current token until the end of the statement; the current token on exit
324 /// will be either the EndOfStatement or EOF.
325 StringRef parseStringToEndOfStatement() override;
327 /// \brief Parse until the end of a statement or a comma is encountered,
328 /// return the contents from the current token up to the end or comma.
329 StringRef parseStringToComma();
331 bool parseAssignment(StringRef Name, bool allow_redef,
332 bool NoDeadStrip = false);
334 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
335 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
336 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
338 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
340 // Generic (target and platform independent) directive parsing.
342 DK_NO_DIRECTIVE, // Placeholder
343 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
344 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
345 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
346 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
347 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
348 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
349 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
350 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
351 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
352 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
353 DK_IF, DK_IFNE, DK_IFB, DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFDEF,
354 DK_IFNDEF, DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
355 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
356 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
357 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
358 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
359 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
360 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
361 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
362 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
363 DK_SLEB128, DK_ULEB128,
368 /// \brief Maps directive name --> DirectiveKind enum, for
369 /// directives parsed by this class.
370 StringMap<DirectiveKind> DirectiveKindMap;
372 // ".ascii", ".asciz", ".string"
373 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
374 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
375 bool parseDirectiveOctaValue(); // ".octa"
376 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
377 bool parseDirectiveFill(); // ".fill"
378 bool parseDirectiveZero(); // ".zero"
379 // ".set", ".equ", ".equiv"
380 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
381 bool parseDirectiveOrg(); // ".org"
382 // ".align{,32}", ".p2align{,w,l}"
383 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
385 // ".file", ".line", ".loc", ".stabs"
386 bool parseDirectiveFile(SMLoc DirectiveLoc);
387 bool parseDirectiveLine();
388 bool parseDirectiveLoc();
389 bool parseDirectiveStabs();
392 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
393 bool parseDirectiveCFIWindowSave();
394 bool parseDirectiveCFISections();
395 bool parseDirectiveCFIStartProc();
396 bool parseDirectiveCFIEndProc();
397 bool parseDirectiveCFIDefCfaOffset();
398 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
399 bool parseDirectiveCFIAdjustCfaOffset();
400 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
401 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
403 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
404 bool parseDirectiveCFIRememberState();
405 bool parseDirectiveCFIRestoreState();
406 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
407 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
408 bool parseDirectiveCFIEscape();
409 bool parseDirectiveCFISignalFrame();
410 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
413 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
414 bool parseDirectiveEndMacro(StringRef Directive);
415 bool parseDirectiveMacro(SMLoc DirectiveLoc);
416 bool parseDirectiveMacrosOnOff(StringRef Directive);
418 // ".bundle_align_mode"
419 bool parseDirectiveBundleAlignMode();
421 bool parseDirectiveBundleLock();
423 bool parseDirectiveBundleUnlock();
426 bool parseDirectiveSpace(StringRef IDVal);
428 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
429 bool parseDirectiveLEB128(bool Signed);
431 /// \brief Parse a directive like ".globl" which
432 /// accepts a single symbol (which should be a label or an external).
433 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
435 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
437 bool parseDirectiveAbort(); // ".abort"
438 bool parseDirectiveInclude(); // ".include"
439 bool parseDirectiveIncbin(); // ".incbin"
442 bool parseDirectiveIf(SMLoc DirectiveLoc);
443 // ".ifb" or ".ifnb", depending on ExpectBlank.
444 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
445 // ".ifc" or ".ifnc", depending on ExpectEqual.
446 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
448 bool parseDirectiveIfeqs(SMLoc DirectiveLoc);
449 // ".ifdef" or ".ifndef", depending on expect_defined
450 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
451 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
452 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
453 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
454 bool parseEscapedString(std::string &Data) override;
456 const MCExpr *applyModifierToExpr(const MCExpr *E,
457 MCSymbolRefExpr::VariantKind Variant);
459 // Macro-like directives
460 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
461 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
462 raw_svector_ostream &OS);
463 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
464 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
465 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
466 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
468 // "_emit" or "__emit"
469 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
473 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
476 bool parseDirectiveEnd(SMLoc DirectiveLoc);
478 // ".err" or ".error"
479 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
481 void initializeDirectiveKindMap();
487 extern MCAsmParserExtension *createDarwinAsmParser();
488 extern MCAsmParserExtension *createELFAsmParser();
489 extern MCAsmParserExtension *createCOFFAsmParser();
493 enum { DEFAULT_ADDRSPACE = 0 };
495 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
496 const MCAsmInfo &_MAI)
497 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
498 PlatformParser(0), CurBuffer(0), MacrosEnabledFlag(true),
499 CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false),
500 ParsingInlineAsm(false) {
501 // Save the old handler.
502 SavedDiagHandler = SrcMgr.getDiagHandler();
503 SavedDiagContext = SrcMgr.getDiagContext();
504 // Set our own handler which calls the saved handler.
505 SrcMgr.setDiagHandler(DiagHandler, this);
506 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
508 // Initialize the platform / file format parser.
509 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
510 case MCObjectFileInfo::IsCOFF:
511 PlatformParser = createCOFFAsmParser();
512 PlatformParser->Initialize(*this);
514 case MCObjectFileInfo::IsMachO:
515 PlatformParser = createDarwinAsmParser();
516 PlatformParser->Initialize(*this);
519 case MCObjectFileInfo::IsELF:
520 PlatformParser = createELFAsmParser();
521 PlatformParser->Initialize(*this);
525 initializeDirectiveKindMap();
528 AsmParser::~AsmParser() {
529 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
531 // Destroy any macros.
532 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
535 delete it->getValue();
537 delete PlatformParser;
540 void AsmParser::printMacroInstantiations() {
541 // Print the active macro instantiation stack.
542 for (std::vector<MacroInstantiation *>::const_reverse_iterator
543 it = ActiveMacros.rbegin(),
544 ie = ActiveMacros.rend();
546 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
547 "while in macro instantiation");
550 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
551 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
552 printMacroInstantiations();
555 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
556 if (FatalAssemblerWarnings)
557 return Error(L, Msg, Ranges);
558 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
559 printMacroInstantiations();
563 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
565 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
566 printMacroInstantiations();
570 bool AsmParser::enterIncludeFile(const std::string &Filename) {
571 std::string IncludedFile;
572 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
578 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
583 /// Process the specified .incbin file by searching for it in the include paths
584 /// then just emitting the byte contents of the file to the streamer. This
585 /// returns true on failure.
586 bool AsmParser::processIncbinFile(const std::string &Filename) {
587 std::string IncludedFile;
588 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
592 // Pick up the bytes from the file and emit them.
593 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
597 void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
598 if (InBuffer != -1) {
599 CurBuffer = InBuffer;
601 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
603 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
606 const AsmToken &AsmParser::Lex() {
607 const AsmToken *tok = &Lexer.Lex();
609 if (tok->is(AsmToken::Eof)) {
610 // If this is the end of an included file, pop the parent file off the
612 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
613 if (ParentIncludeLoc != SMLoc()) {
614 jumpToLoc(ParentIncludeLoc);
619 if (tok->is(AsmToken::Error))
620 Error(Lexer.getErrLoc(), Lexer.getErr());
625 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
626 // Create the initial section, if requested.
627 if (!NoInitialTextSection)
634 AsmCond StartingCondState = TheCondState;
636 // If we are generating dwarf for assembly source files save the initial text
637 // section and generate a .file directive.
638 if (getContext().getGenDwarfForAssembly()) {
639 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
640 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
641 getStreamer().EmitLabel(SectionStartSym);
642 getContext().setGenDwarfSectionStartSym(SectionStartSym);
643 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
645 getContext().getMainFileName());
648 // While we have input, parse each statement.
649 while (Lexer.isNot(AsmToken::Eof)) {
650 ParseStatementInfo Info;
651 if (!parseStatement(Info))
654 // We had an error, validate that one was emitted and recover by skipping to
656 assert(HadError && "Parse statement returned an error, but none emitted!");
657 eatToEndOfStatement();
660 if (TheCondState.TheCond != StartingCondState.TheCond ||
661 TheCondState.Ignore != StartingCondState.Ignore)
662 return TokError("unmatched .ifs or .elses");
664 // Check to see there are no empty DwarfFile slots.
665 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
666 getContext().getMCDwarfFiles();
667 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
668 if (!MCDwarfFiles[i])
669 TokError("unassigned file number: " + Twine(i) + " for .file directives");
672 // Check to see that all assembler local symbols were actually defined.
673 // Targets that don't do subsections via symbols may not want this, though,
674 // so conservatively exclude them. Only do this if we're finalizing, though,
675 // as otherwise we won't necessarilly have seen everything yet.
676 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
677 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
678 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
681 MCSymbol *Sym = i->getValue();
682 // Variable symbols may not be marked as defined, so check those
683 // explicitly. If we know it's a variable, we have a definition for
684 // the purposes of this check.
685 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
686 // FIXME: We would really like to refer back to where the symbol was
687 // first referenced for a source location. We need to add something
688 // to track that. Currently, we just point to the end of the file.
690 getLexer().getLoc(), SourceMgr::DK_Error,
691 "assembler local symbol '" + Sym->getName() + "' not defined");
695 // Finalize the output stream if there are no errors and if the client wants
697 if (!HadError && !NoFinalize)
703 void AsmParser::checkForValidSection() {
704 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
705 TokError("expected section directive before assembly directive");
710 /// \brief Throw away the rest of the line for testing purposes.
711 void AsmParser::eatToEndOfStatement() {
712 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
716 if (Lexer.is(AsmToken::EndOfStatement))
720 StringRef AsmParser::parseStringToEndOfStatement() {
721 const char *Start = getTok().getLoc().getPointer();
723 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
726 const char *End = getTok().getLoc().getPointer();
727 return StringRef(Start, End - Start);
730 StringRef AsmParser::parseStringToComma() {
731 const char *Start = getTok().getLoc().getPointer();
733 while (Lexer.isNot(AsmToken::EndOfStatement) &&
734 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
737 const char *End = getTok().getLoc().getPointer();
738 return StringRef(Start, End - Start);
741 /// \brief Parse a paren expression and return it.
742 /// NOTE: This assumes the leading '(' has already been consumed.
744 /// parenexpr ::= expr)
746 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
747 if (parseExpression(Res))
749 if (Lexer.isNot(AsmToken::RParen))
750 return TokError("expected ')' in parentheses expression");
751 EndLoc = Lexer.getTok().getEndLoc();
756 /// \brief Parse a bracket expression and return it.
757 /// NOTE: This assumes the leading '[' has already been consumed.
759 /// bracketexpr ::= expr]
761 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
762 if (parseExpression(Res))
764 if (Lexer.isNot(AsmToken::RBrac))
765 return TokError("expected ']' in brackets expression");
766 EndLoc = Lexer.getTok().getEndLoc();
771 /// \brief Parse a primary expression and return it.
772 /// primaryexpr ::= (parenexpr
773 /// primaryexpr ::= symbol
774 /// primaryexpr ::= number
775 /// primaryexpr ::= '.'
776 /// primaryexpr ::= ~,+,- primaryexpr
777 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
778 SMLoc FirstTokenLoc = getLexer().getLoc();
779 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
780 switch (FirstTokenKind) {
782 return TokError("unknown token in expression");
783 // If we have an error assume that we've already handled it.
784 case AsmToken::Error:
786 case AsmToken::Exclaim:
787 Lex(); // Eat the operator.
788 if (parsePrimaryExpr(Res, EndLoc))
790 Res = MCUnaryExpr::CreateLNot(Res, getContext());
792 case AsmToken::Dollar:
794 case AsmToken::String:
795 case AsmToken::Identifier: {
796 StringRef Identifier;
797 if (parseIdentifier(Identifier)) {
798 if (FirstTokenKind == AsmToken::Dollar) {
799 if (Lexer.getMAI().getDollarIsPC()) {
800 // This is a '$' reference, which references the current PC. Emit a
801 // temporary label to the streamer and refer to it.
802 MCSymbol *Sym = Ctx.CreateTempSymbol();
804 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
806 EndLoc = FirstTokenLoc;
809 return Error(FirstTokenLoc, "invalid token in expression");
812 // Parse symbol variant
813 std::pair<StringRef, StringRef> Split;
814 if (!MAI.useParensForSymbolVariant()) {
815 Split = Identifier.split('@');
816 } else if (Lexer.is(AsmToken::LParen)) {
817 Lexer.Lex(); // eat (
819 parseIdentifier(VName);
820 if (Lexer.isNot(AsmToken::RParen)) {
821 return Error(Lexer.getTok().getLoc(),
822 "unexpected token in variant, expected ')'");
824 Lexer.Lex(); // eat )
825 Split = std::make_pair(Identifier, VName);
828 EndLoc = SMLoc::getFromPointer(Identifier.end());
830 // This is a symbol reference.
831 StringRef SymbolName = Identifier;
832 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
834 // Lookup the symbol variant if used.
835 if (Split.second.size()) {
836 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
837 if (Variant != MCSymbolRefExpr::VK_Invalid) {
838 SymbolName = Split.first;
839 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
840 Variant = MCSymbolRefExpr::VK_None;
842 return Error(SMLoc::getFromPointer(Split.second.begin()),
843 "invalid variant '" + Split.second + "'");
847 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
849 // If this is an absolute variable reference, substitute it now to preserve
850 // semantics in the face of reassignment.
851 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
853 return Error(EndLoc, "unexpected modifier on variable reference");
855 Res = Sym->getVariableValue();
859 // Otherwise create a symbol ref.
860 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
863 case AsmToken::BigNum:
864 return TokError("literal value out of range for directive");
865 case AsmToken::Integer: {
866 SMLoc Loc = getTok().getLoc();
867 int64_t IntVal = getTok().getIntVal();
868 Res = MCConstantExpr::Create(IntVal, getContext());
869 EndLoc = Lexer.getTok().getEndLoc();
871 // Look for 'b' or 'f' following an Integer as a directional label
872 if (Lexer.getKind() == AsmToken::Identifier) {
873 StringRef IDVal = getTok().getString();
874 // Lookup the symbol variant if used.
875 std::pair<StringRef, StringRef> Split = IDVal.split('@');
876 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
877 if (Split.first.size() != IDVal.size()) {
878 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
879 if (Variant == MCSymbolRefExpr::VK_Invalid) {
880 Variant = MCSymbolRefExpr::VK_None;
881 return TokError("invalid variant '" + Split.second + "'");
885 if (IDVal == "f" || IDVal == "b") {
887 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "b");
888 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
889 if (IDVal == "b" && Sym->isUndefined())
890 return Error(Loc, "invalid reference to undefined symbol");
891 EndLoc = Lexer.getTok().getEndLoc();
892 Lex(); // Eat identifier.
897 case AsmToken::Real: {
898 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
899 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
900 Res = MCConstantExpr::Create(IntVal, getContext());
901 EndLoc = Lexer.getTok().getEndLoc();
905 case AsmToken::Dot: {
906 // This is a '.' reference, which references the current PC. Emit a
907 // temporary label to the streamer and refer to it.
908 MCSymbol *Sym = Ctx.CreateTempSymbol();
910 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
911 EndLoc = Lexer.getTok().getEndLoc();
912 Lex(); // Eat identifier.
915 case AsmToken::LParen:
916 Lex(); // Eat the '('.
917 return parseParenExpr(Res, EndLoc);
918 case AsmToken::LBrac:
919 if (!PlatformParser->HasBracketExpressions())
920 return TokError("brackets expression not supported on this target");
921 Lex(); // Eat the '['.
922 return parseBracketExpr(Res, EndLoc);
923 case AsmToken::Minus:
924 Lex(); // Eat the operator.
925 if (parsePrimaryExpr(Res, EndLoc))
927 Res = MCUnaryExpr::CreateMinus(Res, getContext());
930 Lex(); // Eat the operator.
931 if (parsePrimaryExpr(Res, EndLoc))
933 Res = MCUnaryExpr::CreatePlus(Res, getContext());
935 case AsmToken::Tilde:
936 Lex(); // Eat the operator.
937 if (parsePrimaryExpr(Res, EndLoc))
939 Res = MCUnaryExpr::CreateNot(Res, getContext());
944 bool AsmParser::parseExpression(const MCExpr *&Res) {
946 return parseExpression(Res, EndLoc);
950 AsmParser::applyModifierToExpr(const MCExpr *E,
951 MCSymbolRefExpr::VariantKind Variant) {
952 // Ask the target implementation about this expression first.
953 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
956 // Recurse over the given expression, rebuilding it to apply the given variant
957 // if there is exactly one symbol.
958 switch (E->getKind()) {
960 case MCExpr::Constant:
963 case MCExpr::SymbolRef: {
964 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
966 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
967 TokError("invalid variant on expression '" + getTok().getIdentifier() +
968 "' (already modified)");
972 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
975 case MCExpr::Unary: {
976 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
977 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
980 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
983 case MCExpr::Binary: {
984 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
985 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
986 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
996 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
1000 llvm_unreachable("Invalid expression kind!");
1003 /// \brief Parse an expression and return it.
1005 /// expr ::= expr &&,|| expr -> lowest.
1006 /// expr ::= expr |,^,&,! expr
1007 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1008 /// expr ::= expr <<,>> expr
1009 /// expr ::= expr +,- expr
1010 /// expr ::= expr *,/,% expr -> highest.
1011 /// expr ::= primaryexpr
1013 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1014 // Parse the expression.
1016 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1019 // As a special case, we support 'a op b @ modifier' by rewriting the
1020 // expression to include the modifier. This is inefficient, but in general we
1021 // expect users to use 'a@modifier op b'.
1022 if (Lexer.getKind() == AsmToken::At) {
1025 if (Lexer.isNot(AsmToken::Identifier))
1026 return TokError("unexpected symbol modifier following '@'");
1028 MCSymbolRefExpr::VariantKind Variant =
1029 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1030 if (Variant == MCSymbolRefExpr::VK_Invalid)
1031 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1033 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1035 return TokError("invalid modifier '" + getTok().getIdentifier() +
1036 "' (no symbols present)");
1043 // Try to constant fold it up front, if possible.
1045 if (Res->EvaluateAsAbsolute(Value))
1046 Res = MCConstantExpr::Create(Value, getContext());
1051 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1053 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1056 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1059 SMLoc StartLoc = Lexer.getLoc();
1060 if (parseExpression(Expr))
1063 if (!Expr->EvaluateAsAbsolute(Res))
1064 return Error(StartLoc, "expected absolute expression");
1069 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1070 MCBinaryExpr::Opcode &Kind) {
1073 return 0; // not a binop.
1075 // Lowest Precedence: &&, ||
1076 case AsmToken::AmpAmp:
1077 Kind = MCBinaryExpr::LAnd;
1079 case AsmToken::PipePipe:
1080 Kind = MCBinaryExpr::LOr;
1083 // Low Precedence: |, &, ^
1085 // FIXME: gas seems to support '!' as an infix operator?
1086 case AsmToken::Pipe:
1087 Kind = MCBinaryExpr::Or;
1089 case AsmToken::Caret:
1090 Kind = MCBinaryExpr::Xor;
1093 Kind = MCBinaryExpr::And;
1096 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1097 case AsmToken::EqualEqual:
1098 Kind = MCBinaryExpr::EQ;
1100 case AsmToken::ExclaimEqual:
1101 case AsmToken::LessGreater:
1102 Kind = MCBinaryExpr::NE;
1104 case AsmToken::Less:
1105 Kind = MCBinaryExpr::LT;
1107 case AsmToken::LessEqual:
1108 Kind = MCBinaryExpr::LTE;
1110 case AsmToken::Greater:
1111 Kind = MCBinaryExpr::GT;
1113 case AsmToken::GreaterEqual:
1114 Kind = MCBinaryExpr::GTE;
1117 // Intermediate Precedence: <<, >>
1118 case AsmToken::LessLess:
1119 Kind = MCBinaryExpr::Shl;
1121 case AsmToken::GreaterGreater:
1122 Kind = MCBinaryExpr::Shr;
1125 // High Intermediate Precedence: +, -
1126 case AsmToken::Plus:
1127 Kind = MCBinaryExpr::Add;
1129 case AsmToken::Minus:
1130 Kind = MCBinaryExpr::Sub;
1133 // Highest Precedence: *, /, %
1134 case AsmToken::Star:
1135 Kind = MCBinaryExpr::Mul;
1137 case AsmToken::Slash:
1138 Kind = MCBinaryExpr::Div;
1140 case AsmToken::Percent:
1141 Kind = MCBinaryExpr::Mod;
1146 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1147 /// Res contains the LHS of the expression on input.
1148 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1151 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1152 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1154 // If the next token is lower precedence than we are allowed to eat, return
1155 // successfully with what we ate already.
1156 if (TokPrec < Precedence)
1161 // Eat the next primary expression.
1163 if (parsePrimaryExpr(RHS, EndLoc))
1166 // If BinOp binds less tightly with RHS than the operator after RHS, let
1167 // the pending operator take RHS as its LHS.
1168 MCBinaryExpr::Opcode Dummy;
1169 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1170 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1173 // Merge LHS and RHS according to operator.
1174 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1179 /// ::= EndOfStatement
1180 /// ::= Label* Directive ...Operands... EndOfStatement
1181 /// ::= Label* Identifier OperandList* EndOfStatement
1182 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1183 if (Lexer.is(AsmToken::EndOfStatement)) {
1189 // Statements always start with an identifier or are a full line comment.
1190 AsmToken ID = getTok();
1191 SMLoc IDLoc = ID.getLoc();
1193 int64_t LocalLabelVal = -1;
1194 // A full line comment is a '#' as the first token.
1195 if (Lexer.is(AsmToken::Hash))
1196 return parseCppHashLineFilenameComment(IDLoc);
1198 // Allow an integer followed by a ':' as a directional local label.
1199 if (Lexer.is(AsmToken::Integer)) {
1200 LocalLabelVal = getTok().getIntVal();
1201 if (LocalLabelVal < 0) {
1202 if (!TheCondState.Ignore)
1203 return TokError("unexpected token at start of statement");
1206 IDVal = getTok().getString();
1207 Lex(); // Consume the integer token to be used as an identifier token.
1208 if (Lexer.getKind() != AsmToken::Colon) {
1209 if (!TheCondState.Ignore)
1210 return TokError("unexpected token at start of statement");
1213 } else if (Lexer.is(AsmToken::Dot)) {
1214 // Treat '.' as a valid identifier in this context.
1217 } else if (parseIdentifier(IDVal)) {
1218 if (!TheCondState.Ignore)
1219 return TokError("unexpected token at start of statement");
1223 // Handle conditional assembly here before checking for skipping. We
1224 // have to do this so that .endif isn't skipped in a ".if 0" block for
1226 StringMap<DirectiveKind>::const_iterator DirKindIt =
1227 DirectiveKindMap.find(IDVal);
1228 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1230 : DirKindIt->getValue();
1236 return parseDirectiveIf(IDLoc);
1238 return parseDirectiveIfb(IDLoc, true);
1240 return parseDirectiveIfb(IDLoc, false);
1242 return parseDirectiveIfc(IDLoc, true);
1244 return parseDirectiveIfeqs(IDLoc);
1246 return parseDirectiveIfc(IDLoc, false);
1248 return parseDirectiveIfdef(IDLoc, true);
1251 return parseDirectiveIfdef(IDLoc, false);
1253 return parseDirectiveElseIf(IDLoc);
1255 return parseDirectiveElse(IDLoc);
1257 return parseDirectiveEndIf(IDLoc);
1260 // Ignore the statement if in the middle of inactive conditional
1262 if (TheCondState.Ignore) {
1263 eatToEndOfStatement();
1267 // FIXME: Recurse on local labels?
1269 // See what kind of statement we have.
1270 switch (Lexer.getKind()) {
1271 case AsmToken::Colon: {
1272 checkForValidSection();
1274 // identifier ':' -> Label.
1277 // Diagnose attempt to use '.' as a label.
1279 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1281 // Diagnose attempt to use a variable as a label.
1283 // FIXME: Diagnostics. Note the location of the definition as a label.
1284 // FIXME: This doesn't diagnose assignment to a symbol which has been
1285 // implicitly marked as external.
1287 if (LocalLabelVal == -1)
1288 Sym = getContext().GetOrCreateSymbol(IDVal);
1290 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1291 if (!Sym->isUndefined() || Sym->isVariable())
1292 return Error(IDLoc, "invalid symbol redefinition");
1295 if (!ParsingInlineAsm)
1298 // If we are generating dwarf for assembly source files then gather the
1299 // info to make a dwarf label entry for this label if needed.
1300 if (getContext().getGenDwarfForAssembly())
1301 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1304 getTargetParser().onLabelParsed(Sym);
1306 // Consume any end of statement token, if present, to avoid spurious
1307 // AddBlankLine calls().
1308 if (Lexer.is(AsmToken::EndOfStatement)) {
1310 if (Lexer.is(AsmToken::Eof))
1317 case AsmToken::Equal:
1318 // identifier '=' ... -> assignment statement
1321 return parseAssignment(IDVal, true);
1323 default: // Normal instruction or directive.
1327 // If macros are enabled, check to see if this is a macro instantiation.
1328 if (areMacrosEnabled())
1329 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1330 return handleMacroEntry(M, IDLoc);
1333 // Otherwise, we have a normal instruction or directive.
1335 // Directives start with "."
1336 if (IDVal[0] == '.' && IDVal != ".") {
1337 // There are several entities interested in parsing directives:
1339 // 1. The target-specific assembly parser. Some directives are target
1340 // specific or may potentially behave differently on certain targets.
1341 // 2. Asm parser extensions. For example, platform-specific parsers
1342 // (like the ELF parser) register themselves as extensions.
1343 // 3. The generic directive parser implemented by this class. These are
1344 // all the directives that behave in a target and platform independent
1345 // manner, or at least have a default behavior that's shared between
1346 // all targets and platforms.
1348 // First query the target-specific parser. It will return 'true' if it
1349 // isn't interested in this directive.
1350 if (!getTargetParser().ParseDirective(ID))
1353 // Next, check the extension directive map to see if any extension has
1354 // registered itself to parse this directive.
1355 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1356 ExtensionDirectiveMap.lookup(IDVal);
1358 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1360 // Finally, if no one else is interested in this directive, it must be
1361 // generic and familiar to this class.
1367 return parseDirectiveSet(IDVal, true);
1369 return parseDirectiveSet(IDVal, false);
1371 return parseDirectiveAscii(IDVal, false);
1374 return parseDirectiveAscii(IDVal, true);
1376 return parseDirectiveValue(1);
1380 return parseDirectiveValue(2);
1384 return parseDirectiveValue(4);
1387 return parseDirectiveValue(8);
1389 return parseDirectiveOctaValue();
1392 return parseDirectiveRealValue(APFloat::IEEEsingle);
1394 return parseDirectiveRealValue(APFloat::IEEEdouble);
1396 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1397 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1400 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1401 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1404 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1406 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1408 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1410 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1412 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1414 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1416 return parseDirectiveOrg();
1418 return parseDirectiveFill();
1420 return parseDirectiveZero();
1422 eatToEndOfStatement(); // .extern is the default, ignore it.
1426 return parseDirectiveSymbolAttribute(MCSA_Global);
1427 case DK_LAZY_REFERENCE:
1428 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1429 case DK_NO_DEAD_STRIP:
1430 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1431 case DK_SYMBOL_RESOLVER:
1432 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1433 case DK_PRIVATE_EXTERN:
1434 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1436 return parseDirectiveSymbolAttribute(MCSA_Reference);
1437 case DK_WEAK_DEFINITION:
1438 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1439 case DK_WEAK_REFERENCE:
1440 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1441 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1442 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1445 return parseDirectiveComm(/*IsLocal=*/false);
1447 return parseDirectiveComm(/*IsLocal=*/true);
1449 return parseDirectiveAbort();
1451 return parseDirectiveInclude();
1453 return parseDirectiveIncbin();
1456 return TokError(Twine(IDVal) + " not supported yet");
1458 return parseDirectiveRept(IDLoc, IDVal);
1460 return parseDirectiveIrp(IDLoc);
1462 return parseDirectiveIrpc(IDLoc);
1464 return parseDirectiveEndr(IDLoc);
1465 case DK_BUNDLE_ALIGN_MODE:
1466 return parseDirectiveBundleAlignMode();
1467 case DK_BUNDLE_LOCK:
1468 return parseDirectiveBundleLock();
1469 case DK_BUNDLE_UNLOCK:
1470 return parseDirectiveBundleUnlock();
1472 return parseDirectiveLEB128(true);
1474 return parseDirectiveLEB128(false);
1477 return parseDirectiveSpace(IDVal);
1479 return parseDirectiveFile(IDLoc);
1481 return parseDirectiveLine();
1483 return parseDirectiveLoc();
1485 return parseDirectiveStabs();
1486 case DK_CFI_SECTIONS:
1487 return parseDirectiveCFISections();
1488 case DK_CFI_STARTPROC:
1489 return parseDirectiveCFIStartProc();
1490 case DK_CFI_ENDPROC:
1491 return parseDirectiveCFIEndProc();
1492 case DK_CFI_DEF_CFA:
1493 return parseDirectiveCFIDefCfa(IDLoc);
1494 case DK_CFI_DEF_CFA_OFFSET:
1495 return parseDirectiveCFIDefCfaOffset();
1496 case DK_CFI_ADJUST_CFA_OFFSET:
1497 return parseDirectiveCFIAdjustCfaOffset();
1498 case DK_CFI_DEF_CFA_REGISTER:
1499 return parseDirectiveCFIDefCfaRegister(IDLoc);
1501 return parseDirectiveCFIOffset(IDLoc);
1502 case DK_CFI_REL_OFFSET:
1503 return parseDirectiveCFIRelOffset(IDLoc);
1504 case DK_CFI_PERSONALITY:
1505 return parseDirectiveCFIPersonalityOrLsda(true);
1507 return parseDirectiveCFIPersonalityOrLsda(false);
1508 case DK_CFI_REMEMBER_STATE:
1509 return parseDirectiveCFIRememberState();
1510 case DK_CFI_RESTORE_STATE:
1511 return parseDirectiveCFIRestoreState();
1512 case DK_CFI_SAME_VALUE:
1513 return parseDirectiveCFISameValue(IDLoc);
1514 case DK_CFI_RESTORE:
1515 return parseDirectiveCFIRestore(IDLoc);
1517 return parseDirectiveCFIEscape();
1518 case DK_CFI_SIGNAL_FRAME:
1519 return parseDirectiveCFISignalFrame();
1520 case DK_CFI_UNDEFINED:
1521 return parseDirectiveCFIUndefined(IDLoc);
1522 case DK_CFI_REGISTER:
1523 return parseDirectiveCFIRegister(IDLoc);
1524 case DK_CFI_WINDOW_SAVE:
1525 return parseDirectiveCFIWindowSave();
1528 return parseDirectiveMacrosOnOff(IDVal);
1530 return parseDirectiveMacro(IDLoc);
1533 return parseDirectiveEndMacro(IDVal);
1535 return parseDirectivePurgeMacro(IDLoc);
1537 return parseDirectiveEnd(IDLoc);
1539 return parseDirectiveError(IDLoc, false);
1541 return parseDirectiveError(IDLoc, true);
1544 return Error(IDLoc, "unknown directive");
1547 // __asm _emit or __asm __emit
1548 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1549 IDVal == "_EMIT" || IDVal == "__EMIT"))
1550 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1553 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1554 return parseDirectiveMSAlign(IDLoc, Info);
1556 checkForValidSection();
1558 // Canonicalize the opcode to lower case.
1559 std::string OpcodeStr = IDVal.lower();
1560 ParseInstructionInfo IInfo(Info.AsmRewrites);
1561 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1562 Info.ParsedOperands);
1563 Info.ParseError = HadError;
1565 // Dump the parsed representation, if requested.
1566 if (getShowParsedOperands()) {
1567 SmallString<256> Str;
1568 raw_svector_ostream OS(Str);
1569 OS << "parsed instruction: [";
1570 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1573 Info.ParsedOperands[i]->print(OS);
1577 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1580 // If we are generating dwarf for assembly source files and the current
1581 // section is the initial text section then generate a .loc directive for
1583 if (!HadError && getContext().getGenDwarfForAssembly() &&
1584 getContext().getGenDwarfSection() ==
1585 getStreamer().getCurrentSection().first) {
1587 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1589 // If we previously parsed a cpp hash file line comment then make sure the
1590 // current Dwarf File is for the CppHashFilename if not then emit the
1591 // Dwarf File table for it and adjust the line number for the .loc.
1592 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
1593 getContext().getMCDwarfFiles();
1594 if (CppHashFilename.size() != 0) {
1595 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->Name !=
1597 getStreamer().EmitDwarfFileDirective(
1598 getContext().nextGenDwarfFileNumber(), StringRef(),
1601 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1602 // cache with the different Loc from the call above we save the last
1603 // info we queried here with SrcMgr.FindLineNumber().
1604 unsigned CppHashLocLineNo;
1605 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1606 CppHashLocLineNo = LastQueryLine;
1608 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1609 LastQueryLine = CppHashLocLineNo;
1610 LastQueryIDLoc = CppHashLoc;
1611 LastQueryBuffer = CppHashBuf;
1613 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1616 getStreamer().EmitDwarfLocDirective(
1617 getContext().getGenDwarfFileNumber(), Line, 0,
1618 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1622 // If parsing succeeded, match the instruction.
1625 HadError = getTargetParser().MatchAndEmitInstruction(
1626 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
1630 // Don't skip the rest of the line, the instruction parser is responsible for
1635 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1636 /// since they may not be able to be tokenized to get to the end of line token.
1637 void AsmParser::eatToEndOfLine() {
1638 if (!Lexer.is(AsmToken::EndOfStatement))
1639 Lexer.LexUntilEndOfLine();
1644 /// parseCppHashLineFilenameComment as this:
1645 /// ::= # number "filename"
1646 /// or just as a full line comment if it doesn't have a number and a string.
1647 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1648 Lex(); // Eat the hash token.
1650 if (getLexer().isNot(AsmToken::Integer)) {
1651 // Consume the line since in cases it is not a well-formed line directive,
1652 // as if were simply a full line comment.
1657 int64_t LineNumber = getTok().getIntVal();
1660 if (getLexer().isNot(AsmToken::String)) {
1665 StringRef Filename = getTok().getString();
1666 // Get rid of the enclosing quotes.
1667 Filename = Filename.substr(1, Filename.size() - 2);
1669 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1671 CppHashFilename = Filename;
1672 CppHashLineNumber = LineNumber;
1673 CppHashBuf = CurBuffer;
1675 // Ignore any trailing characters, they're just comment.
1680 /// \brief will use the last parsed cpp hash line filename comment
1681 /// for the Filename and LineNo if any in the diagnostic.
1682 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1683 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1684 raw_ostream &OS = errs();
1686 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1687 const SMLoc &DiagLoc = Diag.getLoc();
1688 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1689 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1691 // Like SourceMgr::printMessage() we need to print the include stack if any
1692 // before printing the message.
1693 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1694 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1695 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1696 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1699 // If we have not parsed a cpp hash line filename comment or the source
1700 // manager changed or buffer changed (like in a nested include) then just
1701 // print the normal diagnostic using its Filename and LineNo.
1702 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1703 DiagBuf != CppHashBuf) {
1704 if (Parser->SavedDiagHandler)
1705 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1711 // Use the CppHashFilename and calculate a line number based on the
1712 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1714 const std::string &Filename = Parser->CppHashFilename;
1716 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1717 int CppHashLocLineNo =
1718 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1720 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1722 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1723 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1724 Diag.getLineContents(), Diag.getRanges());
1726 if (Parser->SavedDiagHandler)
1727 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1729 NewDiag.print(0, OS);
1732 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1733 // difference being that that function accepts '@' as part of identifiers and
1734 // we can't do that. AsmLexer.cpp should probably be changed to handle
1735 // '@' as a special case when needed.
1736 static bool isIdentifierChar(char c) {
1737 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1741 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1742 ArrayRef<MCAsmMacroParameter> Parameters,
1743 ArrayRef<MCAsmMacroArgument> A, const SMLoc &L) {
1744 unsigned NParameters = Parameters.size();
1745 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1746 return Error(L, "Wrong number of arguments");
1748 // A macro without parameters is handled differently on Darwin:
1749 // gas accepts no arguments and does no substitutions
1750 while (!Body.empty()) {
1751 // Scan for the next substitution.
1752 std::size_t End = Body.size(), Pos = 0;
1753 for (; Pos != End; ++Pos) {
1754 // Check for a substitution or escape.
1755 if (IsDarwin && !NParameters) {
1756 // This macro has no parameters, look for $0, $1, etc.
1757 if (Body[Pos] != '$' || Pos + 1 == End)
1760 char Next = Body[Pos + 1];
1761 if (Next == '$' || Next == 'n' ||
1762 isdigit(static_cast<unsigned char>(Next)))
1765 // This macro has parameters, look for \foo, \bar, etc.
1766 if (Body[Pos] == '\\' && Pos + 1 != End)
1772 OS << Body.slice(0, Pos);
1774 // Check if we reached the end.
1778 if (IsDarwin && !NParameters) {
1779 switch (Body[Pos + 1]) {
1785 // $n => number of arguments
1790 // $[0-9] => argument
1792 // Missing arguments are ignored.
1793 unsigned Index = Body[Pos + 1] - '0';
1794 if (Index >= A.size())
1797 // Otherwise substitute with the token values, with spaces eliminated.
1798 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1799 ie = A[Index].end();
1801 OS << it->getString();
1807 unsigned I = Pos + 1;
1808 while (isIdentifierChar(Body[I]) && I + 1 != End)
1811 const char *Begin = Body.data() + Pos + 1;
1812 StringRef Argument(Begin, I - (Pos + 1));
1814 for (; Index < NParameters; ++Index)
1815 if (Parameters[Index].Name == Argument)
1818 if (Index == NParameters) {
1819 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1822 OS << '\\' << Argument;
1826 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1827 ie = A[Index].end();
1829 if (it->getKind() == AsmToken::String)
1830 OS << it->getStringContents();
1832 OS << it->getString();
1834 Pos += 1 + Argument.size();
1837 // Update the scan point.
1838 Body = Body.substr(Pos);
1844 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1845 SMLoc EL, MemoryBuffer *I)
1846 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1849 static bool isOperator(AsmToken::TokenKind kind) {
1853 case AsmToken::Plus:
1854 case AsmToken::Minus:
1855 case AsmToken::Tilde:
1856 case AsmToken::Slash:
1857 case AsmToken::Star:
1859 case AsmToken::Equal:
1860 case AsmToken::EqualEqual:
1861 case AsmToken::Pipe:
1862 case AsmToken::PipePipe:
1863 case AsmToken::Caret:
1865 case AsmToken::AmpAmp:
1866 case AsmToken::Exclaim:
1867 case AsmToken::ExclaimEqual:
1868 case AsmToken::Percent:
1869 case AsmToken::Less:
1870 case AsmToken::LessEqual:
1871 case AsmToken::LessLess:
1872 case AsmToken::LessGreater:
1873 case AsmToken::Greater:
1874 case AsmToken::GreaterEqual:
1875 case AsmToken::GreaterGreater:
1881 class AsmLexerSkipSpaceRAII {
1883 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1884 Lexer.setSkipSpace(SkipSpace);
1887 ~AsmLexerSkipSpaceRAII() {
1888 Lexer.setSkipSpace(true);
1896 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA) {
1897 unsigned ParenLevel = 0;
1898 unsigned AddTokens = 0;
1900 // Darwin doesn't use spaces to delmit arguments.
1901 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1904 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1905 return TokError("unexpected token in macro instantiation");
1907 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1910 if (Lexer.is(AsmToken::Space)) {
1911 Lex(); // Eat spaces
1913 // Spaces can delimit parameters, but could also be part an expression.
1914 // If the token after a space is an operator, add the token and the next
1915 // one into this argument
1917 if (isOperator(Lexer.getKind())) {
1918 // Check to see whether the token is used as an operator,
1919 // or part of an identifier
1920 const char *NextChar = getTok().getEndLoc().getPointer();
1921 if (*NextChar == ' ')
1925 if (!AddTokens && ParenLevel == 0) {
1931 // handleMacroEntry relies on not advancing the lexer here
1932 // to be able to fill in the remaining default parameter values
1933 if (Lexer.is(AsmToken::EndOfStatement))
1936 // Adjust the current parentheses level.
1937 if (Lexer.is(AsmToken::LParen))
1939 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1942 // Append the token to the current argument list.
1943 MA.push_back(getTok());
1949 if (ParenLevel != 0)
1950 return TokError("unbalanced parentheses in macro argument");
1954 // Parse the macro instantiation arguments.
1955 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1956 MCAsmMacroArguments &A) {
1957 const unsigned NParameters = M ? M->Parameters.size() : 0;
1958 bool NamedParametersFound = false;
1959 SmallVector<SMLoc, 4> FALocs;
1961 A.resize(NParameters);
1962 FALocs.resize(NParameters);
1964 // Parse two kinds of macro invocations:
1965 // - macros defined without any parameters accept an arbitrary number of them
1966 // - macros defined with parameters accept at most that many of them
1967 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1969 SMLoc IDLoc = Lexer.getLoc();
1970 MCAsmMacroParameter FA;
1972 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
1973 if (parseIdentifier(FA.Name)) {
1974 Error(IDLoc, "invalid argument identifier for formal argument");
1975 eatToEndOfStatement();
1979 if (!Lexer.is(AsmToken::Equal)) {
1980 TokError("expected '=' after formal parameter identifier");
1981 eatToEndOfStatement();
1986 NamedParametersFound = true;
1989 if (NamedParametersFound && FA.Name.empty()) {
1990 Error(IDLoc, "cannot mix positional and keyword arguments");
1991 eatToEndOfStatement();
1995 if (parseMacroArgument(FA.Value))
1998 unsigned PI = Parameter;
1999 if (!FA.Name.empty()) {
2001 for (FAI = 0; FAI < NParameters; ++FAI)
2002 if (M->Parameters[FAI].Name == FA.Name)
2005 if (FAI >= NParameters) {
2007 "parameter named '" + FA.Name + "' does not exist for macro '" +
2008 (M ? M->Name : "<unnamed>") + "'");
2014 if (!FA.Value.empty()) {
2019 if (FALocs.size() <= PI)
2020 FALocs.resize(PI + 1);
2022 FALocs[PI] = Lexer.getLoc();
2025 // At the end of the statement, fill in remaining arguments that have
2026 // default values. If there aren't any, then the next argument is
2027 // required but missing
2028 if (Lexer.is(AsmToken::EndOfStatement)) {
2029 bool Failure = false;
2030 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2031 if (A[FAI].empty()) {
2032 if (M->Parameters[FAI].Required) {
2033 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2034 "missing value for required parameter "
2035 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2039 if (!M->Parameters[FAI].Value.empty())
2040 A[FAI] = M->Parameters[FAI].Value;
2046 if (Lexer.is(AsmToken::Comma))
2050 return TokError("too many positional arguments");
2053 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2054 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2055 return (I == MacroMap.end()) ? NULL : I->getValue();
2058 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
2059 MacroMap[Name] = new MCAsmMacro(Macro);
2062 void AsmParser::undefineMacro(StringRef Name) {
2063 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2064 if (I != MacroMap.end()) {
2065 delete I->getValue();
2070 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2071 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2072 // this, although we should protect against infinite loops.
2073 if (ActiveMacros.size() == 20)
2074 return TokError("macros cannot be nested more than 20 levels deep");
2076 MCAsmMacroArguments A;
2077 if (parseMacroArguments(M, A))
2080 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2081 // to hold the macro body with substitutions.
2082 SmallString<256> Buf;
2083 StringRef Body = M->Body;
2084 raw_svector_ostream OS(Buf);
2086 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2089 // We include the .endmacro in the buffer as our cue to exit the macro
2091 OS << ".endmacro\n";
2093 MemoryBuffer *Instantiation =
2094 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2096 // Create the macro instantiation object and add to the current macro
2097 // instantiation stack.
2098 MacroInstantiation *MI = new MacroInstantiation(
2099 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
2100 ActiveMacros.push_back(MI);
2102 // Jump to the macro instantiation and prime the lexer.
2103 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2104 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2110 void AsmParser::handleMacroExit() {
2111 // Jump to the EndOfStatement we should return to, and consume it.
2112 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2115 // Pop the instantiation entry.
2116 delete ActiveMacros.back();
2117 ActiveMacros.pop_back();
2120 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2121 switch (Value->getKind()) {
2122 case MCExpr::Binary: {
2123 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2124 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2126 case MCExpr::Target:
2127 case MCExpr::Constant:
2129 case MCExpr::SymbolRef: {
2131 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2133 return isUsedIn(Sym, S.getVariableValue());
2137 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2140 llvm_unreachable("Unknown expr kind!");
2143 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2145 // FIXME: Use better location, we should use proper tokens.
2146 SMLoc EqualLoc = Lexer.getLoc();
2148 const MCExpr *Value;
2149 if (parseExpression(Value))
2152 // Note: we don't count b as used in "a = b". This is to allow
2156 if (Lexer.isNot(AsmToken::EndOfStatement))
2157 return TokError("unexpected token in assignment");
2159 // Eat the end of statement marker.
2162 // Validate that the LHS is allowed to be a variable (either it has not been
2163 // used as a symbol, or it is an absolute symbol).
2164 MCSymbol *Sym = getContext().LookupSymbol(Name);
2166 // Diagnose assignment to a label.
2168 // FIXME: Diagnostics. Note the location of the definition as a label.
2169 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2170 if (isUsedIn(Sym, Value))
2171 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2172 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2173 ; // Allow redefinitions of undefined symbols only used in directives.
2174 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2175 ; // Allow redefinitions of variables that haven't yet been used.
2176 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2177 return Error(EqualLoc, "redefinition of '" + Name + "'");
2178 else if (!Sym->isVariable())
2179 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2180 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2181 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2184 // Don't count these checks as uses.
2185 Sym->setUsed(false);
2186 } else if (Name == ".") {
2187 if (Out.EmitValueToOffset(Value, 0)) {
2188 Error(EqualLoc, "expected absolute expression");
2189 eatToEndOfStatement();
2193 Sym = getContext().GetOrCreateSymbol(Name);
2195 // Do the assignment.
2196 Out.EmitAssignment(Sym, Value);
2198 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2203 /// parseIdentifier:
2206 bool AsmParser::parseIdentifier(StringRef &Res) {
2207 // The assembler has relaxed rules for accepting identifiers, in particular we
2208 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2209 // separate tokens. At this level, we have already lexed so we cannot (currently)
2210 // handle this as a context dependent token, instead we detect adjacent tokens
2211 // and return the combined identifier.
2212 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2213 SMLoc PrefixLoc = getLexer().getLoc();
2215 // Consume the prefix character, and check for a following identifier.
2217 if (Lexer.isNot(AsmToken::Identifier))
2220 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2221 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2224 // Construct the joined identifier and consume the token.
2226 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2231 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2234 Res = getTok().getIdentifier();
2236 Lex(); // Consume the identifier token.
2241 /// parseDirectiveSet:
2242 /// ::= .equ identifier ',' expression
2243 /// ::= .equiv identifier ',' expression
2244 /// ::= .set identifier ',' expression
2245 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2248 if (parseIdentifier(Name))
2249 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2251 if (getLexer().isNot(AsmToken::Comma))
2252 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2255 return parseAssignment(Name, allow_redef, true);
2258 bool AsmParser::parseEscapedString(std::string &Data) {
2259 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2262 StringRef Str = getTok().getStringContents();
2263 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2264 if (Str[i] != '\\') {
2269 // Recognize escaped characters. Note that this escape semantics currently
2270 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2273 return TokError("unexpected backslash at end of string");
2275 // Recognize octal sequences.
2276 if ((unsigned)(Str[i] - '0') <= 7) {
2277 // Consume up to three octal characters.
2278 unsigned Value = Str[i] - '0';
2280 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2282 Value = Value * 8 + (Str[i] - '0');
2284 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2286 Value = Value * 8 + (Str[i] - '0');
2291 return TokError("invalid octal escape sequence (out of range)");
2293 Data += (unsigned char)Value;
2297 // Otherwise recognize individual escapes.
2300 // Just reject invalid escape sequences for now.
2301 return TokError("invalid escape sequence (unrecognized character)");
2303 case 'b': Data += '\b'; break;
2304 case 'f': Data += '\f'; break;
2305 case 'n': Data += '\n'; break;
2306 case 'r': Data += '\r'; break;
2307 case 't': Data += '\t'; break;
2308 case '"': Data += '"'; break;
2309 case '\\': Data += '\\'; break;
2316 /// parseDirectiveAscii:
2317 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2318 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2319 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2320 checkForValidSection();
2323 if (getLexer().isNot(AsmToken::String))
2324 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2327 if (parseEscapedString(Data))
2330 getStreamer().EmitBytes(Data);
2332 getStreamer().EmitBytes(StringRef("\0", 1));
2336 if (getLexer().is(AsmToken::EndOfStatement))
2339 if (getLexer().isNot(AsmToken::Comma))
2340 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2349 /// parseDirectiveValue
2350 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2351 bool AsmParser::parseDirectiveValue(unsigned Size) {
2352 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2353 checkForValidSection();
2356 const MCExpr *Value;
2357 SMLoc ExprLoc = getLexer().getLoc();
2358 if (parseExpression(Value))
2361 // Special case constant expressions to match code generator.
2362 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2363 assert(Size <= 8 && "Invalid size");
2364 uint64_t IntValue = MCE->getValue();
2365 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2366 return Error(ExprLoc, "literal value out of range for directive");
2367 getStreamer().EmitIntValue(IntValue, Size);
2369 getStreamer().EmitValue(Value, Size);
2371 if (getLexer().is(AsmToken::EndOfStatement))
2374 // FIXME: Improve diagnostic.
2375 if (getLexer().isNot(AsmToken::Comma))
2376 return TokError("unexpected token in directive");
2385 /// ParseDirectiveOctaValue
2386 /// ::= .octa [ hexconstant (, hexconstant)* ]
2387 bool AsmParser::parseDirectiveOctaValue() {
2388 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2389 checkForValidSection();
2392 if (Lexer.getKind() == AsmToken::Error)
2394 if (Lexer.getKind() != AsmToken::Integer &&
2395 Lexer.getKind() != AsmToken::BigNum)
2396 return TokError("unknown token in expression");
2398 SMLoc ExprLoc = getLexer().getLoc();
2399 APInt IntValue = getTok().getAPIntVal();
2403 if (IntValue.isIntN(64)) {
2405 lo = IntValue.getZExtValue();
2406 } else if (IntValue.isIntN(128)) {
2407 // It might actually have more than 128 bits, but the top ones are zero.
2408 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2409 lo = IntValue.getLoBits(64).getZExtValue();
2411 return Error(ExprLoc, "literal value out of range for directive");
2413 if (MAI.isLittleEndian()) {
2414 getStreamer().EmitIntValue(lo, 8);
2415 getStreamer().EmitIntValue(hi, 8);
2417 getStreamer().EmitIntValue(hi, 8);
2418 getStreamer().EmitIntValue(lo, 8);
2421 if (getLexer().is(AsmToken::EndOfStatement))
2424 // FIXME: Improve diagnostic.
2425 if (getLexer().isNot(AsmToken::Comma))
2426 return TokError("unexpected token in directive");
2435 /// parseDirectiveRealValue
2436 /// ::= (.single | .double) [ expression (, expression)* ]
2437 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2438 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2439 checkForValidSection();
2442 // We don't truly support arithmetic on floating point expressions, so we
2443 // have to manually parse unary prefixes.
2445 if (getLexer().is(AsmToken::Minus)) {
2448 } else if (getLexer().is(AsmToken::Plus))
2451 if (getLexer().isNot(AsmToken::Integer) &&
2452 getLexer().isNot(AsmToken::Real) &&
2453 getLexer().isNot(AsmToken::Identifier))
2454 return TokError("unexpected token in directive");
2456 // Convert to an APFloat.
2457 APFloat Value(Semantics);
2458 StringRef IDVal = getTok().getString();
2459 if (getLexer().is(AsmToken::Identifier)) {
2460 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2461 Value = APFloat::getInf(Semantics);
2462 else if (!IDVal.compare_lower("nan"))
2463 Value = APFloat::getNaN(Semantics, false, ~0);
2465 return TokError("invalid floating point literal");
2466 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2467 APFloat::opInvalidOp)
2468 return TokError("invalid floating point literal");
2472 // Consume the numeric token.
2475 // Emit the value as an integer.
2476 APInt AsInt = Value.bitcastToAPInt();
2477 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2478 AsInt.getBitWidth() / 8);
2480 if (getLexer().is(AsmToken::EndOfStatement))
2483 if (getLexer().isNot(AsmToken::Comma))
2484 return TokError("unexpected token in directive");
2493 /// parseDirectiveZero
2494 /// ::= .zero expression
2495 bool AsmParser::parseDirectiveZero() {
2496 checkForValidSection();
2499 if (parseAbsoluteExpression(NumBytes))
2503 if (getLexer().is(AsmToken::Comma)) {
2505 if (parseAbsoluteExpression(Val))
2509 if (getLexer().isNot(AsmToken::EndOfStatement))
2510 return TokError("unexpected token in '.zero' directive");
2514 getStreamer().EmitFill(NumBytes, Val);
2519 /// parseDirectiveFill
2520 /// ::= .fill expression [ , expression [ , expression ] ]
2521 bool AsmParser::parseDirectiveFill() {
2522 checkForValidSection();
2524 SMLoc RepeatLoc = getLexer().getLoc();
2526 if (parseAbsoluteExpression(NumValues))
2529 if (NumValues < 0) {
2531 "'.fill' directive with negative repeat count has no effect");
2535 int64_t FillSize = 1;
2536 int64_t FillExpr = 0;
2538 SMLoc SizeLoc, ExprLoc;
2539 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2540 if (getLexer().isNot(AsmToken::Comma))
2541 return TokError("unexpected token in '.fill' directive");
2544 SizeLoc = getLexer().getLoc();
2545 if (parseAbsoluteExpression(FillSize))
2548 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2549 if (getLexer().isNot(AsmToken::Comma))
2550 return TokError("unexpected token in '.fill' directive");
2553 ExprLoc = getLexer().getLoc();
2554 if (parseAbsoluteExpression(FillExpr))
2557 if (getLexer().isNot(AsmToken::EndOfStatement))
2558 return TokError("unexpected token in '.fill' directive");
2565 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2569 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2573 if (!isUInt<32>(FillExpr) && FillSize > 4)
2574 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2576 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2577 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2579 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2580 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2581 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2587 /// parseDirectiveOrg
2588 /// ::= .org expression [ , expression ]
2589 bool AsmParser::parseDirectiveOrg() {
2590 checkForValidSection();
2592 const MCExpr *Offset;
2593 SMLoc Loc = getTok().getLoc();
2594 if (parseExpression(Offset))
2597 // Parse optional fill expression.
2598 int64_t FillExpr = 0;
2599 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2600 if (getLexer().isNot(AsmToken::Comma))
2601 return TokError("unexpected token in '.org' directive");
2604 if (parseAbsoluteExpression(FillExpr))
2607 if (getLexer().isNot(AsmToken::EndOfStatement))
2608 return TokError("unexpected token in '.org' directive");
2613 // Only limited forms of relocatable expressions are accepted here, it
2614 // has to be relative to the current section. The streamer will return
2615 // 'true' if the expression wasn't evaluatable.
2616 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2617 return Error(Loc, "expected assembly-time absolute expression");
2622 /// parseDirectiveAlign
2623 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2624 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2625 checkForValidSection();
2627 SMLoc AlignmentLoc = getLexer().getLoc();
2629 if (parseAbsoluteExpression(Alignment))
2633 bool HasFillExpr = false;
2634 int64_t FillExpr = 0;
2635 int64_t MaxBytesToFill = 0;
2636 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2637 if (getLexer().isNot(AsmToken::Comma))
2638 return TokError("unexpected token in directive");
2641 // The fill expression can be omitted while specifying a maximum number of
2642 // alignment bytes, e.g:
2644 if (getLexer().isNot(AsmToken::Comma)) {
2646 if (parseAbsoluteExpression(FillExpr))
2650 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2651 if (getLexer().isNot(AsmToken::Comma))
2652 return TokError("unexpected token in directive");
2655 MaxBytesLoc = getLexer().getLoc();
2656 if (parseAbsoluteExpression(MaxBytesToFill))
2659 if (getLexer().isNot(AsmToken::EndOfStatement))
2660 return TokError("unexpected token in directive");
2669 // Compute alignment in bytes.
2671 // FIXME: Diagnose overflow.
2672 if (Alignment >= 32) {
2673 Error(AlignmentLoc, "invalid alignment value");
2677 Alignment = 1ULL << Alignment;
2679 // Reject alignments that aren't a power of two, for gas compatibility.
2680 if (!isPowerOf2_64(Alignment))
2681 Error(AlignmentLoc, "alignment must be a power of 2");
2684 // Diagnose non-sensical max bytes to align.
2685 if (MaxBytesLoc.isValid()) {
2686 if (MaxBytesToFill < 1) {
2687 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2688 "many bytes, ignoring maximum bytes expression");
2692 if (MaxBytesToFill >= Alignment) {
2693 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2699 // Check whether we should use optimal code alignment for this .align
2701 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2702 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2703 ValueSize == 1 && UseCodeAlign) {
2704 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2706 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2707 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2714 /// parseDirectiveFile
2715 /// ::= .file [number] filename
2716 /// ::= .file number directory filename
2717 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2718 // FIXME: I'm not sure what this is.
2719 int64_t FileNumber = -1;
2720 SMLoc FileNumberLoc = getLexer().getLoc();
2721 if (getLexer().is(AsmToken::Integer)) {
2722 FileNumber = getTok().getIntVal();
2726 return TokError("file number less than one");
2729 if (getLexer().isNot(AsmToken::String))
2730 return TokError("unexpected token in '.file' directive");
2732 // Usually the directory and filename together, otherwise just the directory.
2733 // Allow the strings to have escaped octal character sequence.
2734 std::string Path = getTok().getString();
2735 if (parseEscapedString(Path))
2739 StringRef Directory;
2741 std::string FilenameData;
2742 if (getLexer().is(AsmToken::String)) {
2743 if (FileNumber == -1)
2744 return TokError("explicit path specified, but no file number");
2745 if (parseEscapedString(FilenameData))
2747 Filename = FilenameData;
2754 if (getLexer().isNot(AsmToken::EndOfStatement))
2755 return TokError("unexpected token in '.file' directive");
2757 if (FileNumber == -1)
2758 getStreamer().EmitFileDirective(Filename);
2760 if (getContext().getGenDwarfForAssembly() == true)
2762 "input can't have .file dwarf directives when -g is "
2763 "used to generate dwarf debug info for assembly code");
2765 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2766 Error(FileNumberLoc, "file number already allocated");
2772 /// parseDirectiveLine
2773 /// ::= .line [number]
2774 bool AsmParser::parseDirectiveLine() {
2775 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2776 if (getLexer().isNot(AsmToken::Integer))
2777 return TokError("unexpected token in '.line' directive");
2779 int64_t LineNumber = getTok().getIntVal();
2783 // FIXME: Do something with the .line.
2786 if (getLexer().isNot(AsmToken::EndOfStatement))
2787 return TokError("unexpected token in '.line' directive");
2792 /// parseDirectiveLoc
2793 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2794 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2795 /// The first number is a file number, must have been previously assigned with
2796 /// a .file directive, the second number is the line number and optionally the
2797 /// third number is a column position (zero if not specified). The remaining
2798 /// optional items are .loc sub-directives.
2799 bool AsmParser::parseDirectiveLoc() {
2800 if (getLexer().isNot(AsmToken::Integer))
2801 return TokError("unexpected token in '.loc' directive");
2802 int64_t FileNumber = getTok().getIntVal();
2804 return TokError("file number less than one in '.loc' directive");
2805 if (!getContext().isValidDwarfFileNumber(FileNumber))
2806 return TokError("unassigned file number in '.loc' directive");
2809 int64_t LineNumber = 0;
2810 if (getLexer().is(AsmToken::Integer)) {
2811 LineNumber = getTok().getIntVal();
2813 return TokError("line number less than zero in '.loc' directive");
2817 int64_t ColumnPos = 0;
2818 if (getLexer().is(AsmToken::Integer)) {
2819 ColumnPos = getTok().getIntVal();
2821 return TokError("column position less than zero in '.loc' directive");
2825 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2827 int64_t Discriminator = 0;
2828 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2830 if (getLexer().is(AsmToken::EndOfStatement))
2834 SMLoc Loc = getTok().getLoc();
2835 if (parseIdentifier(Name))
2836 return TokError("unexpected token in '.loc' directive");
2838 if (Name == "basic_block")
2839 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2840 else if (Name == "prologue_end")
2841 Flags |= DWARF2_FLAG_PROLOGUE_END;
2842 else if (Name == "epilogue_begin")
2843 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2844 else if (Name == "is_stmt") {
2845 Loc = getTok().getLoc();
2846 const MCExpr *Value;
2847 if (parseExpression(Value))
2849 // The expression must be the constant 0 or 1.
2850 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2851 int Value = MCE->getValue();
2853 Flags &= ~DWARF2_FLAG_IS_STMT;
2854 else if (Value == 1)
2855 Flags |= DWARF2_FLAG_IS_STMT;
2857 return Error(Loc, "is_stmt value not 0 or 1");
2859 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2861 } else if (Name == "isa") {
2862 Loc = getTok().getLoc();
2863 const MCExpr *Value;
2864 if (parseExpression(Value))
2866 // The expression must be a constant greater or equal to 0.
2867 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2868 int Value = MCE->getValue();
2870 return Error(Loc, "isa number less than zero");
2873 return Error(Loc, "isa number not a constant value");
2875 } else if (Name == "discriminator") {
2876 if (parseAbsoluteExpression(Discriminator))
2879 return Error(Loc, "unknown sub-directive in '.loc' directive");
2882 if (getLexer().is(AsmToken::EndOfStatement))
2887 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2888 Isa, Discriminator, StringRef());
2893 /// parseDirectiveStabs
2894 /// ::= .stabs string, number, number, number
2895 bool AsmParser::parseDirectiveStabs() {
2896 return TokError("unsupported directive '.stabs'");
2899 /// parseDirectiveCFISections
2900 /// ::= .cfi_sections section [, section]
2901 bool AsmParser::parseDirectiveCFISections() {
2906 if (parseIdentifier(Name))
2907 return TokError("Expected an identifier");
2909 if (Name == ".eh_frame")
2911 else if (Name == ".debug_frame")
2914 if (getLexer().is(AsmToken::Comma)) {
2917 if (parseIdentifier(Name))
2918 return TokError("Expected an identifier");
2920 if (Name == ".eh_frame")
2922 else if (Name == ".debug_frame")
2926 getStreamer().EmitCFISections(EH, Debug);
2930 /// parseDirectiveCFIStartProc
2931 /// ::= .cfi_startproc [simple]
2932 bool AsmParser::parseDirectiveCFIStartProc() {
2934 if (getLexer().isNot(AsmToken::EndOfStatement))
2935 if (parseIdentifier(Simple) || Simple != "simple")
2936 return TokError("unexpected token in .cfi_startproc directive");
2938 getStreamer().EmitCFIStartProc(!Simple.empty());
2942 /// parseDirectiveCFIEndProc
2943 /// ::= .cfi_endproc
2944 bool AsmParser::parseDirectiveCFIEndProc() {
2945 getStreamer().EmitCFIEndProc();
2949 /// \brief parse register name or number.
2950 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2951 SMLoc DirectiveLoc) {
2954 if (getLexer().isNot(AsmToken::Integer)) {
2955 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2957 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2959 return parseAbsoluteExpression(Register);
2964 /// parseDirectiveCFIDefCfa
2965 /// ::= .cfi_def_cfa register, offset
2966 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2967 int64_t Register = 0;
2968 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2971 if (getLexer().isNot(AsmToken::Comma))
2972 return TokError("unexpected token in directive");
2976 if (parseAbsoluteExpression(Offset))
2979 getStreamer().EmitCFIDefCfa(Register, Offset);
2983 /// parseDirectiveCFIDefCfaOffset
2984 /// ::= .cfi_def_cfa_offset offset
2985 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2987 if (parseAbsoluteExpression(Offset))
2990 getStreamer().EmitCFIDefCfaOffset(Offset);
2994 /// parseDirectiveCFIRegister
2995 /// ::= .cfi_register register, register
2996 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2997 int64_t Register1 = 0;
2998 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3001 if (getLexer().isNot(AsmToken::Comma))
3002 return TokError("unexpected token in directive");
3005 int64_t Register2 = 0;
3006 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3009 getStreamer().EmitCFIRegister(Register1, Register2);
3013 /// parseDirectiveCFIWindowSave
3014 /// ::= .cfi_window_save
3015 bool AsmParser::parseDirectiveCFIWindowSave() {
3016 getStreamer().EmitCFIWindowSave();
3020 /// parseDirectiveCFIAdjustCfaOffset
3021 /// ::= .cfi_adjust_cfa_offset adjustment
3022 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3023 int64_t Adjustment = 0;
3024 if (parseAbsoluteExpression(Adjustment))
3027 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3031 /// parseDirectiveCFIDefCfaRegister
3032 /// ::= .cfi_def_cfa_register register
3033 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3034 int64_t Register = 0;
3035 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3038 getStreamer().EmitCFIDefCfaRegister(Register);
3042 /// parseDirectiveCFIOffset
3043 /// ::= .cfi_offset register, offset
3044 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3045 int64_t Register = 0;
3048 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3051 if (getLexer().isNot(AsmToken::Comma))
3052 return TokError("unexpected token in directive");
3055 if (parseAbsoluteExpression(Offset))
3058 getStreamer().EmitCFIOffset(Register, Offset);
3062 /// parseDirectiveCFIRelOffset
3063 /// ::= .cfi_rel_offset register, offset
3064 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3065 int64_t Register = 0;
3067 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3070 if (getLexer().isNot(AsmToken::Comma))
3071 return TokError("unexpected token in directive");
3075 if (parseAbsoluteExpression(Offset))
3078 getStreamer().EmitCFIRelOffset(Register, Offset);
3082 static bool isValidEncoding(int64_t Encoding) {
3083 if (Encoding & ~0xff)
3086 if (Encoding == dwarf::DW_EH_PE_omit)
3089 const unsigned Format = Encoding & 0xf;
3090 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3091 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3092 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3093 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3096 const unsigned Application = Encoding & 0x70;
3097 if (Application != dwarf::DW_EH_PE_absptr &&
3098 Application != dwarf::DW_EH_PE_pcrel)
3104 /// parseDirectiveCFIPersonalityOrLsda
3105 /// IsPersonality true for cfi_personality, false for cfi_lsda
3106 /// ::= .cfi_personality encoding, [symbol_name]
3107 /// ::= .cfi_lsda encoding, [symbol_name]
3108 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3109 int64_t Encoding = 0;
3110 if (parseAbsoluteExpression(Encoding))
3112 if (Encoding == dwarf::DW_EH_PE_omit)
3115 if (!isValidEncoding(Encoding))
3116 return TokError("unsupported encoding.");
3118 if (getLexer().isNot(AsmToken::Comma))
3119 return TokError("unexpected token in directive");
3123 if (parseIdentifier(Name))
3124 return TokError("expected identifier in directive");
3126 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3129 getStreamer().EmitCFIPersonality(Sym, Encoding);
3131 getStreamer().EmitCFILsda(Sym, Encoding);
3135 /// parseDirectiveCFIRememberState
3136 /// ::= .cfi_remember_state
3137 bool AsmParser::parseDirectiveCFIRememberState() {
3138 getStreamer().EmitCFIRememberState();
3142 /// parseDirectiveCFIRestoreState
3143 /// ::= .cfi_remember_state
3144 bool AsmParser::parseDirectiveCFIRestoreState() {
3145 getStreamer().EmitCFIRestoreState();
3149 /// parseDirectiveCFISameValue
3150 /// ::= .cfi_same_value register
3151 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3152 int64_t Register = 0;
3154 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3157 getStreamer().EmitCFISameValue(Register);
3161 /// parseDirectiveCFIRestore
3162 /// ::= .cfi_restore register
3163 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3164 int64_t Register = 0;
3165 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3168 getStreamer().EmitCFIRestore(Register);
3172 /// parseDirectiveCFIEscape
3173 /// ::= .cfi_escape expression[,...]
3174 bool AsmParser::parseDirectiveCFIEscape() {
3177 if (parseAbsoluteExpression(CurrValue))
3180 Values.push_back((uint8_t)CurrValue);
3182 while (getLexer().is(AsmToken::Comma)) {
3185 if (parseAbsoluteExpression(CurrValue))
3188 Values.push_back((uint8_t)CurrValue);
3191 getStreamer().EmitCFIEscape(Values);
3195 /// parseDirectiveCFISignalFrame
3196 /// ::= .cfi_signal_frame
3197 bool AsmParser::parseDirectiveCFISignalFrame() {
3198 if (getLexer().isNot(AsmToken::EndOfStatement))
3199 return Error(getLexer().getLoc(),
3200 "unexpected token in '.cfi_signal_frame'");
3202 getStreamer().EmitCFISignalFrame();
3206 /// parseDirectiveCFIUndefined
3207 /// ::= .cfi_undefined register
3208 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3209 int64_t Register = 0;
3211 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3214 getStreamer().EmitCFIUndefined(Register);
3218 /// parseDirectiveMacrosOnOff
3221 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3222 if (getLexer().isNot(AsmToken::EndOfStatement))
3223 return Error(getLexer().getLoc(),
3224 "unexpected token in '" + Directive + "' directive");
3226 setMacrosEnabled(Directive == ".macros_on");
3230 /// parseDirectiveMacro
3231 /// ::= .macro name[,] [parameters]
3232 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3234 if (parseIdentifier(Name))
3235 return TokError("expected identifier in '.macro' directive");
3237 if (getLexer().is(AsmToken::Comma))
3240 MCAsmMacroParameters Parameters;
3241 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3242 MCAsmMacroParameter Parameter;
3243 if (parseIdentifier(Parameter.Name))
3244 return TokError("expected identifier in '.macro' directive");
3246 if (Lexer.is(AsmToken::Colon)) {
3247 Lex(); // consume ':'
3250 StringRef Qualifier;
3252 QualLoc = Lexer.getLoc();
3253 if (parseIdentifier(Qualifier))
3254 return Error(QualLoc, "missing parameter qualifier for "
3255 "'" + Parameter.Name + "' in macro '" + Name + "'");
3257 if (Qualifier == "req")
3258 Parameter.Required = true;
3260 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3261 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3264 if (getLexer().is(AsmToken::Equal)) {
3269 ParamLoc = Lexer.getLoc();
3270 if (parseMacroArgument(Parameter.Value))
3273 if (Parameter.Required)
3274 Warning(ParamLoc, "pointless default value for required parameter "
3275 "'" + Parameter.Name + "' in macro '" + Name + "'");
3278 Parameters.push_back(Parameter);
3280 if (getLexer().is(AsmToken::Comma))
3284 // Eat the end of statement.
3287 AsmToken EndToken, StartToken = getTok();
3288 unsigned MacroDepth = 0;
3290 // Lex the macro definition.
3292 // Check whether we have reached the end of the file.
3293 if (getLexer().is(AsmToken::Eof))
3294 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3296 // Otherwise, check whether we have reach the .endmacro.
3297 if (getLexer().is(AsmToken::Identifier)) {
3298 if (getTok().getIdentifier() == ".endm" ||
3299 getTok().getIdentifier() == ".endmacro") {
3300 if (MacroDepth == 0) { // Outermost macro.
3301 EndToken = getTok();
3303 if (getLexer().isNot(AsmToken::EndOfStatement))
3304 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3308 // Otherwise we just found the end of an inner macro.
3311 } else if (getTok().getIdentifier() == ".macro") {
3312 // We allow nested macros. Those aren't instantiated until the outermost
3313 // macro is expanded so just ignore them for now.
3318 // Otherwise, scan til the end of the statement.
3319 eatToEndOfStatement();
3322 if (lookupMacro(Name)) {
3323 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3326 const char *BodyStart = StartToken.getLoc().getPointer();
3327 const char *BodyEnd = EndToken.getLoc().getPointer();
3328 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3329 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3330 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3334 /// checkForBadMacro
3336 /// With the support added for named parameters there may be code out there that
3337 /// is transitioning from positional parameters. In versions of gas that did
3338 /// not support named parameters they would be ignored on the macro definition.
3339 /// But to support both styles of parameters this is not possible so if a macro
3340 /// definition has named parameters but does not use them and has what appears
3341 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3342 /// warning that the positional parameter found in body which have no effect.
3343 /// Hoping the developer will either remove the named parameters from the macro
3344 /// definition so the positional parameters get used if that was what was
3345 /// intended or change the macro to use the named parameters. It is possible
3346 /// this warning will trigger when the none of the named parameters are used
3347 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3348 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3350 ArrayRef<MCAsmMacroParameter> Parameters) {
3351 // If this macro is not defined with named parameters the warning we are
3352 // checking for here doesn't apply.
3353 unsigned NParameters = Parameters.size();
3354 if (NParameters == 0)
3357 bool NamedParametersFound = false;
3358 bool PositionalParametersFound = false;
3360 // Look at the body of the macro for use of both the named parameters and what
3361 // are likely to be positional parameters. This is what expandMacro() is
3362 // doing when it finds the parameters in the body.
3363 while (!Body.empty()) {
3364 // Scan for the next possible parameter.
3365 std::size_t End = Body.size(), Pos = 0;
3366 for (; Pos != End; ++Pos) {
3367 // Check for a substitution or escape.
3368 // This macro is defined with parameters, look for \foo, \bar, etc.
3369 if (Body[Pos] == '\\' && Pos + 1 != End)
3372 // This macro should have parameters, but look for $0, $1, ..., $n too.
3373 if (Body[Pos] != '$' || Pos + 1 == End)
3375 char Next = Body[Pos + 1];
3376 if (Next == '$' || Next == 'n' ||
3377 isdigit(static_cast<unsigned char>(Next)))
3381 // Check if we reached the end.
3385 if (Body[Pos] == '$') {
3386 switch (Body[Pos + 1]) {
3391 // $n => number of arguments
3393 PositionalParametersFound = true;
3396 // $[0-9] => argument
3398 PositionalParametersFound = true;
3404 unsigned I = Pos + 1;
3405 while (isIdentifierChar(Body[I]) && I + 1 != End)
3408 const char *Begin = Body.data() + Pos + 1;
3409 StringRef Argument(Begin, I - (Pos + 1));
3411 for (; Index < NParameters; ++Index)
3412 if (Parameters[Index].Name == Argument)
3415 if (Index == NParameters) {
3416 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3422 NamedParametersFound = true;
3423 Pos += 1 + Argument.size();
3426 // Update the scan point.
3427 Body = Body.substr(Pos);
3430 if (!NamedParametersFound && PositionalParametersFound)
3431 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3432 "used in macro body, possible positional parameter "
3433 "found in body which will have no effect");
3436 /// parseDirectiveEndMacro
3439 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3440 if (getLexer().isNot(AsmToken::EndOfStatement))
3441 return TokError("unexpected token in '" + Directive + "' directive");
3443 // If we are inside a macro instantiation, terminate the current
3445 if (isInsideMacroInstantiation()) {
3450 // Otherwise, this .endmacro is a stray entry in the file; well formed
3451 // .endmacro directives are handled during the macro definition parsing.
3452 return TokError("unexpected '" + Directive + "' in file, "
3453 "no current macro definition");
3456 /// parseDirectivePurgeMacro
3458 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3460 if (parseIdentifier(Name))
3461 return TokError("expected identifier in '.purgem' directive");
3463 if (getLexer().isNot(AsmToken::EndOfStatement))
3464 return TokError("unexpected token in '.purgem' directive");
3466 if (!lookupMacro(Name))
3467 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3469 undefineMacro(Name);
3473 /// parseDirectiveBundleAlignMode
3474 /// ::= {.bundle_align_mode} expression
3475 bool AsmParser::parseDirectiveBundleAlignMode() {
3476 checkForValidSection();
3478 // Expect a single argument: an expression that evaluates to a constant
3479 // in the inclusive range 0-30.
3480 SMLoc ExprLoc = getLexer().getLoc();
3481 int64_t AlignSizePow2;
3482 if (parseAbsoluteExpression(AlignSizePow2))
3484 else if (getLexer().isNot(AsmToken::EndOfStatement))
3485 return TokError("unexpected token after expression in"
3486 " '.bundle_align_mode' directive");
3487 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3488 return Error(ExprLoc,
3489 "invalid bundle alignment size (expected between 0 and 30)");
3493 // Because of AlignSizePow2's verified range we can safely truncate it to
3495 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3499 /// parseDirectiveBundleLock
3500 /// ::= {.bundle_lock} [align_to_end]
3501 bool AsmParser::parseDirectiveBundleLock() {
3502 checkForValidSection();
3503 bool AlignToEnd = false;
3505 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3507 SMLoc Loc = getTok().getLoc();
3508 const char *kInvalidOptionError =
3509 "invalid option for '.bundle_lock' directive";
3511 if (parseIdentifier(Option))
3512 return Error(Loc, kInvalidOptionError);
3514 if (Option != "align_to_end")
3515 return Error(Loc, kInvalidOptionError);
3516 else if (getLexer().isNot(AsmToken::EndOfStatement))
3518 "unexpected token after '.bundle_lock' directive option");
3524 getStreamer().EmitBundleLock(AlignToEnd);
3528 /// parseDirectiveBundleLock
3529 /// ::= {.bundle_lock}
3530 bool AsmParser::parseDirectiveBundleUnlock() {
3531 checkForValidSection();
3533 if (getLexer().isNot(AsmToken::EndOfStatement))
3534 return TokError("unexpected token in '.bundle_unlock' directive");
3537 getStreamer().EmitBundleUnlock();
3541 /// parseDirectiveSpace
3542 /// ::= (.skip | .space) expression [ , expression ]
3543 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3544 checkForValidSection();
3547 if (parseAbsoluteExpression(NumBytes))
3550 int64_t FillExpr = 0;
3551 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3552 if (getLexer().isNot(AsmToken::Comma))
3553 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3556 if (parseAbsoluteExpression(FillExpr))
3559 if (getLexer().isNot(AsmToken::EndOfStatement))
3560 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3566 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3569 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3570 getStreamer().EmitFill(NumBytes, FillExpr);
3575 /// parseDirectiveLEB128
3576 /// ::= (.sleb128 | .uleb128) expression
3577 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3578 checkForValidSection();
3579 const MCExpr *Value;
3581 if (parseExpression(Value))
3584 if (getLexer().isNot(AsmToken::EndOfStatement))
3585 return TokError("unexpected token in directive");
3588 getStreamer().EmitSLEB128Value(Value);
3590 getStreamer().EmitULEB128Value(Value);
3595 /// parseDirectiveSymbolAttribute
3596 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3597 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3598 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3601 SMLoc Loc = getTok().getLoc();
3603 if (parseIdentifier(Name))
3604 return Error(Loc, "expected identifier in directive");
3606 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3608 // Assembler local symbols don't make any sense here. Complain loudly.
3609 if (Sym->isTemporary())
3610 return Error(Loc, "non-local symbol required in directive");
3612 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3613 return Error(Loc, "unable to emit symbol attribute");
3615 if (getLexer().is(AsmToken::EndOfStatement))
3618 if (getLexer().isNot(AsmToken::Comma))
3619 return TokError("unexpected token in directive");
3628 /// parseDirectiveComm
3629 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3630 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3631 checkForValidSection();
3633 SMLoc IDLoc = getLexer().getLoc();
3635 if (parseIdentifier(Name))
3636 return TokError("expected identifier in directive");
3638 // Handle the identifier as the key symbol.
3639 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3641 if (getLexer().isNot(AsmToken::Comma))
3642 return TokError("unexpected token in directive");
3646 SMLoc SizeLoc = getLexer().getLoc();
3647 if (parseAbsoluteExpression(Size))
3650 int64_t Pow2Alignment = 0;
3651 SMLoc Pow2AlignmentLoc;
3652 if (getLexer().is(AsmToken::Comma)) {
3654 Pow2AlignmentLoc = getLexer().getLoc();
3655 if (parseAbsoluteExpression(Pow2Alignment))
3658 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3659 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3660 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3662 // If this target takes alignments in bytes (not log) validate and convert.
3663 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3664 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3665 if (!isPowerOf2_64(Pow2Alignment))
3666 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3667 Pow2Alignment = Log2_64(Pow2Alignment);
3671 if (getLexer().isNot(AsmToken::EndOfStatement))
3672 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3676 // NOTE: a size of zero for a .comm should create a undefined symbol
3677 // but a size of .lcomm creates a bss symbol of size zero.
3679 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3680 "be less than zero");
3682 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3683 // may internally end up wanting an alignment in bytes.
3684 // FIXME: Diagnose overflow.
3685 if (Pow2Alignment < 0)
3686 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3687 "alignment, can't be less than zero");
3689 if (!Sym->isUndefined())
3690 return Error(IDLoc, "invalid symbol redefinition");
3692 // Create the Symbol as a common or local common with Size and Pow2Alignment
3694 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3698 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3702 /// parseDirectiveAbort
3703 /// ::= .abort [... message ...]
3704 bool AsmParser::parseDirectiveAbort() {
3705 // FIXME: Use loc from directive.
3706 SMLoc Loc = getLexer().getLoc();
3708 StringRef Str = parseStringToEndOfStatement();
3709 if (getLexer().isNot(AsmToken::EndOfStatement))
3710 return TokError("unexpected token in '.abort' directive");
3715 Error(Loc, ".abort detected. Assembly stopping.");
3717 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3718 // FIXME: Actually abort assembly here.
3723 /// parseDirectiveInclude
3724 /// ::= .include "filename"
3725 bool AsmParser::parseDirectiveInclude() {
3726 if (getLexer().isNot(AsmToken::String))
3727 return TokError("expected string in '.include' directive");
3729 // Allow the strings to have escaped octal character sequence.
3730 std::string Filename;
3731 if (parseEscapedString(Filename))
3733 SMLoc IncludeLoc = getLexer().getLoc();
3736 if (getLexer().isNot(AsmToken::EndOfStatement))
3737 return TokError("unexpected token in '.include' directive");
3739 // Attempt to switch the lexer to the included file before consuming the end
3740 // of statement to avoid losing it when we switch.
3741 if (enterIncludeFile(Filename)) {
3742 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3749 /// parseDirectiveIncbin
3750 /// ::= .incbin "filename"
3751 bool AsmParser::parseDirectiveIncbin() {
3752 if (getLexer().isNot(AsmToken::String))
3753 return TokError("expected string in '.incbin' directive");
3755 // Allow the strings to have escaped octal character sequence.
3756 std::string Filename;
3757 if (parseEscapedString(Filename))
3759 SMLoc IncbinLoc = getLexer().getLoc();
3762 if (getLexer().isNot(AsmToken::EndOfStatement))
3763 return TokError("unexpected token in '.incbin' directive");
3765 // Attempt to process the included file.
3766 if (processIncbinFile(Filename)) {
3767 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3774 /// parseDirectiveIf
3775 /// ::= .if expression
3776 /// ::= .ifne expression
3777 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3778 TheCondStack.push_back(TheCondState);
3779 TheCondState.TheCond = AsmCond::IfCond;
3780 if (TheCondState.Ignore) {
3781 eatToEndOfStatement();
3784 if (parseAbsoluteExpression(ExprValue))
3787 if (getLexer().isNot(AsmToken::EndOfStatement))
3788 return TokError("unexpected token in '.if' directive");
3792 TheCondState.CondMet = ExprValue;
3793 TheCondState.Ignore = !TheCondState.CondMet;
3799 /// parseDirectiveIfb
3801 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3802 TheCondStack.push_back(TheCondState);
3803 TheCondState.TheCond = AsmCond::IfCond;
3805 if (TheCondState.Ignore) {
3806 eatToEndOfStatement();
3808 StringRef Str = parseStringToEndOfStatement();
3810 if (getLexer().isNot(AsmToken::EndOfStatement))
3811 return TokError("unexpected token in '.ifb' directive");
3815 TheCondState.CondMet = ExpectBlank == Str.empty();
3816 TheCondState.Ignore = !TheCondState.CondMet;
3822 /// parseDirectiveIfc
3823 /// ::= .ifc string1, string2
3824 /// ::= .ifnc string1, string2
3825 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3826 TheCondStack.push_back(TheCondState);
3827 TheCondState.TheCond = AsmCond::IfCond;
3829 if (TheCondState.Ignore) {
3830 eatToEndOfStatement();
3832 StringRef Str1 = parseStringToComma();
3834 if (getLexer().isNot(AsmToken::Comma))
3835 return TokError("unexpected token in '.ifc' directive");
3839 StringRef Str2 = parseStringToEndOfStatement();
3841 if (getLexer().isNot(AsmToken::EndOfStatement))
3842 return TokError("unexpected token in '.ifc' directive");
3846 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3847 TheCondState.Ignore = !TheCondState.CondMet;
3853 /// parseDirectiveIfeqs
3854 /// ::= .ifeqs string1, string2
3855 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc) {
3856 if (Lexer.isNot(AsmToken::String)) {
3857 TokError("expected string parameter for '.ifeqs' directive");
3858 eatToEndOfStatement();
3862 StringRef String1 = getTok().getStringContents();
3865 if (Lexer.isNot(AsmToken::Comma)) {
3866 TokError("expected comma after first string for '.ifeqs' directive");
3867 eatToEndOfStatement();
3873 if (Lexer.isNot(AsmToken::String)) {
3874 TokError("expected string parameter for '.ifeqs' directive");
3875 eatToEndOfStatement();
3879 StringRef String2 = getTok().getStringContents();
3882 TheCondStack.push_back(TheCondState);
3883 TheCondState.TheCond = AsmCond::IfCond;
3884 TheCondState.CondMet = String1 == String2;
3885 TheCondState.Ignore = !TheCondState.CondMet;
3890 /// parseDirectiveIfdef
3891 /// ::= .ifdef symbol
3892 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3894 TheCondStack.push_back(TheCondState);
3895 TheCondState.TheCond = AsmCond::IfCond;
3897 if (TheCondState.Ignore) {
3898 eatToEndOfStatement();
3900 if (parseIdentifier(Name))
3901 return TokError("expected identifier after '.ifdef'");
3905 MCSymbol *Sym = getContext().LookupSymbol(Name);
3908 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3910 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3911 TheCondState.Ignore = !TheCondState.CondMet;
3917 /// parseDirectiveElseIf
3918 /// ::= .elseif expression
3919 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3920 if (TheCondState.TheCond != AsmCond::IfCond &&
3921 TheCondState.TheCond != AsmCond::ElseIfCond)
3922 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3924 TheCondState.TheCond = AsmCond::ElseIfCond;
3926 bool LastIgnoreState = false;
3927 if (!TheCondStack.empty())
3928 LastIgnoreState = TheCondStack.back().Ignore;
3929 if (LastIgnoreState || TheCondState.CondMet) {
3930 TheCondState.Ignore = true;
3931 eatToEndOfStatement();
3934 if (parseAbsoluteExpression(ExprValue))
3937 if (getLexer().isNot(AsmToken::EndOfStatement))
3938 return TokError("unexpected token in '.elseif' directive");
3941 TheCondState.CondMet = ExprValue;
3942 TheCondState.Ignore = !TheCondState.CondMet;
3948 /// parseDirectiveElse
3950 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3951 if (getLexer().isNot(AsmToken::EndOfStatement))
3952 return TokError("unexpected token in '.else' directive");
3956 if (TheCondState.TheCond != AsmCond::IfCond &&
3957 TheCondState.TheCond != AsmCond::ElseIfCond)
3958 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3960 TheCondState.TheCond = AsmCond::ElseCond;
3961 bool LastIgnoreState = false;
3962 if (!TheCondStack.empty())
3963 LastIgnoreState = TheCondStack.back().Ignore;
3964 if (LastIgnoreState || TheCondState.CondMet)
3965 TheCondState.Ignore = true;
3967 TheCondState.Ignore = false;
3972 /// parseDirectiveEnd
3974 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
3975 if (getLexer().isNot(AsmToken::EndOfStatement))
3976 return TokError("unexpected token in '.end' directive");
3980 while (Lexer.isNot(AsmToken::Eof))
3986 /// parseDirectiveError
3988 /// ::= .error [string]
3989 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
3990 if (!TheCondStack.empty()) {
3991 if (TheCondStack.back().Ignore) {
3992 eatToEndOfStatement();
3998 return Error(L, ".err encountered");
4000 StringRef Message = ".error directive invoked in source file";
4001 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4002 if (Lexer.isNot(AsmToken::String)) {
4003 TokError(".error argument must be a string");
4004 eatToEndOfStatement();
4008 Message = getTok().getStringContents();
4016 /// parseDirectiveEndIf
4018 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4019 if (getLexer().isNot(AsmToken::EndOfStatement))
4020 return TokError("unexpected token in '.endif' directive");
4024 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4025 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4027 if (!TheCondStack.empty()) {
4028 TheCondState = TheCondStack.back();
4029 TheCondStack.pop_back();
4035 void AsmParser::initializeDirectiveKindMap() {
4036 DirectiveKindMap[".set"] = DK_SET;
4037 DirectiveKindMap[".equ"] = DK_EQU;
4038 DirectiveKindMap[".equiv"] = DK_EQUIV;
4039 DirectiveKindMap[".ascii"] = DK_ASCII;
4040 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4041 DirectiveKindMap[".string"] = DK_STRING;
4042 DirectiveKindMap[".byte"] = DK_BYTE;
4043 DirectiveKindMap[".short"] = DK_SHORT;
4044 DirectiveKindMap[".value"] = DK_VALUE;
4045 DirectiveKindMap[".2byte"] = DK_2BYTE;
4046 DirectiveKindMap[".long"] = DK_LONG;
4047 DirectiveKindMap[".int"] = DK_INT;
4048 DirectiveKindMap[".4byte"] = DK_4BYTE;
4049 DirectiveKindMap[".quad"] = DK_QUAD;
4050 DirectiveKindMap[".8byte"] = DK_8BYTE;
4051 DirectiveKindMap[".octa"] = DK_OCTA;
4052 DirectiveKindMap[".single"] = DK_SINGLE;
4053 DirectiveKindMap[".float"] = DK_FLOAT;
4054 DirectiveKindMap[".double"] = DK_DOUBLE;
4055 DirectiveKindMap[".align"] = DK_ALIGN;
4056 DirectiveKindMap[".align32"] = DK_ALIGN32;
4057 DirectiveKindMap[".balign"] = DK_BALIGN;
4058 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4059 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4060 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4061 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4062 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4063 DirectiveKindMap[".org"] = DK_ORG;
4064 DirectiveKindMap[".fill"] = DK_FILL;
4065 DirectiveKindMap[".zero"] = DK_ZERO;
4066 DirectiveKindMap[".extern"] = DK_EXTERN;
4067 DirectiveKindMap[".globl"] = DK_GLOBL;
4068 DirectiveKindMap[".global"] = DK_GLOBAL;
4069 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4070 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4071 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4072 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4073 DirectiveKindMap[".reference"] = DK_REFERENCE;
4074 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4075 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4076 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4077 DirectiveKindMap[".comm"] = DK_COMM;
4078 DirectiveKindMap[".common"] = DK_COMMON;
4079 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4080 DirectiveKindMap[".abort"] = DK_ABORT;
4081 DirectiveKindMap[".include"] = DK_INCLUDE;
4082 DirectiveKindMap[".incbin"] = DK_INCBIN;
4083 DirectiveKindMap[".code16"] = DK_CODE16;
4084 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4085 DirectiveKindMap[".rept"] = DK_REPT;
4086 DirectiveKindMap[".rep"] = DK_REPT;
4087 DirectiveKindMap[".irp"] = DK_IRP;
4088 DirectiveKindMap[".irpc"] = DK_IRPC;
4089 DirectiveKindMap[".endr"] = DK_ENDR;
4090 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4091 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4092 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4093 DirectiveKindMap[".if"] = DK_IF;
4094 DirectiveKindMap[".ifne"] = DK_IFNE;
4095 DirectiveKindMap[".ifb"] = DK_IFB;
4096 DirectiveKindMap[".ifnb"] = DK_IFNB;
4097 DirectiveKindMap[".ifc"] = DK_IFC;
4098 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4099 DirectiveKindMap[".ifnc"] = DK_IFNC;
4100 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4101 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4102 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4103 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4104 DirectiveKindMap[".else"] = DK_ELSE;
4105 DirectiveKindMap[".end"] = DK_END;
4106 DirectiveKindMap[".endif"] = DK_ENDIF;
4107 DirectiveKindMap[".skip"] = DK_SKIP;
4108 DirectiveKindMap[".space"] = DK_SPACE;
4109 DirectiveKindMap[".file"] = DK_FILE;
4110 DirectiveKindMap[".line"] = DK_LINE;
4111 DirectiveKindMap[".loc"] = DK_LOC;
4112 DirectiveKindMap[".stabs"] = DK_STABS;
4113 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4114 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4115 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4116 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4117 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4118 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4119 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4120 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4121 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4122 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4123 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4124 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4125 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4126 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4127 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4128 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4129 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4130 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4131 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4132 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4133 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4134 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4135 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4136 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4137 DirectiveKindMap[".macro"] = DK_MACRO;
4138 DirectiveKindMap[".endm"] = DK_ENDM;
4139 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4140 DirectiveKindMap[".purgem"] = DK_PURGEM;
4141 DirectiveKindMap[".err"] = DK_ERR;
4142 DirectiveKindMap[".error"] = DK_ERROR;
4145 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4146 AsmToken EndToken, StartToken = getTok();
4148 unsigned NestLevel = 0;
4150 // Check whether we have reached the end of the file.
4151 if (getLexer().is(AsmToken::Eof)) {
4152 Error(DirectiveLoc, "no matching '.endr' in definition");
4156 if (Lexer.is(AsmToken::Identifier) &&
4157 (getTok().getIdentifier() == ".rept")) {
4161 // Otherwise, check whether we have reached the .endr.
4162 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4163 if (NestLevel == 0) {
4164 EndToken = getTok();
4166 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4167 TokError("unexpected token in '.endr' directive");
4175 // Otherwise, scan till the end of the statement.
4176 eatToEndOfStatement();
4179 const char *BodyStart = StartToken.getLoc().getPointer();
4180 const char *BodyEnd = EndToken.getLoc().getPointer();
4181 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4183 // We Are Anonymous.
4184 MacroLikeBodies.push_back(MCAsmMacro(StringRef(), Body, None));
4185 return &MacroLikeBodies.back();
4188 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4189 raw_svector_ostream &OS) {
4192 MemoryBuffer *Instantiation =
4193 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4195 // Create the macro instantiation object and add to the current macro
4196 // instantiation stack.
4197 MacroInstantiation *MI = new MacroInstantiation(
4198 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
4199 ActiveMacros.push_back(MI);
4201 // Jump to the macro instantiation and prime the lexer.
4202 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
4203 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
4207 /// parseDirectiveRept
4208 /// ::= .rep | .rept count
4209 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4210 const MCExpr *CountExpr;
4211 SMLoc CountLoc = getTok().getLoc();
4212 if (parseExpression(CountExpr))
4216 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4217 eatToEndOfStatement();
4218 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4222 return Error(CountLoc, "Count is negative");
4224 if (Lexer.isNot(AsmToken::EndOfStatement))
4225 return TokError("unexpected token in '" + Dir + "' directive");
4227 // Eat the end of statement.
4230 // Lex the rept definition.
4231 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4235 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4236 // to hold the macro body with substitutions.
4237 SmallString<256> Buf;
4238 raw_svector_ostream OS(Buf);
4240 if (expandMacro(OS, M->Body, None, None, getTok().getLoc()))
4243 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4248 /// parseDirectiveIrp
4249 /// ::= .irp symbol,values
4250 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4251 MCAsmMacroParameter Parameter;
4253 if (parseIdentifier(Parameter.Name))
4254 return TokError("expected identifier in '.irp' directive");
4256 if (Lexer.isNot(AsmToken::Comma))
4257 return TokError("expected comma in '.irp' directive");
4261 MCAsmMacroArguments A;
4262 if (parseMacroArguments(0, A))
4265 // Eat the end of statement.
4268 // Lex the irp definition.
4269 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4273 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4274 // to hold the macro body with substitutions.
4275 SmallString<256> Buf;
4276 raw_svector_ostream OS(Buf);
4278 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4279 if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc()))
4283 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4288 /// parseDirectiveIrpc
4289 /// ::= .irpc symbol,values
4290 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4291 MCAsmMacroParameter Parameter;
4293 if (parseIdentifier(Parameter.Name))
4294 return TokError("expected identifier in '.irpc' directive");
4296 if (Lexer.isNot(AsmToken::Comma))
4297 return TokError("expected comma in '.irpc' directive");
4301 MCAsmMacroArguments A;
4302 if (parseMacroArguments(0, A))
4305 if (A.size() != 1 || A.front().size() != 1)
4306 return TokError("unexpected token in '.irpc' directive");
4308 // Eat the end of statement.
4311 // Lex the irpc definition.
4312 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4316 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4317 // to hold the macro body with substitutions.
4318 SmallString<256> Buf;
4319 raw_svector_ostream OS(Buf);
4321 StringRef Values = A.front().front().getString();
4322 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4323 MCAsmMacroArgument Arg;
4324 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4326 if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc()))
4330 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4335 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4336 if (ActiveMacros.empty())
4337 return TokError("unmatched '.endr' directive");
4339 // The only .repl that should get here are the ones created by
4340 // instantiateMacroLikeBody.
4341 assert(getLexer().is(AsmToken::EndOfStatement));
4347 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4349 const MCExpr *Value;
4350 SMLoc ExprLoc = getLexer().getLoc();
4351 if (parseExpression(Value))
4353 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4355 return Error(ExprLoc, "unexpected expression in _emit");
4356 uint64_t IntValue = MCE->getValue();
4357 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4358 return Error(ExprLoc, "literal value out of range for directive");
4360 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4364 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4365 const MCExpr *Value;
4366 SMLoc ExprLoc = getLexer().getLoc();
4367 if (parseExpression(Value))
4369 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4371 return Error(ExprLoc, "unexpected expression in align");
4372 uint64_t IntValue = MCE->getValue();
4373 if (!isPowerOf2_64(IntValue))
4374 return Error(ExprLoc, "literal value not a power of two greater then zero");
4376 Info.AsmRewrites->push_back(
4377 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4381 // We are comparing pointers, but the pointers are relative to a single string.
4382 // Thus, this should always be deterministic.
4383 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4384 const AsmRewrite *AsmRewriteB) {
4385 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4387 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4390 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4391 // rewrite to the same location. Make sure the SizeDirective rewrite is
4392 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4393 // ensures the sort algorithm is stable.
4394 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4395 AsmRewritePrecedence[AsmRewriteB->Kind])
4398 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4399 AsmRewritePrecedence[AsmRewriteB->Kind])
4401 llvm_unreachable("Unstable rewrite sort.");
4404 bool AsmParser::parseMSInlineAsm(
4405 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4406 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4407 SmallVectorImpl<std::string> &Constraints,
4408 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4409 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4410 SmallVector<void *, 4> InputDecls;
4411 SmallVector<void *, 4> OutputDecls;
4412 SmallVector<bool, 4> InputDeclsAddressOf;
4413 SmallVector<bool, 4> OutputDeclsAddressOf;
4414 SmallVector<std::string, 4> InputConstraints;
4415 SmallVector<std::string, 4> OutputConstraints;
4416 SmallVector<unsigned, 4> ClobberRegs;
4418 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4423 // While we have input, parse each statement.
4424 unsigned InputIdx = 0;
4425 unsigned OutputIdx = 0;
4426 while (getLexer().isNot(AsmToken::Eof)) {
4427 ParseStatementInfo Info(&AsmStrRewrites);
4428 if (parseStatement(Info))
4431 if (Info.ParseError)
4434 if (Info.Opcode == ~0U)
4437 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4439 // Build the list of clobbers, outputs and inputs.
4440 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4441 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4444 if (Operand->isImm())
4447 // Register operand.
4448 if (Operand->isReg() && !Operand->needAddressOf()) {
4449 unsigned NumDefs = Desc.getNumDefs();
4451 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4452 ClobberRegs.push_back(Operand->getReg());
4456 // Expr/Input or Output.
4457 StringRef SymName = Operand->getSymName();
4458 if (SymName.empty())
4461 void *OpDecl = Operand->getOpDecl();
4465 bool isOutput = (i == 1) && Desc.mayStore();
4466 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4469 OutputDecls.push_back(OpDecl);
4470 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4471 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4472 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4474 InputDecls.push_back(OpDecl);
4475 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4476 InputConstraints.push_back(Operand->getConstraint().str());
4477 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4481 // Consider implicit defs to be clobbers. Think of cpuid and push.
4482 const uint16_t *ImpDefs = Desc.getImplicitDefs();
4483 for (unsigned I = 0, E = Desc.getNumImplicitDefs(); I != E; ++I)
4484 ClobberRegs.push_back(ImpDefs[I]);
4487 // Set the number of Outputs and Inputs.
4488 NumOutputs = OutputDecls.size();
4489 NumInputs = InputDecls.size();
4491 // Set the unique clobbers.
4492 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4493 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4495 Clobbers.assign(ClobberRegs.size(), std::string());
4496 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4497 raw_string_ostream OS(Clobbers[I]);
4498 IP->printRegName(OS, ClobberRegs[I]);
4501 // Merge the various outputs and inputs. Output are expected first.
4502 if (NumOutputs || NumInputs) {
4503 unsigned NumExprs = NumOutputs + NumInputs;
4504 OpDecls.resize(NumExprs);
4505 Constraints.resize(NumExprs);
4506 for (unsigned i = 0; i < NumOutputs; ++i) {
4507 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4508 Constraints[i] = OutputConstraints[i];
4510 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4511 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4512 Constraints[j] = InputConstraints[i];
4516 // Build the IR assembly string.
4517 std::string AsmStringIR;
4518 raw_string_ostream OS(AsmStringIR);
4519 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4520 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4521 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4522 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4523 E = AsmStrRewrites.end();
4525 AsmRewriteKind Kind = (*I).Kind;
4526 if (Kind == AOK_Delete)
4529 const char *Loc = (*I).Loc.getPointer();
4530 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4532 // Emit everything up to the immediate/expression.
4533 unsigned Len = Loc - AsmStart;
4535 OS << StringRef(AsmStart, Len);
4537 // Skip the original expression.
4538 if (Kind == AOK_Skip) {
4539 AsmStart = Loc + (*I).Len;
4543 unsigned AdditionalSkip = 0;
4544 // Rewrite expressions in $N notation.
4549 OS << "$$" << (*I).Val;
4555 OS << '$' << InputIdx++;
4558 OS << '$' << OutputIdx++;
4560 case AOK_SizeDirective:
4563 case 8: OS << "byte ptr "; break;
4564 case 16: OS << "word ptr "; break;
4565 case 32: OS << "dword ptr "; break;
4566 case 64: OS << "qword ptr "; break;
4567 case 80: OS << "xword ptr "; break;
4568 case 128: OS << "xmmword ptr "; break;
4569 case 256: OS << "ymmword ptr "; break;
4576 unsigned Val = (*I).Val;
4577 OS << ".align " << Val;
4579 // Skip the original immediate.
4580 assert(Val < 10 && "Expected alignment less then 2^10.");
4581 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4584 case AOK_DotOperator:
4585 // Insert the dot if the user omitted it.
4587 if (AsmStringIR.back() != '.')
4593 // Skip the original expression.
4594 AsmStart = Loc + (*I).Len + AdditionalSkip;
4597 // Emit the remainder of the asm string.
4598 if (AsmStart != AsmEnd)
4599 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4601 AsmString = OS.str();
4605 /// \brief Create an MCAsmParser instance.
4606 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4607 MCStreamer &Out, const MCAsmInfo &MAI) {
4608 return new AsmParser(SM, C, Out, MAI);