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() {}
55 /// \brief Helper types for tracking macro definitions.
56 typedef std::vector<AsmToken> MCAsmMacroArgument;
57 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
58 typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
59 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
64 MCAsmMacroParameters Parameters;
67 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
68 Name(N), Body(B), Parameters(P) {}
70 MCAsmMacro(const MCAsmMacro& Other)
71 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
74 /// \brief Helper class for storing information about an active macro
76 struct MacroInstantiation {
77 /// The macro being instantiated.
78 const MCAsmMacro *TheMacro;
80 /// The macro instantiation with substitutions.
81 MemoryBuffer *Instantiation;
83 /// The location of the instantiation.
84 SMLoc InstantiationLoc;
86 /// The buffer where parsing should resume upon instantiation completion.
89 /// The location where parsing should resume upon instantiation completion.
93 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
97 struct ParseStatementInfo {
98 /// \brief The parsed operands from the last parsed statement.
99 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
101 /// \brief The opcode from the last parsed instruction.
104 /// \brief Was there an error parsing the inline assembly?
107 SmallVectorImpl<AsmRewrite> *AsmRewrites;
109 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
110 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
111 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
113 ~ParseStatementInfo() {
114 // Free any parsed operands.
115 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
116 delete ParsedOperands[i];
117 ParsedOperands.clear();
121 /// \brief The concrete assembly parser instance.
122 class AsmParser : public MCAsmParser {
123 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
124 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
129 const MCAsmInfo &MAI;
131 SourceMgr::DiagHandlerTy SavedDiagHandler;
132 void *SavedDiagContext;
133 MCAsmParserExtension *PlatformParser;
135 /// This is the current buffer index we're lexing from as managed by the
136 /// SourceMgr object.
139 AsmCond TheCondState;
140 std::vector<AsmCond> TheCondStack;
142 /// \brief maps directive names to handler methods in parser
143 /// extensions. Extensions register themselves in this map by calling
144 /// addDirectiveHandler.
145 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
147 /// \brief Map of currently defined macros.
148 StringMap<MCAsmMacro*> MacroMap;
150 /// \brief Stack of active macro instantiations.
151 std::vector<MacroInstantiation*> ActiveMacros;
153 /// \brief List of bodies of anonymous macros.
154 std::deque<MCAsmMacro> MacroLikeBodies;
156 /// Boolean tracking whether macro substitution is enabled.
157 unsigned MacrosEnabledFlag : 1;
159 /// Flag tracking whether any errors have been encountered.
160 unsigned HadError : 1;
162 /// The values from the last parsed cpp hash file line comment if any.
163 StringRef CppHashFilename;
164 int64_t CppHashLineNumber;
167 /// When generating dwarf for assembly source files we need to calculate the
168 /// logical line number based on the last parsed cpp hash file line comment
169 /// and current line. Since this is slow and messes up the SourceMgr's
170 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
171 SMLoc LastQueryIDLoc;
173 unsigned LastQueryLine;
175 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
176 unsigned AssemblerDialect;
178 /// \brief is Darwin compatibility enabled?
181 /// \brief Are we parsing ms-style inline assembly?
182 bool ParsingInlineAsm;
185 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
186 const MCAsmInfo &MAI);
187 virtual ~AsmParser();
189 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
191 virtual void addDirectiveHandler(StringRef Directive,
192 ExtensionDirectiveHandler Handler) {
193 ExtensionDirectiveMap[Directive] = Handler;
197 /// @name MCAsmParser Interface
200 virtual SourceMgr &getSourceManager() { return SrcMgr; }
201 virtual MCAsmLexer &getLexer() { return Lexer; }
202 virtual MCContext &getContext() { return Ctx; }
203 virtual MCStreamer &getStreamer() { return Out; }
204 virtual unsigned getAssemblerDialect() {
205 if (AssemblerDialect == ~0U)
206 return MAI.getAssemblerDialect();
208 return AssemblerDialect;
210 virtual void setAssemblerDialect(unsigned i) {
211 AssemblerDialect = i;
214 virtual void Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges = None);
215 virtual bool Warning(SMLoc L, const Twine &Msg,
216 ArrayRef<SMRange> Ranges = None);
217 virtual bool Error(SMLoc L, const Twine &Msg,
218 ArrayRef<SMRange> Ranges = None);
220 virtual const AsmToken &Lex();
222 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
223 bool isParsingInlineAsm() { return ParsingInlineAsm; }
225 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
226 unsigned &NumOutputs, unsigned &NumInputs,
227 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
228 SmallVectorImpl<std::string> &Constraints,
229 SmallVectorImpl<std::string> &Clobbers,
230 const MCInstrInfo *MII,
231 const MCInstPrinter *IP,
232 MCAsmParserSemaCallback &SI);
234 bool parseExpression(const MCExpr *&Res);
235 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
236 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
237 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
238 virtual bool parseAbsoluteExpression(int64_t &Res);
240 /// \brief Parse an identifier or string (as a quoted identifier)
241 /// and set \p Res to the identifier contents.
242 virtual bool parseIdentifier(StringRef &Res);
243 virtual void eatToEndOfStatement();
245 virtual void checkForValidSection();
250 bool parseStatement(ParseStatementInfo &Info);
251 void eatToEndOfLine();
252 bool parseCppHashLineFilenameComment(const SMLoc &L);
254 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
255 MCAsmMacroParameters Parameters);
256 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
257 const MCAsmMacroParameters &Parameters,
258 const MCAsmMacroArguments &A,
261 /// \brief Are macros enabled in the parser?
262 bool areMacrosEnabled() {return MacrosEnabledFlag;}
264 /// \brief Control a flag in the parser that enables or disables macros.
265 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
267 /// \brief Lookup a previously defined macro.
268 /// \param Name Macro name.
269 /// \returns Pointer to macro. NULL if no such macro was defined.
270 const MCAsmMacro* lookupMacro(StringRef Name);
272 /// \brief Define a new macro with the given name and information.
273 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
275 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
276 void undefineMacro(StringRef Name);
278 /// \brief Are we inside a macro instantiation?
279 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
281 /// \brief Handle entry to macro instantiation.
283 /// \param M The macro.
284 /// \param NameLoc Instantiation location.
285 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
287 /// \brief Handle exit from macro instantiation.
288 void handleMacroExit();
290 /// \brief Extract AsmTokens for a macro argument.
291 bool parseMacroArgument(MCAsmMacroArgument &MA);
293 /// \brief Parse all macro arguments for a given macro.
294 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
296 void printMacroInstantiations();
297 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
298 ArrayRef<SMRange> Ranges = None) const {
299 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
301 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
303 /// \brief Enter the specified file. This returns true on failure.
304 bool enterIncludeFile(const std::string &Filename);
306 /// \brief Process the specified file for the .incbin directive.
307 /// This returns true on failure.
308 bool processIncbinFile(const std::string &Filename);
310 /// \brief Reset the current lexer position to that given by \p Loc. The
311 /// current token is not set; clients should ensure Lex() is called
314 /// \param InBuffer If not -1, should be the known buffer id that contains the
316 void jumpToLoc(SMLoc Loc, int InBuffer=-1);
318 /// \brief Parse up to the end of statement and a return the contents from the
319 /// current token until the end of the statement; the current token on exit
320 /// will be either the EndOfStatement or EOF.
321 virtual StringRef parseStringToEndOfStatement();
323 /// \brief Parse until the end of a statement or a comma is encountered,
324 /// return the contents from the current token up to the end or comma.
325 StringRef parseStringToComma();
327 bool parseAssignment(StringRef Name, bool allow_redef,
328 bool NoDeadStrip = false);
330 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
331 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
332 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
334 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
336 // Generic (target and platform independent) directive parsing.
338 DK_NO_DIRECTIVE, // Placeholder
339 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
340 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
341 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
342 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
343 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
344 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
345 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
346 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
347 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
348 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
349 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
350 DK_ELSEIF, DK_ELSE, DK_ENDIF,
351 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
352 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
353 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
354 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
355 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
356 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
357 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
358 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
359 DK_SLEB128, DK_ULEB128,
363 /// \brief Maps directive name --> DirectiveKind enum, for
364 /// directives parsed by this class.
365 StringMap<DirectiveKind> DirectiveKindMap;
367 // ".ascii", ".asciz", ".string"
368 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
369 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
370 bool parseDirectiveOctaValue(); // ".octa"
371 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
372 bool parseDirectiveFill(); // ".fill"
373 bool parseDirectiveZero(); // ".zero"
374 // ".set", ".equ", ".equiv"
375 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
376 bool parseDirectiveOrg(); // ".org"
377 // ".align{,32}", ".p2align{,w,l}"
378 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
380 // ".file", ".line", ".loc", ".stabs"
381 bool parseDirectiveFile(SMLoc DirectiveLoc);
382 bool parseDirectiveLine();
383 bool parseDirectiveLoc();
384 bool parseDirectiveStabs();
387 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
388 bool parseDirectiveCFIWindowSave();
389 bool parseDirectiveCFISections();
390 bool parseDirectiveCFIStartProc();
391 bool parseDirectiveCFIEndProc();
392 bool parseDirectiveCFIDefCfaOffset();
393 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
394 bool parseDirectiveCFIAdjustCfaOffset();
395 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
396 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
397 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
398 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
399 bool parseDirectiveCFIRememberState();
400 bool parseDirectiveCFIRestoreState();
401 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
403 bool parseDirectiveCFIEscape();
404 bool parseDirectiveCFISignalFrame();
405 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
408 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
409 bool parseDirectiveEndMacro(StringRef Directive);
410 bool parseDirectiveMacro(SMLoc DirectiveLoc);
411 bool parseDirectiveMacrosOnOff(StringRef Directive);
413 // ".bundle_align_mode"
414 bool parseDirectiveBundleAlignMode();
416 bool parseDirectiveBundleLock();
418 bool parseDirectiveBundleUnlock();
421 bool parseDirectiveSpace(StringRef IDVal);
423 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
424 bool parseDirectiveLEB128(bool Signed);
426 /// \brief Parse a directive like ".globl" which
427 /// accepts a single symbol (which should be a label or an external).
428 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
430 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
432 bool parseDirectiveAbort(); // ".abort"
433 bool parseDirectiveInclude(); // ".include"
434 bool parseDirectiveIncbin(); // ".incbin"
436 bool parseDirectiveIf(SMLoc DirectiveLoc); // ".if"
437 // ".ifb" or ".ifnb", depending on ExpectBlank.
438 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
439 // ".ifc" or ".ifnc", depending on ExpectEqual.
440 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
441 // ".ifdef" or ".ifndef", depending on expect_defined
442 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
443 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
444 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
445 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
446 virtual bool parseEscapedString(std::string &Data);
448 const MCExpr *applyModifierToExpr(const MCExpr *E,
449 MCSymbolRefExpr::VariantKind Variant);
451 // Macro-like directives
452 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
453 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
454 raw_svector_ostream &OS);
455 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
456 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
457 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
458 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
460 // "_emit" or "__emit"
461 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
465 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
468 bool parseDirectiveEnd(SMLoc DirectiveLoc);
470 void initializeDirectiveKindMap();
476 extern MCAsmParserExtension *createDarwinAsmParser();
477 extern MCAsmParserExtension *createELFAsmParser();
478 extern MCAsmParserExtension *createCOFFAsmParser();
482 enum { DEFAULT_ADDRSPACE = 0 };
484 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
485 const MCAsmInfo &_MAI)
486 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
487 PlatformParser(0), CurBuffer(0), MacrosEnabledFlag(true),
488 CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false),
489 ParsingInlineAsm(false) {
490 // Save the old handler.
491 SavedDiagHandler = SrcMgr.getDiagHandler();
492 SavedDiagContext = SrcMgr.getDiagContext();
493 // Set our own handler which calls the saved handler.
494 SrcMgr.setDiagHandler(DiagHandler, this);
495 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
497 // Initialize the platform / file format parser.
498 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
499 case MCObjectFileInfo::IsCOFF:
500 PlatformParser = createCOFFAsmParser();
501 PlatformParser->Initialize(*this);
503 case MCObjectFileInfo::IsMachO:
504 PlatformParser = createDarwinAsmParser();
505 PlatformParser->Initialize(*this);
508 case MCObjectFileInfo::IsELF:
509 PlatformParser = createELFAsmParser();
510 PlatformParser->Initialize(*this);
514 initializeDirectiveKindMap();
517 AsmParser::~AsmParser() {
518 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
520 // Destroy any macros.
521 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
524 delete it->getValue();
526 delete PlatformParser;
529 void AsmParser::printMacroInstantiations() {
530 // Print the active macro instantiation stack.
531 for (std::vector<MacroInstantiation *>::const_reverse_iterator
532 it = ActiveMacros.rbegin(),
533 ie = ActiveMacros.rend();
535 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
536 "while in macro instantiation");
539 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
540 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
541 printMacroInstantiations();
544 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
545 if (FatalAssemblerWarnings)
546 return Error(L, Msg, Ranges);
547 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
548 printMacroInstantiations();
552 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
554 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
555 printMacroInstantiations();
559 bool AsmParser::enterIncludeFile(const std::string &Filename) {
560 std::string IncludedFile;
561 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
567 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
572 /// Process the specified .incbin file by searching for it in the include paths
573 /// then just emitting the byte contents of the file to the streamer. This
574 /// returns true on failure.
575 bool AsmParser::processIncbinFile(const std::string &Filename) {
576 std::string IncludedFile;
577 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
581 // Pick up the bytes from the file and emit them.
582 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
586 void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
587 if (InBuffer != -1) {
588 CurBuffer = InBuffer;
590 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
592 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
595 const AsmToken &AsmParser::Lex() {
596 const AsmToken *tok = &Lexer.Lex();
598 if (tok->is(AsmToken::Eof)) {
599 // If this is the end of an included file, pop the parent file off the
601 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
602 if (ParentIncludeLoc != SMLoc()) {
603 jumpToLoc(ParentIncludeLoc);
608 if (tok->is(AsmToken::Error))
609 Error(Lexer.getErrLoc(), Lexer.getErr());
614 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
615 // Create the initial section, if requested.
616 if (!NoInitialTextSection)
623 AsmCond StartingCondState = TheCondState;
625 // If we are generating dwarf for assembly source files save the initial text
626 // section and generate a .file directive.
627 if (getContext().getGenDwarfForAssembly()) {
628 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
629 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
630 getStreamer().EmitLabel(SectionStartSym);
631 getContext().setGenDwarfSectionStartSym(SectionStartSym);
632 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
634 getContext().getMainFileName());
637 // While we have input, parse each statement.
638 while (Lexer.isNot(AsmToken::Eof)) {
639 ParseStatementInfo Info;
640 if (!parseStatement(Info))
643 // We had an error, validate that one was emitted and recover by skipping to
645 assert(HadError && "Parse statement returned an error, but none emitted!");
646 eatToEndOfStatement();
649 if (TheCondState.TheCond != StartingCondState.TheCond ||
650 TheCondState.Ignore != StartingCondState.Ignore)
651 return TokError("unmatched .ifs or .elses");
653 // Check to see there are no empty DwarfFile slots.
654 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
655 getContext().getMCDwarfFiles();
656 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
657 if (!MCDwarfFiles[i])
658 TokError("unassigned file number: " + Twine(i) + " for .file directives");
661 // Check to see that all assembler local symbols were actually defined.
662 // Targets that don't do subsections via symbols may not want this, though,
663 // so conservatively exclude them. Only do this if we're finalizing, though,
664 // as otherwise we won't necessarilly have seen everything yet.
665 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
666 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
667 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
670 MCSymbol *Sym = i->getValue();
671 // Variable symbols may not be marked as defined, so check those
672 // explicitly. If we know it's a variable, we have a definition for
673 // the purposes of this check.
674 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
675 // FIXME: We would really like to refer back to where the symbol was
676 // first referenced for a source location. We need to add something
677 // to track that. Currently, we just point to the end of the file.
679 getLexer().getLoc(), SourceMgr::DK_Error,
680 "assembler local symbol '" + Sym->getName() + "' not defined");
684 // Finalize the output stream if there are no errors and if the client wants
686 if (!HadError && !NoFinalize)
692 void AsmParser::checkForValidSection() {
693 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
694 TokError("expected section directive before assembly directive");
699 /// \brief Throw away the rest of the line for testing purposes.
700 void AsmParser::eatToEndOfStatement() {
701 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
705 if (Lexer.is(AsmToken::EndOfStatement))
709 StringRef AsmParser::parseStringToEndOfStatement() {
710 const char *Start = getTok().getLoc().getPointer();
712 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
715 const char *End = getTok().getLoc().getPointer();
716 return StringRef(Start, End - Start);
719 StringRef AsmParser::parseStringToComma() {
720 const char *Start = getTok().getLoc().getPointer();
722 while (Lexer.isNot(AsmToken::EndOfStatement) &&
723 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
726 const char *End = getTok().getLoc().getPointer();
727 return StringRef(Start, End - Start);
730 /// \brief Parse a paren expression and return it.
731 /// NOTE: This assumes the leading '(' has already been consumed.
733 /// parenexpr ::= expr)
735 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
736 if (parseExpression(Res))
738 if (Lexer.isNot(AsmToken::RParen))
739 return TokError("expected ')' in parentheses expression");
740 EndLoc = Lexer.getTok().getEndLoc();
745 /// \brief Parse a bracket expression and return it.
746 /// NOTE: This assumes the leading '[' has already been consumed.
748 /// bracketexpr ::= expr]
750 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
751 if (parseExpression(Res))
753 if (Lexer.isNot(AsmToken::RBrac))
754 return TokError("expected ']' in brackets expression");
755 EndLoc = Lexer.getTok().getEndLoc();
760 /// \brief Parse a primary expression and return it.
761 /// primaryexpr ::= (parenexpr
762 /// primaryexpr ::= symbol
763 /// primaryexpr ::= number
764 /// primaryexpr ::= '.'
765 /// primaryexpr ::= ~,+,- primaryexpr
766 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
767 SMLoc FirstTokenLoc = getLexer().getLoc();
768 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
769 switch (FirstTokenKind) {
771 return TokError("unknown token in expression");
772 // If we have an error assume that we've already handled it.
773 case AsmToken::Error:
775 case AsmToken::Exclaim:
776 Lex(); // Eat the operator.
777 if (parsePrimaryExpr(Res, EndLoc))
779 Res = MCUnaryExpr::CreateLNot(Res, getContext());
781 case AsmToken::Dollar:
783 case AsmToken::String:
784 case AsmToken::Identifier: {
785 StringRef Identifier;
786 if (parseIdentifier(Identifier)) {
787 if (FirstTokenKind == AsmToken::Dollar) {
788 if (Lexer.getMAI().getDollarIsPC()) {
789 // This is a '$' reference, which references the current PC. Emit a
790 // temporary label to the streamer and refer to it.
791 MCSymbol *Sym = Ctx.CreateTempSymbol();
793 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
795 EndLoc = FirstTokenLoc;
798 return Error(FirstTokenLoc, "invalid token in expression");
802 // Parse symbol variant
803 std::pair<StringRef, StringRef> Split;
804 if (!MAI.useParensForSymbolVariant()) {
805 Split = Identifier.split('@');
806 } else if (Lexer.is(AsmToken::LParen)) {
807 Lexer.Lex(); // eat (
809 parseIdentifier(VName);
810 if (Lexer.isNot(AsmToken::RParen)) {
811 return Error(Lexer.getTok().getLoc(),
812 "unexpected token in variant, expected ')'");
814 Lexer.Lex(); // eat )
815 Split = std::make_pair(Identifier, VName);
818 EndLoc = SMLoc::getFromPointer(Identifier.end());
820 // This is a symbol reference.
821 StringRef SymbolName = Identifier;
822 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
824 // Lookup the symbol variant if used.
825 if (Split.second.size()) {
826 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
827 if (Variant != MCSymbolRefExpr::VK_Invalid) {
828 SymbolName = Split.first;
829 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
830 Variant = MCSymbolRefExpr::VK_None;
832 Variant = MCSymbolRefExpr::VK_None;
833 return Error(SMLoc::getFromPointer(Split.second.begin()),
834 "invalid variant '" + Split.second + "'");
838 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
840 // If this is an absolute variable reference, substitute it now to preserve
841 // semantics in the face of reassignment.
842 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
844 return Error(EndLoc, "unexpected modifier on variable reference");
846 Res = Sym->getVariableValue();
850 // Otherwise create a symbol ref.
851 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
854 case AsmToken::BigNum:
855 return TokError("literal value out of range for directive");
856 case AsmToken::Integer: {
857 SMLoc Loc = getTok().getLoc();
858 int64_t IntVal = getTok().getIntVal();
859 Res = MCConstantExpr::Create(IntVal, getContext());
860 EndLoc = Lexer.getTok().getEndLoc();
862 // Look for 'b' or 'f' following an Integer as a directional label
863 if (Lexer.getKind() == AsmToken::Identifier) {
864 StringRef IDVal = getTok().getString();
865 // Lookup the symbol variant if used.
866 std::pair<StringRef, StringRef> Split = IDVal.split('@');
867 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
868 if (Split.first.size() != IDVal.size()) {
869 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
870 if (Variant == MCSymbolRefExpr::VK_Invalid) {
871 Variant = MCSymbolRefExpr::VK_None;
872 return TokError("invalid variant '" + Split.second + "'");
876 if (IDVal == "f" || IDVal == "b") {
878 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "f" ? 1 : 0);
879 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
880 if (IDVal == "b" && Sym->isUndefined())
881 return Error(Loc, "invalid reference to undefined symbol");
882 EndLoc = Lexer.getTok().getEndLoc();
883 Lex(); // Eat identifier.
888 case AsmToken::Real: {
889 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
890 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
891 Res = MCConstantExpr::Create(IntVal, getContext());
892 EndLoc = Lexer.getTok().getEndLoc();
896 case AsmToken::Dot: {
897 // This is a '.' reference, which references the current PC. Emit a
898 // temporary label to the streamer and refer to it.
899 MCSymbol *Sym = Ctx.CreateTempSymbol();
901 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
902 EndLoc = Lexer.getTok().getEndLoc();
903 Lex(); // Eat identifier.
906 case AsmToken::LParen:
907 Lex(); // Eat the '('.
908 return parseParenExpr(Res, EndLoc);
909 case AsmToken::LBrac:
910 if (!PlatformParser->HasBracketExpressions())
911 return TokError("brackets expression not supported on this target");
912 Lex(); // Eat the '['.
913 return parseBracketExpr(Res, EndLoc);
914 case AsmToken::Minus:
915 Lex(); // Eat the operator.
916 if (parsePrimaryExpr(Res, EndLoc))
918 Res = MCUnaryExpr::CreateMinus(Res, getContext());
921 Lex(); // Eat the operator.
922 if (parsePrimaryExpr(Res, EndLoc))
924 Res = MCUnaryExpr::CreatePlus(Res, getContext());
926 case AsmToken::Tilde:
927 Lex(); // Eat the operator.
928 if (parsePrimaryExpr(Res, EndLoc))
930 Res = MCUnaryExpr::CreateNot(Res, getContext());
935 bool AsmParser::parseExpression(const MCExpr *&Res) {
937 return parseExpression(Res, EndLoc);
941 AsmParser::applyModifierToExpr(const MCExpr *E,
942 MCSymbolRefExpr::VariantKind Variant) {
943 // Ask the target implementation about this expression first.
944 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
947 // Recurse over the given expression, rebuilding it to apply the given variant
948 // if there is exactly one symbol.
949 switch (E->getKind()) {
951 case MCExpr::Constant:
954 case MCExpr::SymbolRef: {
955 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
957 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
958 TokError("invalid variant on expression '" + getTok().getIdentifier() +
959 "' (already modified)");
963 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
966 case MCExpr::Unary: {
967 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
968 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
971 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
974 case MCExpr::Binary: {
975 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
976 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
977 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
987 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
991 llvm_unreachable("Invalid expression kind!");
994 /// \brief Parse an expression and return it.
996 /// expr ::= expr &&,|| expr -> lowest.
997 /// expr ::= expr |,^,&,! expr
998 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
999 /// expr ::= expr <<,>> expr
1000 /// expr ::= expr +,- expr
1001 /// expr ::= expr *,/,% expr -> highest.
1002 /// expr ::= primaryexpr
1004 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1005 // Parse the expression.
1007 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1010 // As a special case, we support 'a op b @ modifier' by rewriting the
1011 // expression to include the modifier. This is inefficient, but in general we
1012 // expect users to use 'a@modifier op b'.
1013 if (Lexer.getKind() == AsmToken::At) {
1016 if (Lexer.isNot(AsmToken::Identifier))
1017 return TokError("unexpected symbol modifier following '@'");
1019 MCSymbolRefExpr::VariantKind Variant =
1020 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1021 if (Variant == MCSymbolRefExpr::VK_Invalid)
1022 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1024 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1026 return TokError("invalid modifier '" + getTok().getIdentifier() +
1027 "' (no symbols present)");
1034 // Try to constant fold it up front, if possible.
1036 if (Res->EvaluateAsAbsolute(Value))
1037 Res = MCConstantExpr::Create(Value, getContext());
1042 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1044 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1047 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1050 SMLoc StartLoc = Lexer.getLoc();
1051 if (parseExpression(Expr))
1054 if (!Expr->EvaluateAsAbsolute(Res))
1055 return Error(StartLoc, "expected absolute expression");
1060 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1061 MCBinaryExpr::Opcode &Kind) {
1064 return 0; // not a binop.
1066 // Lowest Precedence: &&, ||
1067 case AsmToken::AmpAmp:
1068 Kind = MCBinaryExpr::LAnd;
1070 case AsmToken::PipePipe:
1071 Kind = MCBinaryExpr::LOr;
1074 // Low Precedence: |, &, ^
1076 // FIXME: gas seems to support '!' as an infix operator?
1077 case AsmToken::Pipe:
1078 Kind = MCBinaryExpr::Or;
1080 case AsmToken::Caret:
1081 Kind = MCBinaryExpr::Xor;
1084 Kind = MCBinaryExpr::And;
1087 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1088 case AsmToken::EqualEqual:
1089 Kind = MCBinaryExpr::EQ;
1091 case AsmToken::ExclaimEqual:
1092 case AsmToken::LessGreater:
1093 Kind = MCBinaryExpr::NE;
1095 case AsmToken::Less:
1096 Kind = MCBinaryExpr::LT;
1098 case AsmToken::LessEqual:
1099 Kind = MCBinaryExpr::LTE;
1101 case AsmToken::Greater:
1102 Kind = MCBinaryExpr::GT;
1104 case AsmToken::GreaterEqual:
1105 Kind = MCBinaryExpr::GTE;
1108 // Intermediate Precedence: <<, >>
1109 case AsmToken::LessLess:
1110 Kind = MCBinaryExpr::Shl;
1112 case AsmToken::GreaterGreater:
1113 Kind = MCBinaryExpr::Shr;
1116 // High Intermediate Precedence: +, -
1117 case AsmToken::Plus:
1118 Kind = MCBinaryExpr::Add;
1120 case AsmToken::Minus:
1121 Kind = MCBinaryExpr::Sub;
1124 // Highest Precedence: *, /, %
1125 case AsmToken::Star:
1126 Kind = MCBinaryExpr::Mul;
1128 case AsmToken::Slash:
1129 Kind = MCBinaryExpr::Div;
1131 case AsmToken::Percent:
1132 Kind = MCBinaryExpr::Mod;
1137 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1138 /// Res contains the LHS of the expression on input.
1139 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1142 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1143 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1145 // If the next token is lower precedence than we are allowed to eat, return
1146 // successfully with what we ate already.
1147 if (TokPrec < Precedence)
1152 // Eat the next primary expression.
1154 if (parsePrimaryExpr(RHS, EndLoc))
1157 // If BinOp binds less tightly with RHS than the operator after RHS, let
1158 // the pending operator take RHS as its LHS.
1159 MCBinaryExpr::Opcode Dummy;
1160 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1161 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1164 // Merge LHS and RHS according to operator.
1165 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1170 /// ::= EndOfStatement
1171 /// ::= Label* Directive ...Operands... EndOfStatement
1172 /// ::= Label* Identifier OperandList* EndOfStatement
1173 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1174 if (Lexer.is(AsmToken::EndOfStatement)) {
1180 // Statements always start with an identifier or are a full line comment.
1181 AsmToken ID = getTok();
1182 SMLoc IDLoc = ID.getLoc();
1184 int64_t LocalLabelVal = -1;
1185 // A full line comment is a '#' as the first token.
1186 if (Lexer.is(AsmToken::Hash))
1187 return parseCppHashLineFilenameComment(IDLoc);
1189 // Allow an integer followed by a ':' as a directional local label.
1190 if (Lexer.is(AsmToken::Integer)) {
1191 LocalLabelVal = getTok().getIntVal();
1192 if (LocalLabelVal < 0) {
1193 if (!TheCondState.Ignore)
1194 return TokError("unexpected token at start of statement");
1197 IDVal = getTok().getString();
1198 Lex(); // Consume the integer token to be used as an identifier token.
1199 if (Lexer.getKind() != AsmToken::Colon) {
1200 if (!TheCondState.Ignore)
1201 return TokError("unexpected token at start of statement");
1204 } else if (Lexer.is(AsmToken::Dot)) {
1205 // Treat '.' as a valid identifier in this context.
1208 } else if (parseIdentifier(IDVal)) {
1209 if (!TheCondState.Ignore)
1210 return TokError("unexpected token at start of statement");
1214 // Handle conditional assembly here before checking for skipping. We
1215 // have to do this so that .endif isn't skipped in a ".if 0" block for
1217 StringMap<DirectiveKind>::const_iterator DirKindIt =
1218 DirectiveKindMap.find(IDVal);
1219 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1221 : DirKindIt->getValue();
1226 return parseDirectiveIf(IDLoc);
1228 return parseDirectiveIfb(IDLoc, true);
1230 return parseDirectiveIfb(IDLoc, false);
1232 return parseDirectiveIfc(IDLoc, true);
1234 return parseDirectiveIfc(IDLoc, false);
1236 return parseDirectiveIfdef(IDLoc, true);
1239 return parseDirectiveIfdef(IDLoc, false);
1241 return parseDirectiveElseIf(IDLoc);
1243 return parseDirectiveElse(IDLoc);
1245 return parseDirectiveEndIf(IDLoc);
1248 // Ignore the statement if in the middle of inactive conditional
1250 if (TheCondState.Ignore) {
1251 eatToEndOfStatement();
1255 // FIXME: Recurse on local labels?
1257 // See what kind of statement we have.
1258 switch (Lexer.getKind()) {
1259 case AsmToken::Colon: {
1260 checkForValidSection();
1262 // identifier ':' -> Label.
1265 // Diagnose attempt to use '.' as a label.
1267 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1269 // Diagnose attempt to use a variable as a label.
1271 // FIXME: Diagnostics. Note the location of the definition as a label.
1272 // FIXME: This doesn't diagnose assignment to a symbol which has been
1273 // implicitly marked as external.
1275 if (LocalLabelVal == -1)
1276 Sym = getContext().GetOrCreateSymbol(IDVal);
1278 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1279 if (!Sym->isUndefined() || Sym->isVariable())
1280 return Error(IDLoc, "invalid symbol redefinition");
1283 if (!ParsingInlineAsm)
1286 // If we are generating dwarf for assembly source files then gather the
1287 // info to make a dwarf label entry for this label if needed.
1288 if (getContext().getGenDwarfForAssembly())
1289 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1292 getTargetParser().onLabelParsed(Sym);
1294 // Consume any end of statement token, if present, to avoid spurious
1295 // AddBlankLine calls().
1296 if (Lexer.is(AsmToken::EndOfStatement)) {
1298 if (Lexer.is(AsmToken::Eof))
1305 case AsmToken::Equal:
1306 // identifier '=' ... -> assignment statement
1309 return parseAssignment(IDVal, true);
1311 default: // Normal instruction or directive.
1315 // If macros are enabled, check to see if this is a macro instantiation.
1316 if (areMacrosEnabled())
1317 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1318 return handleMacroEntry(M, IDLoc);
1321 // Otherwise, we have a normal instruction or directive.
1323 // Directives start with "."
1324 if (IDVal[0] == '.' && IDVal != ".") {
1325 // There are several entities interested in parsing directives:
1327 // 1. The target-specific assembly parser. Some directives are target
1328 // specific or may potentially behave differently on certain targets.
1329 // 2. Asm parser extensions. For example, platform-specific parsers
1330 // (like the ELF parser) register themselves as extensions.
1331 // 3. The generic directive parser implemented by this class. These are
1332 // all the directives that behave in a target and platform independent
1333 // manner, or at least have a default behavior that's shared between
1334 // all targets and platforms.
1336 // First query the target-specific parser. It will return 'true' if it
1337 // isn't interested in this directive.
1338 if (!getTargetParser().ParseDirective(ID))
1341 // Next, check the extension directive map to see if any extension has
1342 // registered itself to parse this directive.
1343 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1344 ExtensionDirectiveMap.lookup(IDVal);
1346 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1348 // Finally, if no one else is interested in this directive, it must be
1349 // generic and familiar to this class.
1355 return parseDirectiveSet(IDVal, true);
1357 return parseDirectiveSet(IDVal, false);
1359 return parseDirectiveAscii(IDVal, false);
1362 return parseDirectiveAscii(IDVal, true);
1364 return parseDirectiveValue(1);
1368 return parseDirectiveValue(2);
1372 return parseDirectiveValue(4);
1375 return parseDirectiveValue(8);
1377 return parseDirectiveOctaValue();
1380 return parseDirectiveRealValue(APFloat::IEEEsingle);
1382 return parseDirectiveRealValue(APFloat::IEEEdouble);
1384 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1385 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1388 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1389 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1392 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1394 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1396 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1398 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1400 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1402 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1404 return parseDirectiveOrg();
1406 return parseDirectiveFill();
1408 return parseDirectiveZero();
1410 eatToEndOfStatement(); // .extern is the default, ignore it.
1414 return parseDirectiveSymbolAttribute(MCSA_Global);
1415 case DK_LAZY_REFERENCE:
1416 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1417 case DK_NO_DEAD_STRIP:
1418 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1419 case DK_SYMBOL_RESOLVER:
1420 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1421 case DK_PRIVATE_EXTERN:
1422 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1424 return parseDirectiveSymbolAttribute(MCSA_Reference);
1425 case DK_WEAK_DEFINITION:
1426 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1427 case DK_WEAK_REFERENCE:
1428 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1429 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1430 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1433 return parseDirectiveComm(/*IsLocal=*/false);
1435 return parseDirectiveComm(/*IsLocal=*/true);
1437 return parseDirectiveAbort();
1439 return parseDirectiveInclude();
1441 return parseDirectiveIncbin();
1444 return TokError(Twine(IDVal) + " not supported yet");
1446 return parseDirectiveRept(IDLoc, IDVal);
1448 return parseDirectiveIrp(IDLoc);
1450 return parseDirectiveIrpc(IDLoc);
1452 return parseDirectiveEndr(IDLoc);
1453 case DK_BUNDLE_ALIGN_MODE:
1454 return parseDirectiveBundleAlignMode();
1455 case DK_BUNDLE_LOCK:
1456 return parseDirectiveBundleLock();
1457 case DK_BUNDLE_UNLOCK:
1458 return parseDirectiveBundleUnlock();
1460 return parseDirectiveLEB128(true);
1462 return parseDirectiveLEB128(false);
1465 return parseDirectiveSpace(IDVal);
1467 return parseDirectiveFile(IDLoc);
1469 return parseDirectiveLine();
1471 return parseDirectiveLoc();
1473 return parseDirectiveStabs();
1474 case DK_CFI_SECTIONS:
1475 return parseDirectiveCFISections();
1476 case DK_CFI_STARTPROC:
1477 return parseDirectiveCFIStartProc();
1478 case DK_CFI_ENDPROC:
1479 return parseDirectiveCFIEndProc();
1480 case DK_CFI_DEF_CFA:
1481 return parseDirectiveCFIDefCfa(IDLoc);
1482 case DK_CFI_DEF_CFA_OFFSET:
1483 return parseDirectiveCFIDefCfaOffset();
1484 case DK_CFI_ADJUST_CFA_OFFSET:
1485 return parseDirectiveCFIAdjustCfaOffset();
1486 case DK_CFI_DEF_CFA_REGISTER:
1487 return parseDirectiveCFIDefCfaRegister(IDLoc);
1489 return parseDirectiveCFIOffset(IDLoc);
1490 case DK_CFI_REL_OFFSET:
1491 return parseDirectiveCFIRelOffset(IDLoc);
1492 case DK_CFI_PERSONALITY:
1493 return parseDirectiveCFIPersonalityOrLsda(true);
1495 return parseDirectiveCFIPersonalityOrLsda(false);
1496 case DK_CFI_REMEMBER_STATE:
1497 return parseDirectiveCFIRememberState();
1498 case DK_CFI_RESTORE_STATE:
1499 return parseDirectiveCFIRestoreState();
1500 case DK_CFI_SAME_VALUE:
1501 return parseDirectiveCFISameValue(IDLoc);
1502 case DK_CFI_RESTORE:
1503 return parseDirectiveCFIRestore(IDLoc);
1505 return parseDirectiveCFIEscape();
1506 case DK_CFI_SIGNAL_FRAME:
1507 return parseDirectiveCFISignalFrame();
1508 case DK_CFI_UNDEFINED:
1509 return parseDirectiveCFIUndefined(IDLoc);
1510 case DK_CFI_REGISTER:
1511 return parseDirectiveCFIRegister(IDLoc);
1512 case DK_CFI_WINDOW_SAVE:
1513 return parseDirectiveCFIWindowSave();
1516 return parseDirectiveMacrosOnOff(IDVal);
1518 return parseDirectiveMacro(IDLoc);
1521 return parseDirectiveEndMacro(IDVal);
1523 return parseDirectivePurgeMacro(IDLoc);
1525 return parseDirectiveEnd(IDLoc);
1528 return Error(IDLoc, "unknown directive");
1531 // __asm _emit or __asm __emit
1532 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1533 IDVal == "_EMIT" || IDVal == "__EMIT"))
1534 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1537 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1538 return parseDirectiveMSAlign(IDLoc, Info);
1540 checkForValidSection();
1542 // Canonicalize the opcode to lower case.
1543 std::string OpcodeStr = IDVal.lower();
1544 ParseInstructionInfo IInfo(Info.AsmRewrites);
1545 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1546 Info.ParsedOperands);
1547 Info.ParseError = HadError;
1549 // Dump the parsed representation, if requested.
1550 if (getShowParsedOperands()) {
1551 SmallString<256> Str;
1552 raw_svector_ostream OS(Str);
1553 OS << "parsed instruction: [";
1554 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1557 Info.ParsedOperands[i]->print(OS);
1561 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1564 // If we are generating dwarf for assembly source files and the current
1565 // section is the initial text section then generate a .loc directive for
1567 if (!HadError && getContext().getGenDwarfForAssembly() &&
1568 getContext().getGenDwarfSection() ==
1569 getStreamer().getCurrentSection().first) {
1571 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1573 // If we previously parsed a cpp hash file line comment then make sure the
1574 // current Dwarf File is for the CppHashFilename if not then emit the
1575 // Dwarf File table for it and adjust the line number for the .loc.
1576 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
1577 getContext().getMCDwarfFiles();
1578 if (CppHashFilename.size() != 0) {
1579 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1581 getStreamer().EmitDwarfFileDirective(
1582 getContext().nextGenDwarfFileNumber(), StringRef(),
1585 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1586 // cache with the different Loc from the call above we save the last
1587 // info we queried here with SrcMgr.FindLineNumber().
1588 unsigned CppHashLocLineNo;
1589 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1590 CppHashLocLineNo = LastQueryLine;
1592 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1593 LastQueryLine = CppHashLocLineNo;
1594 LastQueryIDLoc = CppHashLoc;
1595 LastQueryBuffer = CppHashBuf;
1597 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1600 getStreamer().EmitDwarfLocDirective(
1601 getContext().getGenDwarfFileNumber(), Line, 0,
1602 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1606 // If parsing succeeded, match the instruction.
1609 HadError = getTargetParser().MatchAndEmitInstruction(
1610 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
1614 // Don't skip the rest of the line, the instruction parser is responsible for
1619 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1620 /// since they may not be able to be tokenized to get to the end of line token.
1621 void AsmParser::eatToEndOfLine() {
1622 if (!Lexer.is(AsmToken::EndOfStatement))
1623 Lexer.LexUntilEndOfLine();
1628 /// parseCppHashLineFilenameComment as this:
1629 /// ::= # number "filename"
1630 /// or just as a full line comment if it doesn't have a number and a string.
1631 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1632 Lex(); // Eat the hash token.
1634 if (getLexer().isNot(AsmToken::Integer)) {
1635 // Consume the line since in cases it is not a well-formed line directive,
1636 // as if were simply a full line comment.
1641 int64_t LineNumber = getTok().getIntVal();
1644 if (getLexer().isNot(AsmToken::String)) {
1649 StringRef Filename = getTok().getString();
1650 // Get rid of the enclosing quotes.
1651 Filename = Filename.substr(1, Filename.size() - 2);
1653 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1655 CppHashFilename = Filename;
1656 CppHashLineNumber = LineNumber;
1657 CppHashBuf = CurBuffer;
1659 // Ignore any trailing characters, they're just comment.
1664 /// \brief will use the last parsed cpp hash line filename comment
1665 /// for the Filename and LineNo if any in the diagnostic.
1666 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1667 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1668 raw_ostream &OS = errs();
1670 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1671 const SMLoc &DiagLoc = Diag.getLoc();
1672 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1673 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1675 // Like SourceMgr::printMessage() we need to print the include stack if any
1676 // before printing the message.
1677 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1678 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1679 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1680 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1683 // If we have not parsed a cpp hash line filename comment or the source
1684 // manager changed or buffer changed (like in a nested include) then just
1685 // print the normal diagnostic using its Filename and LineNo.
1686 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1687 DiagBuf != CppHashBuf) {
1688 if (Parser->SavedDiagHandler)
1689 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1695 // Use the CppHashFilename and calculate a line number based on the
1696 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1698 const std::string &Filename = Parser->CppHashFilename;
1700 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1701 int CppHashLocLineNo =
1702 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1704 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1706 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1707 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1708 Diag.getLineContents(), Diag.getRanges());
1710 if (Parser->SavedDiagHandler)
1711 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1713 NewDiag.print(0, OS);
1716 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1717 // difference being that that function accepts '@' as part of identifiers and
1718 // we can't do that. AsmLexer.cpp should probably be changed to handle
1719 // '@' as a special case when needed.
1720 static bool isIdentifierChar(char c) {
1721 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1725 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1726 const MCAsmMacroParameters &Parameters,
1727 const MCAsmMacroArguments &A, const SMLoc &L) {
1728 unsigned NParameters = Parameters.size();
1729 if (NParameters != 0 && NParameters != A.size())
1730 return Error(L, "Wrong number of arguments");
1732 // A macro without parameters is handled differently on Darwin:
1733 // gas accepts no arguments and does no substitutions
1734 while (!Body.empty()) {
1735 // Scan for the next substitution.
1736 std::size_t End = Body.size(), Pos = 0;
1737 for (; Pos != End; ++Pos) {
1738 // Check for a substitution or escape.
1740 // This macro has no parameters, look for $0, $1, etc.
1741 if (Body[Pos] != '$' || Pos + 1 == End)
1744 char Next = Body[Pos + 1];
1745 if (Next == '$' || Next == 'n' ||
1746 isdigit(static_cast<unsigned char>(Next)))
1749 // This macro has parameters, look for \foo, \bar, etc.
1750 if (Body[Pos] == '\\' && Pos + 1 != End)
1756 OS << Body.slice(0, Pos);
1758 // Check if we reached the end.
1763 switch (Body[Pos + 1]) {
1769 // $n => number of arguments
1774 // $[0-9] => argument
1776 // Missing arguments are ignored.
1777 unsigned Index = Body[Pos + 1] - '0';
1778 if (Index >= A.size())
1781 // Otherwise substitute with the token values, with spaces eliminated.
1782 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1783 ie = A[Index].end();
1785 OS << it->getString();
1791 unsigned I = Pos + 1;
1792 while (isIdentifierChar(Body[I]) && I + 1 != End)
1795 const char *Begin = Body.data() + Pos + 1;
1796 StringRef Argument(Begin, I - (Pos + 1));
1798 for (; Index < NParameters; ++Index)
1799 if (Parameters[Index].first == Argument)
1802 if (Index == NParameters) {
1803 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1806 OS << '\\' << Argument;
1810 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1811 ie = A[Index].end();
1813 if (it->getKind() == AsmToken::String)
1814 OS << it->getStringContents();
1816 OS << it->getString();
1818 Pos += 1 + Argument.size();
1821 // Update the scan point.
1822 Body = Body.substr(Pos);
1828 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1829 SMLoc EL, MemoryBuffer *I)
1830 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1833 static bool isOperator(AsmToken::TokenKind kind) {
1837 case AsmToken::Plus:
1838 case AsmToken::Minus:
1839 case AsmToken::Tilde:
1840 case AsmToken::Slash:
1841 case AsmToken::Star:
1843 case AsmToken::Equal:
1844 case AsmToken::EqualEqual:
1845 case AsmToken::Pipe:
1846 case AsmToken::PipePipe:
1847 case AsmToken::Caret:
1849 case AsmToken::AmpAmp:
1850 case AsmToken::Exclaim:
1851 case AsmToken::ExclaimEqual:
1852 case AsmToken::Percent:
1853 case AsmToken::Less:
1854 case AsmToken::LessEqual:
1855 case AsmToken::LessLess:
1856 case AsmToken::LessGreater:
1857 case AsmToken::Greater:
1858 case AsmToken::GreaterEqual:
1859 case AsmToken::GreaterGreater:
1865 class AsmLexerSkipSpaceRAII {
1867 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1868 Lexer.setSkipSpace(SkipSpace);
1871 ~AsmLexerSkipSpaceRAII() {
1872 Lexer.setSkipSpace(true);
1880 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA) {
1881 unsigned ParenLevel = 0;
1882 unsigned AddTokens = 0;
1884 // Darwin doesn't use spaces to delmit arguments.
1885 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1888 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1889 return TokError("unexpected token in macro instantiation");
1891 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1894 if (Lexer.is(AsmToken::Space)) {
1895 Lex(); // Eat spaces
1897 // Spaces can delimit parameters, but could also be part an expression.
1898 // If the token after a space is an operator, add the token and the next
1899 // one into this argument
1901 if (isOperator(Lexer.getKind())) {
1902 // Check to see whether the token is used as an operator,
1903 // or part of an identifier
1904 const char *NextChar = getTok().getEndLoc().getPointer();
1905 if (*NextChar == ' ')
1909 if (!AddTokens && ParenLevel == 0) {
1915 // handleMacroEntry relies on not advancing the lexer here
1916 // to be able to fill in the remaining default parameter values
1917 if (Lexer.is(AsmToken::EndOfStatement))
1920 // Adjust the current parentheses level.
1921 if (Lexer.is(AsmToken::LParen))
1923 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1926 // Append the token to the current argument list.
1927 MA.push_back(getTok());
1933 if (ParenLevel != 0)
1934 return TokError("unbalanced parentheses in macro argument");
1938 // Parse the macro instantiation arguments.
1939 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1940 MCAsmMacroArguments &A) {
1941 const unsigned NParameters = M ? M->Parameters.size() : 0;
1943 // Parse two kinds of macro invocations:
1944 // - macros defined without any parameters accept an arbitrary number of them
1945 // - macros defined with parameters accept at most that many of them
1946 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1948 MCAsmMacroArgument MA;
1950 if (parseMacroArgument(MA))
1953 if (!MA.empty() || (!NParameters && !Lexer.is(AsmToken::EndOfStatement)))
1955 else if (NParameters) {
1956 if (!M->Parameters[Parameter].second.empty())
1957 A.push_back(M->Parameters[Parameter].second);
1962 // At the end of the statement, fill in remaining arguments that have
1963 // default values. If there aren't any, then the next argument is
1964 // required but missing
1965 if (Lexer.is(AsmToken::EndOfStatement)) {
1966 if (NParameters && Parameter < NParameters - 1) {
1972 if (Lexer.is(AsmToken::Comma))
1975 return TokError("Too many arguments");
1978 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
1979 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
1980 return (I == MacroMap.end()) ? NULL : I->getValue();
1983 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
1984 MacroMap[Name] = new MCAsmMacro(Macro);
1987 void AsmParser::undefineMacro(StringRef Name) {
1988 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
1989 if (I != MacroMap.end()) {
1990 delete I->getValue();
1995 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
1996 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1997 // this, although we should protect against infinite loops.
1998 if (ActiveMacros.size() == 20)
1999 return TokError("macros cannot be nested more than 20 levels deep");
2001 MCAsmMacroArguments A;
2002 if (parseMacroArguments(M, A))
2005 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2006 // to hold the macro body with substitutions.
2007 SmallString<256> Buf;
2008 StringRef Body = M->Body;
2009 raw_svector_ostream OS(Buf);
2011 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2014 // We include the .endmacro in the buffer as our cue to exit the macro
2016 OS << ".endmacro\n";
2018 MemoryBuffer *Instantiation =
2019 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2021 // Create the macro instantiation object and add to the current macro
2022 // instantiation stack.
2023 MacroInstantiation *MI = new MacroInstantiation(
2024 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
2025 ActiveMacros.push_back(MI);
2027 // Jump to the macro instantiation and prime the lexer.
2028 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2029 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2035 void AsmParser::handleMacroExit() {
2036 // Jump to the EndOfStatement we should return to, and consume it.
2037 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2040 // Pop the instantiation entry.
2041 delete ActiveMacros.back();
2042 ActiveMacros.pop_back();
2045 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2046 switch (Value->getKind()) {
2047 case MCExpr::Binary: {
2048 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2049 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2051 case MCExpr::Target:
2052 case MCExpr::Constant:
2054 case MCExpr::SymbolRef: {
2056 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2058 return isUsedIn(Sym, S.getVariableValue());
2062 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2065 llvm_unreachable("Unknown expr kind!");
2068 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2070 // FIXME: Use better location, we should use proper tokens.
2071 SMLoc EqualLoc = Lexer.getLoc();
2073 const MCExpr *Value;
2074 if (parseExpression(Value))
2077 // Note: we don't count b as used in "a = b". This is to allow
2081 if (Lexer.isNot(AsmToken::EndOfStatement))
2082 return TokError("unexpected token in assignment");
2084 // Error on assignment to '.'.
2086 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2087 "(use '.space' or '.org').)"));
2090 // Eat the end of statement marker.
2093 // Validate that the LHS is allowed to be a variable (either it has not been
2094 // used as a symbol, or it is an absolute symbol).
2095 MCSymbol *Sym = getContext().LookupSymbol(Name);
2097 // Diagnose assignment to a label.
2099 // FIXME: Diagnostics. Note the location of the definition as a label.
2100 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2101 if (isUsedIn(Sym, Value))
2102 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2103 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2104 ; // Allow redefinitions of undefined symbols only used in directives.
2105 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2106 ; // Allow redefinitions of variables that haven't yet been used.
2107 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2108 return Error(EqualLoc, "redefinition of '" + Name + "'");
2109 else if (!Sym->isVariable())
2110 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2111 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2112 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2115 // Don't count these checks as uses.
2116 Sym->setUsed(false);
2118 Sym = getContext().GetOrCreateSymbol(Name);
2120 // FIXME: Handle '.'.
2122 // Do the assignment.
2123 Out.EmitAssignment(Sym, Value);
2125 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2130 /// parseIdentifier:
2133 bool AsmParser::parseIdentifier(StringRef &Res) {
2134 // The assembler has relaxed rules for accepting identifiers, in particular we
2135 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2136 // separate tokens. At this level, we have already lexed so we cannot (currently)
2137 // handle this as a context dependent token, instead we detect adjacent tokens
2138 // and return the combined identifier.
2139 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2140 SMLoc PrefixLoc = getLexer().getLoc();
2142 // Consume the prefix character, and check for a following identifier.
2144 if (Lexer.isNot(AsmToken::Identifier))
2147 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2148 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2151 // Construct the joined identifier and consume the token.
2153 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2158 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2161 Res = getTok().getIdentifier();
2163 Lex(); // Consume the identifier token.
2168 /// parseDirectiveSet:
2169 /// ::= .equ identifier ',' expression
2170 /// ::= .equiv identifier ',' expression
2171 /// ::= .set identifier ',' expression
2172 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2175 if (parseIdentifier(Name))
2176 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2178 if (getLexer().isNot(AsmToken::Comma))
2179 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2182 return parseAssignment(Name, allow_redef, true);
2185 bool AsmParser::parseEscapedString(std::string &Data) {
2186 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2189 StringRef Str = getTok().getStringContents();
2190 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2191 if (Str[i] != '\\') {
2196 // Recognize escaped characters. Note that this escape semantics currently
2197 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2200 return TokError("unexpected backslash at end of string");
2202 // Recognize octal sequences.
2203 if ((unsigned)(Str[i] - '0') <= 7) {
2204 // Consume up to three octal characters.
2205 unsigned Value = Str[i] - '0';
2207 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2209 Value = Value * 8 + (Str[i] - '0');
2211 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2213 Value = Value * 8 + (Str[i] - '0');
2218 return TokError("invalid octal escape sequence (out of range)");
2220 Data += (unsigned char)Value;
2224 // Otherwise recognize individual escapes.
2227 // Just reject invalid escape sequences for now.
2228 return TokError("invalid escape sequence (unrecognized character)");
2230 case 'b': Data += '\b'; break;
2231 case 'f': Data += '\f'; break;
2232 case 'n': Data += '\n'; break;
2233 case 'r': Data += '\r'; break;
2234 case 't': Data += '\t'; break;
2235 case '"': Data += '"'; break;
2236 case '\\': Data += '\\'; break;
2243 /// parseDirectiveAscii:
2244 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2245 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2246 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2247 checkForValidSection();
2250 if (getLexer().isNot(AsmToken::String))
2251 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2254 if (parseEscapedString(Data))
2257 getStreamer().EmitBytes(Data);
2259 getStreamer().EmitBytes(StringRef("\0", 1));
2263 if (getLexer().is(AsmToken::EndOfStatement))
2266 if (getLexer().isNot(AsmToken::Comma))
2267 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2276 /// parseDirectiveValue
2277 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2278 bool AsmParser::parseDirectiveValue(unsigned Size) {
2279 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2280 checkForValidSection();
2283 const MCExpr *Value;
2284 SMLoc ExprLoc = getLexer().getLoc();
2285 if (parseExpression(Value))
2288 // Special case constant expressions to match code generator.
2289 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2290 assert(Size <= 8 && "Invalid size");
2291 uint64_t IntValue = MCE->getValue();
2292 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2293 return Error(ExprLoc, "literal value out of range for directive");
2294 getStreamer().EmitIntValue(IntValue, Size);
2296 getStreamer().EmitValue(Value, Size);
2298 if (getLexer().is(AsmToken::EndOfStatement))
2301 // FIXME: Improve diagnostic.
2302 if (getLexer().isNot(AsmToken::Comma))
2303 return TokError("unexpected token in directive");
2312 /// ParseDirectiveOctaValue
2313 /// ::= .octa [ hexconstant (, hexconstant)* ]
2314 bool AsmParser::parseDirectiveOctaValue() {
2315 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2316 checkForValidSection();
2319 if (Lexer.getKind() == AsmToken::Error)
2321 if (Lexer.getKind() != AsmToken::Integer &&
2322 Lexer.getKind() != AsmToken::BigNum)
2323 return TokError("unknown token in expression");
2325 SMLoc ExprLoc = getLexer().getLoc();
2326 APInt IntValue = getTok().getAPIntVal();
2330 if (IntValue.isIntN(64)) {
2332 lo = IntValue.getZExtValue();
2333 } else if (IntValue.isIntN(128)) {
2334 // It might actually have more than 128 bits, but the top ones are zero.
2335 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2336 lo = IntValue.getLoBits(64).getZExtValue();
2338 return Error(ExprLoc, "literal value out of range for directive");
2340 if (MAI.isLittleEndian()) {
2341 getStreamer().EmitIntValue(lo, 8);
2342 getStreamer().EmitIntValue(hi, 8);
2344 getStreamer().EmitIntValue(hi, 8);
2345 getStreamer().EmitIntValue(lo, 8);
2348 if (getLexer().is(AsmToken::EndOfStatement))
2351 // FIXME: Improve diagnostic.
2352 if (getLexer().isNot(AsmToken::Comma))
2353 return TokError("unexpected token in directive");
2362 /// parseDirectiveRealValue
2363 /// ::= (.single | .double) [ expression (, expression)* ]
2364 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2365 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2366 checkForValidSection();
2369 // We don't truly support arithmetic on floating point expressions, so we
2370 // have to manually parse unary prefixes.
2372 if (getLexer().is(AsmToken::Minus)) {
2375 } else if (getLexer().is(AsmToken::Plus))
2378 if (getLexer().isNot(AsmToken::Integer) &&
2379 getLexer().isNot(AsmToken::Real) &&
2380 getLexer().isNot(AsmToken::Identifier))
2381 return TokError("unexpected token in directive");
2383 // Convert to an APFloat.
2384 APFloat Value(Semantics);
2385 StringRef IDVal = getTok().getString();
2386 if (getLexer().is(AsmToken::Identifier)) {
2387 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2388 Value = APFloat::getInf(Semantics);
2389 else if (!IDVal.compare_lower("nan"))
2390 Value = APFloat::getNaN(Semantics, false, ~0);
2392 return TokError("invalid floating point literal");
2393 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2394 APFloat::opInvalidOp)
2395 return TokError("invalid floating point literal");
2399 // Consume the numeric token.
2402 // Emit the value as an integer.
2403 APInt AsInt = Value.bitcastToAPInt();
2404 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2405 AsInt.getBitWidth() / 8);
2407 if (getLexer().is(AsmToken::EndOfStatement))
2410 if (getLexer().isNot(AsmToken::Comma))
2411 return TokError("unexpected token in directive");
2420 /// parseDirectiveZero
2421 /// ::= .zero expression
2422 bool AsmParser::parseDirectiveZero() {
2423 checkForValidSection();
2426 if (parseAbsoluteExpression(NumBytes))
2430 if (getLexer().is(AsmToken::Comma)) {
2432 if (parseAbsoluteExpression(Val))
2436 if (getLexer().isNot(AsmToken::EndOfStatement))
2437 return TokError("unexpected token in '.zero' directive");
2441 getStreamer().EmitFill(NumBytes, Val);
2446 /// parseDirectiveFill
2447 /// ::= .fill expression [ , expression [ , expression ] ]
2448 bool AsmParser::parseDirectiveFill() {
2449 checkForValidSection();
2451 SMLoc RepeatLoc = getLexer().getLoc();
2453 if (parseAbsoluteExpression(NumValues))
2456 if (NumValues < 0) {
2458 "'.fill' directive with negative repeat count has no effect");
2462 int64_t FillSize = 1;
2463 int64_t FillExpr = 0;
2465 SMLoc SizeLoc, ExprLoc;
2466 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2467 if (getLexer().isNot(AsmToken::Comma))
2468 return TokError("unexpected token in '.fill' directive");
2471 SizeLoc = getLexer().getLoc();
2472 if (parseAbsoluteExpression(FillSize))
2475 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2476 if (getLexer().isNot(AsmToken::Comma))
2477 return TokError("unexpected token in '.fill' directive");
2480 ExprLoc = getLexer().getLoc();
2481 if (parseAbsoluteExpression(FillExpr))
2484 if (getLexer().isNot(AsmToken::EndOfStatement))
2485 return TokError("unexpected token in '.fill' directive");
2492 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2496 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2500 if (!isUInt<32>(FillExpr) && FillSize > 4)
2501 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2503 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2504 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2506 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2507 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2508 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2514 /// parseDirectiveOrg
2515 /// ::= .org expression [ , expression ]
2516 bool AsmParser::parseDirectiveOrg() {
2517 checkForValidSection();
2519 const MCExpr *Offset;
2520 SMLoc Loc = getTok().getLoc();
2521 if (parseExpression(Offset))
2524 // Parse optional fill expression.
2525 int64_t FillExpr = 0;
2526 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2527 if (getLexer().isNot(AsmToken::Comma))
2528 return TokError("unexpected token in '.org' directive");
2531 if (parseAbsoluteExpression(FillExpr))
2534 if (getLexer().isNot(AsmToken::EndOfStatement))
2535 return TokError("unexpected token in '.org' directive");
2540 // Only limited forms of relocatable expressions are accepted here, it
2541 // has to be relative to the current section. The streamer will return
2542 // 'true' if the expression wasn't evaluatable.
2543 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2544 return Error(Loc, "expected assembly-time absolute expression");
2549 /// parseDirectiveAlign
2550 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2551 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2552 checkForValidSection();
2554 SMLoc AlignmentLoc = getLexer().getLoc();
2556 if (parseAbsoluteExpression(Alignment))
2560 bool HasFillExpr = false;
2561 int64_t FillExpr = 0;
2562 int64_t MaxBytesToFill = 0;
2563 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2564 if (getLexer().isNot(AsmToken::Comma))
2565 return TokError("unexpected token in directive");
2568 // The fill expression can be omitted while specifying a maximum number of
2569 // alignment bytes, e.g:
2571 if (getLexer().isNot(AsmToken::Comma)) {
2573 if (parseAbsoluteExpression(FillExpr))
2577 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2578 if (getLexer().isNot(AsmToken::Comma))
2579 return TokError("unexpected token in directive");
2582 MaxBytesLoc = getLexer().getLoc();
2583 if (parseAbsoluteExpression(MaxBytesToFill))
2586 if (getLexer().isNot(AsmToken::EndOfStatement))
2587 return TokError("unexpected token in directive");
2596 // Compute alignment in bytes.
2598 // FIXME: Diagnose overflow.
2599 if (Alignment >= 32) {
2600 Error(AlignmentLoc, "invalid alignment value");
2604 Alignment = 1ULL << Alignment;
2606 // Reject alignments that aren't a power of two, for gas compatibility.
2607 if (!isPowerOf2_64(Alignment))
2608 Error(AlignmentLoc, "alignment must be a power of 2");
2611 // Diagnose non-sensical max bytes to align.
2612 if (MaxBytesLoc.isValid()) {
2613 if (MaxBytesToFill < 1) {
2614 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2615 "many bytes, ignoring maximum bytes expression");
2619 if (MaxBytesToFill >= Alignment) {
2620 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2626 // Check whether we should use optimal code alignment for this .align
2628 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2629 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2630 ValueSize == 1 && UseCodeAlign) {
2631 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2633 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2634 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2641 /// parseDirectiveFile
2642 /// ::= .file [number] filename
2643 /// ::= .file number directory filename
2644 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2645 // FIXME: I'm not sure what this is.
2646 int64_t FileNumber = -1;
2647 SMLoc FileNumberLoc = getLexer().getLoc();
2648 if (getLexer().is(AsmToken::Integer)) {
2649 FileNumber = getTok().getIntVal();
2653 return TokError("file number less than one");
2656 if (getLexer().isNot(AsmToken::String))
2657 return TokError("unexpected token in '.file' directive");
2659 // Usually the directory and filename together, otherwise just the directory.
2660 // Allow the strings to have escaped octal character sequence.
2661 std::string Path = getTok().getString();
2662 if (parseEscapedString(Path))
2666 StringRef Directory;
2668 std::string FilenameData;
2669 if (getLexer().is(AsmToken::String)) {
2670 if (FileNumber == -1)
2671 return TokError("explicit path specified, but no file number");
2672 if (parseEscapedString(FilenameData))
2674 Filename = FilenameData;
2681 if (getLexer().isNot(AsmToken::EndOfStatement))
2682 return TokError("unexpected token in '.file' directive");
2684 if (FileNumber == -1)
2685 getStreamer().EmitFileDirective(Filename);
2687 if (getContext().getGenDwarfForAssembly() == true)
2689 "input can't have .file dwarf directives when -g is "
2690 "used to generate dwarf debug info for assembly code");
2692 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2693 Error(FileNumberLoc, "file number already allocated");
2699 /// parseDirectiveLine
2700 /// ::= .line [number]
2701 bool AsmParser::parseDirectiveLine() {
2702 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2703 if (getLexer().isNot(AsmToken::Integer))
2704 return TokError("unexpected token in '.line' directive");
2706 int64_t LineNumber = getTok().getIntVal();
2710 // FIXME: Do something with the .line.
2713 if (getLexer().isNot(AsmToken::EndOfStatement))
2714 return TokError("unexpected token in '.line' directive");
2719 /// parseDirectiveLoc
2720 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2721 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2722 /// The first number is a file number, must have been previously assigned with
2723 /// a .file directive, the second number is the line number and optionally the
2724 /// third number is a column position (zero if not specified). The remaining
2725 /// optional items are .loc sub-directives.
2726 bool AsmParser::parseDirectiveLoc() {
2727 if (getLexer().isNot(AsmToken::Integer))
2728 return TokError("unexpected token in '.loc' directive");
2729 int64_t FileNumber = getTok().getIntVal();
2731 return TokError("file number less than one in '.loc' directive");
2732 if (!getContext().isValidDwarfFileNumber(FileNumber))
2733 return TokError("unassigned file number in '.loc' directive");
2736 int64_t LineNumber = 0;
2737 if (getLexer().is(AsmToken::Integer)) {
2738 LineNumber = getTok().getIntVal();
2740 return TokError("line number less than zero in '.loc' directive");
2744 int64_t ColumnPos = 0;
2745 if (getLexer().is(AsmToken::Integer)) {
2746 ColumnPos = getTok().getIntVal();
2748 return TokError("column position less than zero in '.loc' directive");
2752 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2754 int64_t Discriminator = 0;
2755 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2757 if (getLexer().is(AsmToken::EndOfStatement))
2761 SMLoc Loc = getTok().getLoc();
2762 if (parseIdentifier(Name))
2763 return TokError("unexpected token in '.loc' directive");
2765 if (Name == "basic_block")
2766 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2767 else if (Name == "prologue_end")
2768 Flags |= DWARF2_FLAG_PROLOGUE_END;
2769 else if (Name == "epilogue_begin")
2770 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2771 else if (Name == "is_stmt") {
2772 Loc = getTok().getLoc();
2773 const MCExpr *Value;
2774 if (parseExpression(Value))
2776 // The expression must be the constant 0 or 1.
2777 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2778 int Value = MCE->getValue();
2780 Flags &= ~DWARF2_FLAG_IS_STMT;
2781 else if (Value == 1)
2782 Flags |= DWARF2_FLAG_IS_STMT;
2784 return Error(Loc, "is_stmt value not 0 or 1");
2786 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2788 } else if (Name == "isa") {
2789 Loc = getTok().getLoc();
2790 const MCExpr *Value;
2791 if (parseExpression(Value))
2793 // The expression must be a constant greater or equal to 0.
2794 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2795 int Value = MCE->getValue();
2797 return Error(Loc, "isa number less than zero");
2800 return Error(Loc, "isa number not a constant value");
2802 } else if (Name == "discriminator") {
2803 if (parseAbsoluteExpression(Discriminator))
2806 return Error(Loc, "unknown sub-directive in '.loc' directive");
2809 if (getLexer().is(AsmToken::EndOfStatement))
2814 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2815 Isa, Discriminator, StringRef());
2820 /// parseDirectiveStabs
2821 /// ::= .stabs string, number, number, number
2822 bool AsmParser::parseDirectiveStabs() {
2823 return TokError("unsupported directive '.stabs'");
2826 /// parseDirectiveCFISections
2827 /// ::= .cfi_sections section [, section]
2828 bool AsmParser::parseDirectiveCFISections() {
2833 if (parseIdentifier(Name))
2834 return TokError("Expected an identifier");
2836 if (Name == ".eh_frame")
2838 else if (Name == ".debug_frame")
2841 if (getLexer().is(AsmToken::Comma)) {
2844 if (parseIdentifier(Name))
2845 return TokError("Expected an identifier");
2847 if (Name == ".eh_frame")
2849 else if (Name == ".debug_frame")
2853 getStreamer().EmitCFISections(EH, Debug);
2857 /// parseDirectiveCFIStartProc
2858 /// ::= .cfi_startproc [simple]
2859 bool AsmParser::parseDirectiveCFIStartProc() {
2861 if (getLexer().isNot(AsmToken::EndOfStatement))
2862 if (parseIdentifier(Simple) || Simple != "simple")
2863 return TokError("unexpected token in .cfi_startproc directive");
2865 getStreamer().EmitCFIStartProc(!Simple.empty());
2869 /// parseDirectiveCFIEndProc
2870 /// ::= .cfi_endproc
2871 bool AsmParser::parseDirectiveCFIEndProc() {
2872 getStreamer().EmitCFIEndProc();
2876 /// \brief parse register name or number.
2877 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2878 SMLoc DirectiveLoc) {
2881 if (getLexer().isNot(AsmToken::Integer)) {
2882 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2884 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2886 return parseAbsoluteExpression(Register);
2891 /// parseDirectiveCFIDefCfa
2892 /// ::= .cfi_def_cfa register, offset
2893 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2894 int64_t Register = 0;
2895 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2898 if (getLexer().isNot(AsmToken::Comma))
2899 return TokError("unexpected token in directive");
2903 if (parseAbsoluteExpression(Offset))
2906 getStreamer().EmitCFIDefCfa(Register, Offset);
2910 /// parseDirectiveCFIDefCfaOffset
2911 /// ::= .cfi_def_cfa_offset offset
2912 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2914 if (parseAbsoluteExpression(Offset))
2917 getStreamer().EmitCFIDefCfaOffset(Offset);
2921 /// parseDirectiveCFIRegister
2922 /// ::= .cfi_register register, register
2923 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2924 int64_t Register1 = 0;
2925 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2928 if (getLexer().isNot(AsmToken::Comma))
2929 return TokError("unexpected token in directive");
2932 int64_t Register2 = 0;
2933 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2936 getStreamer().EmitCFIRegister(Register1, Register2);
2940 /// parseDirectiveCFIWindowSave
2941 /// ::= .cfi_window_save
2942 bool AsmParser::parseDirectiveCFIWindowSave() {
2943 getStreamer().EmitCFIWindowSave();
2947 /// parseDirectiveCFIAdjustCfaOffset
2948 /// ::= .cfi_adjust_cfa_offset adjustment
2949 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
2950 int64_t Adjustment = 0;
2951 if (parseAbsoluteExpression(Adjustment))
2954 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2958 /// parseDirectiveCFIDefCfaRegister
2959 /// ::= .cfi_def_cfa_register register
2960 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2961 int64_t Register = 0;
2962 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2965 getStreamer().EmitCFIDefCfaRegister(Register);
2969 /// parseDirectiveCFIOffset
2970 /// ::= .cfi_offset register, offset
2971 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2972 int64_t Register = 0;
2975 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2978 if (getLexer().isNot(AsmToken::Comma))
2979 return TokError("unexpected token in directive");
2982 if (parseAbsoluteExpression(Offset))
2985 getStreamer().EmitCFIOffset(Register, Offset);
2989 /// parseDirectiveCFIRelOffset
2990 /// ::= .cfi_rel_offset register, offset
2991 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2992 int64_t Register = 0;
2994 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2997 if (getLexer().isNot(AsmToken::Comma))
2998 return TokError("unexpected token in directive");
3002 if (parseAbsoluteExpression(Offset))
3005 getStreamer().EmitCFIRelOffset(Register, Offset);
3009 static bool isValidEncoding(int64_t Encoding) {
3010 if (Encoding & ~0xff)
3013 if (Encoding == dwarf::DW_EH_PE_omit)
3016 const unsigned Format = Encoding & 0xf;
3017 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3018 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3019 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3020 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3023 const unsigned Application = Encoding & 0x70;
3024 if (Application != dwarf::DW_EH_PE_absptr &&
3025 Application != dwarf::DW_EH_PE_pcrel)
3031 /// parseDirectiveCFIPersonalityOrLsda
3032 /// IsPersonality true for cfi_personality, false for cfi_lsda
3033 /// ::= .cfi_personality encoding, [symbol_name]
3034 /// ::= .cfi_lsda encoding, [symbol_name]
3035 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3036 int64_t Encoding = 0;
3037 if (parseAbsoluteExpression(Encoding))
3039 if (Encoding == dwarf::DW_EH_PE_omit)
3042 if (!isValidEncoding(Encoding))
3043 return TokError("unsupported encoding.");
3045 if (getLexer().isNot(AsmToken::Comma))
3046 return TokError("unexpected token in directive");
3050 if (parseIdentifier(Name))
3051 return TokError("expected identifier in directive");
3053 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3056 getStreamer().EmitCFIPersonality(Sym, Encoding);
3058 getStreamer().EmitCFILsda(Sym, Encoding);
3062 /// parseDirectiveCFIRememberState
3063 /// ::= .cfi_remember_state
3064 bool AsmParser::parseDirectiveCFIRememberState() {
3065 getStreamer().EmitCFIRememberState();
3069 /// parseDirectiveCFIRestoreState
3070 /// ::= .cfi_remember_state
3071 bool AsmParser::parseDirectiveCFIRestoreState() {
3072 getStreamer().EmitCFIRestoreState();
3076 /// parseDirectiveCFISameValue
3077 /// ::= .cfi_same_value register
3078 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3079 int64_t Register = 0;
3081 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3084 getStreamer().EmitCFISameValue(Register);
3088 /// parseDirectiveCFIRestore
3089 /// ::= .cfi_restore register
3090 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3091 int64_t Register = 0;
3092 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3095 getStreamer().EmitCFIRestore(Register);
3099 /// parseDirectiveCFIEscape
3100 /// ::= .cfi_escape expression[,...]
3101 bool AsmParser::parseDirectiveCFIEscape() {
3104 if (parseAbsoluteExpression(CurrValue))
3107 Values.push_back((uint8_t)CurrValue);
3109 while (getLexer().is(AsmToken::Comma)) {
3112 if (parseAbsoluteExpression(CurrValue))
3115 Values.push_back((uint8_t)CurrValue);
3118 getStreamer().EmitCFIEscape(Values);
3122 /// parseDirectiveCFISignalFrame
3123 /// ::= .cfi_signal_frame
3124 bool AsmParser::parseDirectiveCFISignalFrame() {
3125 if (getLexer().isNot(AsmToken::EndOfStatement))
3126 return Error(getLexer().getLoc(),
3127 "unexpected token in '.cfi_signal_frame'");
3129 getStreamer().EmitCFISignalFrame();
3133 /// parseDirectiveCFIUndefined
3134 /// ::= .cfi_undefined register
3135 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3136 int64_t Register = 0;
3138 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3141 getStreamer().EmitCFIUndefined(Register);
3145 /// parseDirectiveMacrosOnOff
3148 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3149 if (getLexer().isNot(AsmToken::EndOfStatement))
3150 return Error(getLexer().getLoc(),
3151 "unexpected token in '" + Directive + "' directive");
3153 setMacrosEnabled(Directive == ".macros_on");
3157 /// parseDirectiveMacro
3158 /// ::= .macro name [parameters]
3159 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3161 if (parseIdentifier(Name))
3162 return TokError("expected identifier in '.macro' directive");
3164 MCAsmMacroParameters Parameters;
3165 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3166 MCAsmMacroParameter Parameter;
3167 if (parseIdentifier(Parameter.first))
3168 return TokError("expected identifier in '.macro' directive");
3170 if (getLexer().is(AsmToken::Equal)) {
3172 if (parseMacroArgument(Parameter.second))
3176 Parameters.push_back(Parameter);
3178 if (getLexer().is(AsmToken::Comma))
3182 // Eat the end of statement.
3185 AsmToken EndToken, StartToken = getTok();
3187 // Lex the macro definition.
3189 // Check whether we have reached the end of the file.
3190 if (getLexer().is(AsmToken::Eof))
3191 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3193 // Otherwise, check whether we have reach the .endmacro.
3194 if (getLexer().is(AsmToken::Identifier) &&
3195 (getTok().getIdentifier() == ".endm" ||
3196 getTok().getIdentifier() == ".endmacro")) {
3197 EndToken = getTok();
3199 if (getLexer().isNot(AsmToken::EndOfStatement))
3200 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3205 // Otherwise, scan til the end of the statement.
3206 eatToEndOfStatement();
3209 if (lookupMacro(Name)) {
3210 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3213 const char *BodyStart = StartToken.getLoc().getPointer();
3214 const char *BodyEnd = EndToken.getLoc().getPointer();
3215 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3216 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3217 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3221 /// checkForBadMacro
3223 /// With the support added for named parameters there may be code out there that
3224 /// is transitioning from positional parameters. In versions of gas that did
3225 /// not support named parameters they would be ignored on the macro definition.
3226 /// But to support both styles of parameters this is not possible so if a macro
3227 /// definition has named parameters but does not use them and has what appears
3228 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3229 /// warning that the positional parameter found in body which have no effect.
3230 /// Hoping the developer will either remove the named parameters from the macro
3231 /// definition so the positional parameters get used if that was what was
3232 /// intended or change the macro to use the named parameters. It is possible
3233 /// this warning will trigger when the none of the named parameters are used
3234 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3235 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3237 MCAsmMacroParameters Parameters) {
3238 // If this macro is not defined with named parameters the warning we are
3239 // checking for here doesn't apply.
3240 unsigned NParameters = Parameters.size();
3241 if (NParameters == 0)
3244 bool NamedParametersFound = false;
3245 bool PositionalParametersFound = false;
3247 // Look at the body of the macro for use of both the named parameters and what
3248 // are likely to be positional parameters. This is what expandMacro() is
3249 // doing when it finds the parameters in the body.
3250 while (!Body.empty()) {
3251 // Scan for the next possible parameter.
3252 std::size_t End = Body.size(), Pos = 0;
3253 for (; Pos != End; ++Pos) {
3254 // Check for a substitution or escape.
3255 // This macro is defined with parameters, look for \foo, \bar, etc.
3256 if (Body[Pos] == '\\' && Pos + 1 != End)
3259 // This macro should have parameters, but look for $0, $1, ..., $n too.
3260 if (Body[Pos] != '$' || Pos + 1 == End)
3262 char Next = Body[Pos + 1];
3263 if (Next == '$' || Next == 'n' ||
3264 isdigit(static_cast<unsigned char>(Next)))
3268 // Check if we reached the end.
3272 if (Body[Pos] == '$') {
3273 switch (Body[Pos + 1]) {
3278 // $n => number of arguments
3280 PositionalParametersFound = true;
3283 // $[0-9] => argument
3285 PositionalParametersFound = true;
3291 unsigned I = Pos + 1;
3292 while (isIdentifierChar(Body[I]) && I + 1 != End)
3295 const char *Begin = Body.data() + Pos + 1;
3296 StringRef Argument(Begin, I - (Pos + 1));
3298 for (; Index < NParameters; ++Index)
3299 if (Parameters[Index].first == Argument)
3302 if (Index == NParameters) {
3303 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3309 NamedParametersFound = true;
3310 Pos += 1 + Argument.size();
3313 // Update the scan point.
3314 Body = Body.substr(Pos);
3317 if (!NamedParametersFound && PositionalParametersFound)
3318 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3319 "used in macro body, possible positional parameter "
3320 "found in body which will have no effect");
3323 /// parseDirectiveEndMacro
3326 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3327 if (getLexer().isNot(AsmToken::EndOfStatement))
3328 return TokError("unexpected token in '" + Directive + "' directive");
3330 // If we are inside a macro instantiation, terminate the current
3332 if (isInsideMacroInstantiation()) {
3337 // Otherwise, this .endmacro is a stray entry in the file; well formed
3338 // .endmacro directives are handled during the macro definition parsing.
3339 return TokError("unexpected '" + Directive + "' in file, "
3340 "no current macro definition");
3343 /// parseDirectivePurgeMacro
3345 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3347 if (parseIdentifier(Name))
3348 return TokError("expected identifier in '.purgem' directive");
3350 if (getLexer().isNot(AsmToken::EndOfStatement))
3351 return TokError("unexpected token in '.purgem' directive");
3353 if (!lookupMacro(Name))
3354 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3356 undefineMacro(Name);
3360 /// parseDirectiveBundleAlignMode
3361 /// ::= {.bundle_align_mode} expression
3362 bool AsmParser::parseDirectiveBundleAlignMode() {
3363 checkForValidSection();
3365 // Expect a single argument: an expression that evaluates to a constant
3366 // in the inclusive range 0-30.
3367 SMLoc ExprLoc = getLexer().getLoc();
3368 int64_t AlignSizePow2;
3369 if (parseAbsoluteExpression(AlignSizePow2))
3371 else if (getLexer().isNot(AsmToken::EndOfStatement))
3372 return TokError("unexpected token after expression in"
3373 " '.bundle_align_mode' directive");
3374 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3375 return Error(ExprLoc,
3376 "invalid bundle alignment size (expected between 0 and 30)");
3380 // Because of AlignSizePow2's verified range we can safely truncate it to
3382 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3386 /// parseDirectiveBundleLock
3387 /// ::= {.bundle_lock} [align_to_end]
3388 bool AsmParser::parseDirectiveBundleLock() {
3389 checkForValidSection();
3390 bool AlignToEnd = false;
3392 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3394 SMLoc Loc = getTok().getLoc();
3395 const char *kInvalidOptionError =
3396 "invalid option for '.bundle_lock' directive";
3398 if (parseIdentifier(Option))
3399 return Error(Loc, kInvalidOptionError);
3401 if (Option != "align_to_end")
3402 return Error(Loc, kInvalidOptionError);
3403 else if (getLexer().isNot(AsmToken::EndOfStatement))
3405 "unexpected token after '.bundle_lock' directive option");
3411 getStreamer().EmitBundleLock(AlignToEnd);
3415 /// parseDirectiveBundleLock
3416 /// ::= {.bundle_lock}
3417 bool AsmParser::parseDirectiveBundleUnlock() {
3418 checkForValidSection();
3420 if (getLexer().isNot(AsmToken::EndOfStatement))
3421 return TokError("unexpected token in '.bundle_unlock' directive");
3424 getStreamer().EmitBundleUnlock();
3428 /// parseDirectiveSpace
3429 /// ::= (.skip | .space) expression [ , expression ]
3430 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3431 checkForValidSection();
3434 if (parseAbsoluteExpression(NumBytes))
3437 int64_t FillExpr = 0;
3438 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3439 if (getLexer().isNot(AsmToken::Comma))
3440 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3443 if (parseAbsoluteExpression(FillExpr))
3446 if (getLexer().isNot(AsmToken::EndOfStatement))
3447 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3453 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3456 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3457 getStreamer().EmitFill(NumBytes, FillExpr);
3462 /// parseDirectiveLEB128
3463 /// ::= (.sleb128 | .uleb128) expression
3464 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3465 checkForValidSection();
3466 const MCExpr *Value;
3468 if (parseExpression(Value))
3471 if (getLexer().isNot(AsmToken::EndOfStatement))
3472 return TokError("unexpected token in directive");
3475 getStreamer().EmitSLEB128Value(Value);
3477 getStreamer().EmitULEB128Value(Value);
3482 /// parseDirectiveSymbolAttribute
3483 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3484 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3485 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3488 SMLoc Loc = getTok().getLoc();
3490 if (parseIdentifier(Name))
3491 return Error(Loc, "expected identifier in directive");
3493 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3495 // Assembler local symbols don't make any sense here. Complain loudly.
3496 if (Sym->isTemporary())
3497 return Error(Loc, "non-local symbol required in directive");
3499 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3500 return Error(Loc, "unable to emit symbol attribute");
3502 if (getLexer().is(AsmToken::EndOfStatement))
3505 if (getLexer().isNot(AsmToken::Comma))
3506 return TokError("unexpected token in directive");
3515 /// parseDirectiveComm
3516 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3517 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3518 checkForValidSection();
3520 SMLoc IDLoc = getLexer().getLoc();
3522 if (parseIdentifier(Name))
3523 return TokError("expected identifier in directive");
3525 // Handle the identifier as the key symbol.
3526 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3528 if (getLexer().isNot(AsmToken::Comma))
3529 return TokError("unexpected token in directive");
3533 SMLoc SizeLoc = getLexer().getLoc();
3534 if (parseAbsoluteExpression(Size))
3537 int64_t Pow2Alignment = 0;
3538 SMLoc Pow2AlignmentLoc;
3539 if (getLexer().is(AsmToken::Comma)) {
3541 Pow2AlignmentLoc = getLexer().getLoc();
3542 if (parseAbsoluteExpression(Pow2Alignment))
3545 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3546 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3547 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3549 // If this target takes alignments in bytes (not log) validate and convert.
3550 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3551 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3552 if (!isPowerOf2_64(Pow2Alignment))
3553 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3554 Pow2Alignment = Log2_64(Pow2Alignment);
3558 if (getLexer().isNot(AsmToken::EndOfStatement))
3559 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3563 // NOTE: a size of zero for a .comm should create a undefined symbol
3564 // but a size of .lcomm creates a bss symbol of size zero.
3566 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3567 "be less than zero");
3569 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3570 // may internally end up wanting an alignment in bytes.
3571 // FIXME: Diagnose overflow.
3572 if (Pow2Alignment < 0)
3573 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3574 "alignment, can't be less than zero");
3576 if (!Sym->isUndefined())
3577 return Error(IDLoc, "invalid symbol redefinition");
3579 // Create the Symbol as a common or local common with Size and Pow2Alignment
3581 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3585 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3589 /// parseDirectiveAbort
3590 /// ::= .abort [... message ...]
3591 bool AsmParser::parseDirectiveAbort() {
3592 // FIXME: Use loc from directive.
3593 SMLoc Loc = getLexer().getLoc();
3595 StringRef Str = parseStringToEndOfStatement();
3596 if (getLexer().isNot(AsmToken::EndOfStatement))
3597 return TokError("unexpected token in '.abort' directive");
3602 Error(Loc, ".abort detected. Assembly stopping.");
3604 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3605 // FIXME: Actually abort assembly here.
3610 /// parseDirectiveInclude
3611 /// ::= .include "filename"
3612 bool AsmParser::parseDirectiveInclude() {
3613 if (getLexer().isNot(AsmToken::String))
3614 return TokError("expected string in '.include' directive");
3616 // Allow the strings to have escaped octal character sequence.
3617 std::string Filename;
3618 if (parseEscapedString(Filename))
3620 SMLoc IncludeLoc = getLexer().getLoc();
3623 if (getLexer().isNot(AsmToken::EndOfStatement))
3624 return TokError("unexpected token in '.include' directive");
3626 // Attempt to switch the lexer to the included file before consuming the end
3627 // of statement to avoid losing it when we switch.
3628 if (enterIncludeFile(Filename)) {
3629 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3636 /// parseDirectiveIncbin
3637 /// ::= .incbin "filename"
3638 bool AsmParser::parseDirectiveIncbin() {
3639 if (getLexer().isNot(AsmToken::String))
3640 return TokError("expected string in '.incbin' directive");
3642 // Allow the strings to have escaped octal character sequence.
3643 std::string Filename;
3644 if (parseEscapedString(Filename))
3646 SMLoc IncbinLoc = getLexer().getLoc();
3649 if (getLexer().isNot(AsmToken::EndOfStatement))
3650 return TokError("unexpected token in '.incbin' directive");
3652 // Attempt to process the included file.
3653 if (processIncbinFile(Filename)) {
3654 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3661 /// parseDirectiveIf
3662 /// ::= .if expression
3663 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3664 TheCondStack.push_back(TheCondState);
3665 TheCondState.TheCond = AsmCond::IfCond;
3666 if (TheCondState.Ignore) {
3667 eatToEndOfStatement();
3670 if (parseAbsoluteExpression(ExprValue))
3673 if (getLexer().isNot(AsmToken::EndOfStatement))
3674 return TokError("unexpected token in '.if' directive");
3678 TheCondState.CondMet = ExprValue;
3679 TheCondState.Ignore = !TheCondState.CondMet;
3685 /// parseDirectiveIfb
3687 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3688 TheCondStack.push_back(TheCondState);
3689 TheCondState.TheCond = AsmCond::IfCond;
3691 if (TheCondState.Ignore) {
3692 eatToEndOfStatement();
3694 StringRef Str = parseStringToEndOfStatement();
3696 if (getLexer().isNot(AsmToken::EndOfStatement))
3697 return TokError("unexpected token in '.ifb' directive");
3701 TheCondState.CondMet = ExpectBlank == Str.empty();
3702 TheCondState.Ignore = !TheCondState.CondMet;
3708 /// parseDirectiveIfc
3709 /// ::= .ifc string1, string2
3710 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3711 TheCondStack.push_back(TheCondState);
3712 TheCondState.TheCond = AsmCond::IfCond;
3714 if (TheCondState.Ignore) {
3715 eatToEndOfStatement();
3717 StringRef Str1 = parseStringToComma();
3719 if (getLexer().isNot(AsmToken::Comma))
3720 return TokError("unexpected token in '.ifc' directive");
3724 StringRef Str2 = parseStringToEndOfStatement();
3726 if (getLexer().isNot(AsmToken::EndOfStatement))
3727 return TokError("unexpected token in '.ifc' directive");
3731 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3732 TheCondState.Ignore = !TheCondState.CondMet;
3738 /// parseDirectiveIfdef
3739 /// ::= .ifdef symbol
3740 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3742 TheCondStack.push_back(TheCondState);
3743 TheCondState.TheCond = AsmCond::IfCond;
3745 if (TheCondState.Ignore) {
3746 eatToEndOfStatement();
3748 if (parseIdentifier(Name))
3749 return TokError("expected identifier after '.ifdef'");
3753 MCSymbol *Sym = getContext().LookupSymbol(Name);
3756 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3758 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3759 TheCondState.Ignore = !TheCondState.CondMet;
3765 /// parseDirectiveElseIf
3766 /// ::= .elseif expression
3767 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3768 if (TheCondState.TheCond != AsmCond::IfCond &&
3769 TheCondState.TheCond != AsmCond::ElseIfCond)
3770 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3772 TheCondState.TheCond = AsmCond::ElseIfCond;
3774 bool LastIgnoreState = false;
3775 if (!TheCondStack.empty())
3776 LastIgnoreState = TheCondStack.back().Ignore;
3777 if (LastIgnoreState || TheCondState.CondMet) {
3778 TheCondState.Ignore = true;
3779 eatToEndOfStatement();
3782 if (parseAbsoluteExpression(ExprValue))
3785 if (getLexer().isNot(AsmToken::EndOfStatement))
3786 return TokError("unexpected token in '.elseif' directive");
3789 TheCondState.CondMet = ExprValue;
3790 TheCondState.Ignore = !TheCondState.CondMet;
3796 /// parseDirectiveElse
3798 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3799 if (getLexer().isNot(AsmToken::EndOfStatement))
3800 return TokError("unexpected token in '.else' directive");
3804 if (TheCondState.TheCond != AsmCond::IfCond &&
3805 TheCondState.TheCond != AsmCond::ElseIfCond)
3806 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3808 TheCondState.TheCond = AsmCond::ElseCond;
3809 bool LastIgnoreState = false;
3810 if (!TheCondStack.empty())
3811 LastIgnoreState = TheCondStack.back().Ignore;
3812 if (LastIgnoreState || TheCondState.CondMet)
3813 TheCondState.Ignore = true;
3815 TheCondState.Ignore = false;
3820 /// parseDirectiveEnd
3822 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
3823 if (getLexer().isNot(AsmToken::EndOfStatement))
3824 return TokError("unexpected token in '.end' directive");
3828 while (Lexer.isNot(AsmToken::Eof))
3834 /// parseDirectiveEndIf
3836 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
3837 if (getLexer().isNot(AsmToken::EndOfStatement))
3838 return TokError("unexpected token in '.endif' directive");
3842 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
3843 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3845 if (!TheCondStack.empty()) {
3846 TheCondState = TheCondStack.back();
3847 TheCondStack.pop_back();
3853 void AsmParser::initializeDirectiveKindMap() {
3854 DirectiveKindMap[".set"] = DK_SET;
3855 DirectiveKindMap[".equ"] = DK_EQU;
3856 DirectiveKindMap[".equiv"] = DK_EQUIV;
3857 DirectiveKindMap[".ascii"] = DK_ASCII;
3858 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3859 DirectiveKindMap[".string"] = DK_STRING;
3860 DirectiveKindMap[".byte"] = DK_BYTE;
3861 DirectiveKindMap[".short"] = DK_SHORT;
3862 DirectiveKindMap[".value"] = DK_VALUE;
3863 DirectiveKindMap[".2byte"] = DK_2BYTE;
3864 DirectiveKindMap[".long"] = DK_LONG;
3865 DirectiveKindMap[".int"] = DK_INT;
3866 DirectiveKindMap[".4byte"] = DK_4BYTE;
3867 DirectiveKindMap[".quad"] = DK_QUAD;
3868 DirectiveKindMap[".8byte"] = DK_8BYTE;
3869 DirectiveKindMap[".octa"] = DK_OCTA;
3870 DirectiveKindMap[".single"] = DK_SINGLE;
3871 DirectiveKindMap[".float"] = DK_FLOAT;
3872 DirectiveKindMap[".double"] = DK_DOUBLE;
3873 DirectiveKindMap[".align"] = DK_ALIGN;
3874 DirectiveKindMap[".align32"] = DK_ALIGN32;
3875 DirectiveKindMap[".balign"] = DK_BALIGN;
3876 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3877 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3878 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3879 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3880 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3881 DirectiveKindMap[".org"] = DK_ORG;
3882 DirectiveKindMap[".fill"] = DK_FILL;
3883 DirectiveKindMap[".zero"] = DK_ZERO;
3884 DirectiveKindMap[".extern"] = DK_EXTERN;
3885 DirectiveKindMap[".globl"] = DK_GLOBL;
3886 DirectiveKindMap[".global"] = DK_GLOBAL;
3887 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3888 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3889 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3890 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3891 DirectiveKindMap[".reference"] = DK_REFERENCE;
3892 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3893 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3894 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3895 DirectiveKindMap[".comm"] = DK_COMM;
3896 DirectiveKindMap[".common"] = DK_COMMON;
3897 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3898 DirectiveKindMap[".abort"] = DK_ABORT;
3899 DirectiveKindMap[".include"] = DK_INCLUDE;
3900 DirectiveKindMap[".incbin"] = DK_INCBIN;
3901 DirectiveKindMap[".code16"] = DK_CODE16;
3902 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3903 DirectiveKindMap[".rept"] = DK_REPT;
3904 DirectiveKindMap[".rep"] = DK_REPT;
3905 DirectiveKindMap[".irp"] = DK_IRP;
3906 DirectiveKindMap[".irpc"] = DK_IRPC;
3907 DirectiveKindMap[".endr"] = DK_ENDR;
3908 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3909 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3910 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3911 DirectiveKindMap[".if"] = DK_IF;
3912 DirectiveKindMap[".ifb"] = DK_IFB;
3913 DirectiveKindMap[".ifnb"] = DK_IFNB;
3914 DirectiveKindMap[".ifc"] = DK_IFC;
3915 DirectiveKindMap[".ifnc"] = DK_IFNC;
3916 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3917 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3918 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3919 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3920 DirectiveKindMap[".else"] = DK_ELSE;
3921 DirectiveKindMap[".end"] = DK_END;
3922 DirectiveKindMap[".endif"] = DK_ENDIF;
3923 DirectiveKindMap[".skip"] = DK_SKIP;
3924 DirectiveKindMap[".space"] = DK_SPACE;
3925 DirectiveKindMap[".file"] = DK_FILE;
3926 DirectiveKindMap[".line"] = DK_LINE;
3927 DirectiveKindMap[".loc"] = DK_LOC;
3928 DirectiveKindMap[".stabs"] = DK_STABS;
3929 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3930 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3931 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3932 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3933 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3934 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3935 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3936 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3937 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3938 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3939 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3940 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3941 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3942 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3943 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3944 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3945 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3946 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3947 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3948 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3949 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3950 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
3951 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3952 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3953 DirectiveKindMap[".macro"] = DK_MACRO;
3954 DirectiveKindMap[".endm"] = DK_ENDM;
3955 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3956 DirectiveKindMap[".purgem"] = DK_PURGEM;
3959 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
3960 AsmToken EndToken, StartToken = getTok();
3962 unsigned NestLevel = 0;
3964 // Check whether we have reached the end of the file.
3965 if (getLexer().is(AsmToken::Eof)) {
3966 Error(DirectiveLoc, "no matching '.endr' in definition");
3970 if (Lexer.is(AsmToken::Identifier) &&
3971 (getTok().getIdentifier() == ".rept")) {
3975 // Otherwise, check whether we have reached the .endr.
3976 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
3977 if (NestLevel == 0) {
3978 EndToken = getTok();
3980 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3981 TokError("unexpected token in '.endr' directive");
3989 // Otherwise, scan till the end of the statement.
3990 eatToEndOfStatement();
3993 const char *BodyStart = StartToken.getLoc().getPointer();
3994 const char *BodyEnd = EndToken.getLoc().getPointer();
3995 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3997 // We Are Anonymous.
3999 MCAsmMacroParameters Parameters;
4000 MacroLikeBodies.push_back(MCAsmMacro(Name, Body, Parameters));
4001 return &MacroLikeBodies.back();
4004 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4005 raw_svector_ostream &OS) {
4008 MemoryBuffer *Instantiation =
4009 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4011 // Create the macro instantiation object and add to the current macro
4012 // instantiation stack.
4013 MacroInstantiation *MI = new MacroInstantiation(
4014 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
4015 ActiveMacros.push_back(MI);
4017 // Jump to the macro instantiation and prime the lexer.
4018 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
4019 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
4023 /// parseDirectiveRept
4024 /// ::= .rep | .rept count
4025 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4026 const MCExpr *CountExpr;
4027 SMLoc CountLoc = getTok().getLoc();
4028 if (parseExpression(CountExpr))
4032 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4033 eatToEndOfStatement();
4034 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4038 return Error(CountLoc, "Count is negative");
4040 if (Lexer.isNot(AsmToken::EndOfStatement))
4041 return TokError("unexpected token in '" + Dir + "' directive");
4043 // Eat the end of statement.
4046 // Lex the rept definition.
4047 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4051 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4052 // to hold the macro body with substitutions.
4053 SmallString<256> Buf;
4054 MCAsmMacroParameters Parameters;
4055 MCAsmMacroArguments A;
4056 raw_svector_ostream OS(Buf);
4058 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
4061 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4066 /// parseDirectiveIrp
4067 /// ::= .irp symbol,values
4068 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4069 MCAsmMacroParameters Parameters;
4070 MCAsmMacroParameter Parameter;
4072 if (parseIdentifier(Parameter.first))
4073 return TokError("expected identifier in '.irp' directive");
4075 Parameters.push_back(Parameter);
4077 if (Lexer.isNot(AsmToken::Comma))
4078 return TokError("expected comma in '.irp' directive");
4082 MCAsmMacroArguments A;
4083 if (parseMacroArguments(0, A))
4086 // Eat the end of statement.
4089 // Lex the irp definition.
4090 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4094 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4095 // to hold the macro body with substitutions.
4096 SmallString<256> Buf;
4097 raw_svector_ostream OS(Buf);
4099 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4100 MCAsmMacroArguments Args;
4103 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4107 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4112 /// parseDirectiveIrpc
4113 /// ::= .irpc symbol,values
4114 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4115 MCAsmMacroParameters Parameters;
4116 MCAsmMacroParameter Parameter;
4118 if (parseIdentifier(Parameter.first))
4119 return TokError("expected identifier in '.irpc' directive");
4121 Parameters.push_back(Parameter);
4123 if (Lexer.isNot(AsmToken::Comma))
4124 return TokError("expected comma in '.irpc' directive");
4128 MCAsmMacroArguments A;
4129 if (parseMacroArguments(0, A))
4132 if (A.size() != 1 || A.front().size() != 1)
4133 return TokError("unexpected token in '.irpc' directive");
4135 // Eat the end of statement.
4138 // Lex the irpc definition.
4139 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4143 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4144 // to hold the macro body with substitutions.
4145 SmallString<256> Buf;
4146 raw_svector_ostream OS(Buf);
4148 StringRef Values = A.front().front().getString();
4149 std::size_t I, End = Values.size();
4150 for (I = 0; I < End; ++I) {
4151 MCAsmMacroArgument Arg;
4152 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4154 MCAsmMacroArguments Args;
4155 Args.push_back(Arg);
4157 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4161 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4166 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4167 if (ActiveMacros.empty())
4168 return TokError("unmatched '.endr' directive");
4170 // The only .repl that should get here are the ones created by
4171 // instantiateMacroLikeBody.
4172 assert(getLexer().is(AsmToken::EndOfStatement));
4178 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4180 const MCExpr *Value;
4181 SMLoc ExprLoc = getLexer().getLoc();
4182 if (parseExpression(Value))
4184 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4186 return Error(ExprLoc, "unexpected expression in _emit");
4187 uint64_t IntValue = MCE->getValue();
4188 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4189 return Error(ExprLoc, "literal value out of range for directive");
4191 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4195 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4196 const MCExpr *Value;
4197 SMLoc ExprLoc = getLexer().getLoc();
4198 if (parseExpression(Value))
4200 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4202 return Error(ExprLoc, "unexpected expression in align");
4203 uint64_t IntValue = MCE->getValue();
4204 if (!isPowerOf2_64(IntValue))
4205 return Error(ExprLoc, "literal value not a power of two greater then zero");
4207 Info.AsmRewrites->push_back(
4208 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4212 // We are comparing pointers, but the pointers are relative to a single string.
4213 // Thus, this should always be deterministic.
4214 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4215 const AsmRewrite *AsmRewriteB) {
4216 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4218 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4221 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4222 // rewrite to the same location. Make sure the SizeDirective rewrite is
4223 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4224 // ensures the sort algorithm is stable.
4225 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4226 AsmRewritePrecedence[AsmRewriteB->Kind])
4229 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4230 AsmRewritePrecedence[AsmRewriteB->Kind])
4232 llvm_unreachable("Unstable rewrite sort.");
4235 bool AsmParser::parseMSInlineAsm(
4236 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4237 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4238 SmallVectorImpl<std::string> &Constraints,
4239 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4240 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4241 SmallVector<void *, 4> InputDecls;
4242 SmallVector<void *, 4> OutputDecls;
4243 SmallVector<bool, 4> InputDeclsAddressOf;
4244 SmallVector<bool, 4> OutputDeclsAddressOf;
4245 SmallVector<std::string, 4> InputConstraints;
4246 SmallVector<std::string, 4> OutputConstraints;
4247 SmallVector<unsigned, 4> ClobberRegs;
4249 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4254 // While we have input, parse each statement.
4255 unsigned InputIdx = 0;
4256 unsigned OutputIdx = 0;
4257 while (getLexer().isNot(AsmToken::Eof)) {
4258 ParseStatementInfo Info(&AsmStrRewrites);
4259 if (parseStatement(Info))
4262 if (Info.ParseError)
4265 if (Info.Opcode == ~0U)
4268 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4270 // Build the list of clobbers, outputs and inputs.
4271 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4272 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4275 if (Operand->isImm())
4278 // Register operand.
4279 if (Operand->isReg() && !Operand->needAddressOf()) {
4280 unsigned NumDefs = Desc.getNumDefs();
4282 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4283 ClobberRegs.push_back(Operand->getReg());
4287 // Expr/Input or Output.
4288 StringRef SymName = Operand->getSymName();
4289 if (SymName.empty())
4292 void *OpDecl = Operand->getOpDecl();
4296 bool isOutput = (i == 1) && Desc.mayStore();
4297 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4300 OutputDecls.push_back(OpDecl);
4301 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4302 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4303 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4305 InputDecls.push_back(OpDecl);
4306 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4307 InputConstraints.push_back(Operand->getConstraint().str());
4308 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4312 // Consider implicit defs to be clobbers. Think of cpuid and push.
4313 const uint16_t *ImpDefs = Desc.getImplicitDefs();
4314 for (unsigned I = 0, E = Desc.getNumImplicitDefs(); I != E; ++I)
4315 ClobberRegs.push_back(ImpDefs[I]);
4318 // Set the number of Outputs and Inputs.
4319 NumOutputs = OutputDecls.size();
4320 NumInputs = InputDecls.size();
4322 // Set the unique clobbers.
4323 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4324 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4326 Clobbers.assign(ClobberRegs.size(), std::string());
4327 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4328 raw_string_ostream OS(Clobbers[I]);
4329 IP->printRegName(OS, ClobberRegs[I]);
4332 // Merge the various outputs and inputs. Output are expected first.
4333 if (NumOutputs || NumInputs) {
4334 unsigned NumExprs = NumOutputs + NumInputs;
4335 OpDecls.resize(NumExprs);
4336 Constraints.resize(NumExprs);
4337 for (unsigned i = 0; i < NumOutputs; ++i) {
4338 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4339 Constraints[i] = OutputConstraints[i];
4341 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4342 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4343 Constraints[j] = InputConstraints[i];
4347 // Build the IR assembly string.
4348 std::string AsmStringIR;
4349 raw_string_ostream OS(AsmStringIR);
4350 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4351 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4352 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4353 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4354 E = AsmStrRewrites.end();
4356 AsmRewriteKind Kind = (*I).Kind;
4357 if (Kind == AOK_Delete)
4360 const char *Loc = (*I).Loc.getPointer();
4361 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4363 // Emit everything up to the immediate/expression.
4364 unsigned Len = Loc - AsmStart;
4366 OS << StringRef(AsmStart, Len);
4368 // Skip the original expression.
4369 if (Kind == AOK_Skip) {
4370 AsmStart = Loc + (*I).Len;
4374 unsigned AdditionalSkip = 0;
4375 // Rewrite expressions in $N notation.
4380 OS << "$$" << (*I).Val;
4386 OS << '$' << InputIdx++;
4389 OS << '$' << OutputIdx++;
4391 case AOK_SizeDirective:
4394 case 8: OS << "byte ptr "; break;
4395 case 16: OS << "word ptr "; break;
4396 case 32: OS << "dword ptr "; break;
4397 case 64: OS << "qword ptr "; break;
4398 case 80: OS << "xword ptr "; break;
4399 case 128: OS << "xmmword ptr "; break;
4400 case 256: OS << "ymmword ptr "; break;
4407 unsigned Val = (*I).Val;
4408 OS << ".align " << Val;
4410 // Skip the original immediate.
4411 assert(Val < 10 && "Expected alignment less then 2^10.");
4412 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4415 case AOK_DotOperator:
4420 // Skip the original expression.
4421 AsmStart = Loc + (*I).Len + AdditionalSkip;
4424 // Emit the remainder of the asm string.
4425 if (AsmStart != AsmEnd)
4426 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4428 AsmString = OS.str();
4432 /// \brief Create an MCAsmParser instance.
4433 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4434 MCStreamer &Out, const MCAsmInfo &MAI) {
4435 return new AsmParser(SM, C, Out, MAI);