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. If the argument delimiter
291 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
292 /// correct delimiter by the method.
293 bool parseMacroArgument(MCAsmMacroArgument &MA,
294 AsmToken::TokenKind &ArgumentDelimiter);
296 /// \brief Parse all macro arguments for a given macro.
297 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
299 void printMacroInstantiations();
300 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
301 ArrayRef<SMRange> Ranges = None) const {
302 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
304 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
306 /// \brief Enter the specified file. This returns true on failure.
307 bool enterIncludeFile(const std::string &Filename);
309 /// \brief Process the specified file for the .incbin directive.
310 /// This returns true on failure.
311 bool processIncbinFile(const std::string &Filename);
313 /// \brief Reset the current lexer position to that given by \p Loc. The
314 /// current token is not set; clients should ensure Lex() is called
317 /// \param InBuffer If not -1, should be the known buffer id that contains the
319 void jumpToLoc(SMLoc Loc, int InBuffer=-1);
321 /// \brief Parse up to the end of statement and a return the contents from the
322 /// current token until the end of the statement; the current token on exit
323 /// will be either the EndOfStatement or EOF.
324 virtual StringRef parseStringToEndOfStatement();
326 /// \brief Parse until the end of a statement or a comma is encountered,
327 /// return the contents from the current token up to the end or comma.
328 StringRef parseStringToComma();
330 bool parseAssignment(StringRef Name, bool allow_redef,
331 bool NoDeadStrip = false);
333 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
334 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
335 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
337 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
339 // Generic (target and platform independent) directive parsing.
341 DK_NO_DIRECTIVE, // Placeholder
342 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
343 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
344 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
345 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
346 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
347 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
348 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
349 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
350 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
351 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
352 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
353 DK_ELSEIF, DK_ELSE, DK_ENDIF,
354 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
355 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
356 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
357 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
358 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
359 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
360 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
361 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
362 DK_SLEB128, DK_ULEB128,
366 /// \brief Maps directive name --> DirectiveKind enum, for
367 /// directives parsed by this class.
368 StringMap<DirectiveKind> DirectiveKindMap;
370 // ".ascii", ".asciz", ".string"
371 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
372 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
373 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
374 bool parseDirectiveFill(); // ".fill"
375 bool parseDirectiveZero(); // ".zero"
376 // ".set", ".equ", ".equiv"
377 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
378 bool parseDirectiveOrg(); // ".org"
379 // ".align{,32}", ".p2align{,w,l}"
380 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
382 // ".file", ".line", ".loc", ".stabs"
383 bool parseDirectiveFile(SMLoc DirectiveLoc);
384 bool parseDirectiveLine();
385 bool parseDirectiveLoc();
386 bool parseDirectiveStabs();
389 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
390 bool parseDirectiveCFIWindowSave();
391 bool parseDirectiveCFISections();
392 bool parseDirectiveCFIStartProc();
393 bool parseDirectiveCFIEndProc();
394 bool parseDirectiveCFIDefCfaOffset();
395 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
396 bool parseDirectiveCFIAdjustCfaOffset();
397 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
398 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
399 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
400 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
401 bool parseDirectiveCFIRememberState();
402 bool parseDirectiveCFIRestoreState();
403 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
404 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
405 bool parseDirectiveCFIEscape();
406 bool parseDirectiveCFISignalFrame();
407 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
410 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
411 bool parseDirectiveEndMacro(StringRef Directive);
412 bool parseDirectiveMacro(SMLoc DirectiveLoc);
413 bool parseDirectiveMacrosOnOff(StringRef Directive);
415 // ".bundle_align_mode"
416 bool parseDirectiveBundleAlignMode();
418 bool parseDirectiveBundleLock();
420 bool parseDirectiveBundleUnlock();
423 bool parseDirectiveSpace(StringRef IDVal);
425 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
426 bool parseDirectiveLEB128(bool Signed);
428 /// \brief Parse a directive like ".globl" which
429 /// accepts a single symbol (which should be a label or an external).
430 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
432 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
434 bool parseDirectiveAbort(); // ".abort"
435 bool parseDirectiveInclude(); // ".include"
436 bool parseDirectiveIncbin(); // ".incbin"
438 bool parseDirectiveIf(SMLoc DirectiveLoc); // ".if"
439 // ".ifb" or ".ifnb", depending on ExpectBlank.
440 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
441 // ".ifc" or ".ifnc", depending on ExpectEqual.
442 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
443 // ".ifdef" or ".ifndef", depending on expect_defined
444 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
445 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
446 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
447 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
448 virtual bool parseEscapedString(std::string &Data);
450 const MCExpr *applyModifierToExpr(const MCExpr *E,
451 MCSymbolRefExpr::VariantKind Variant);
453 // Macro-like directives
454 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
455 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
456 raw_svector_ostream &OS);
457 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
458 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
459 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
460 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
462 // "_emit" or "__emit"
463 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
467 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
470 bool parseDirectiveEnd(SMLoc DirectiveLoc);
472 void initializeDirectiveKindMap();
478 extern MCAsmParserExtension *createDarwinAsmParser();
479 extern MCAsmParserExtension *createELFAsmParser();
480 extern MCAsmParserExtension *createCOFFAsmParser();
484 enum { DEFAULT_ADDRSPACE = 0 };
486 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
487 const MCAsmInfo &_MAI)
488 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
489 PlatformParser(0), CurBuffer(0), MacrosEnabledFlag(true),
490 CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false),
491 ParsingInlineAsm(false) {
492 // Save the old handler.
493 SavedDiagHandler = SrcMgr.getDiagHandler();
494 SavedDiagContext = SrcMgr.getDiagContext();
495 // Set our own handler which calls the saved handler.
496 SrcMgr.setDiagHandler(DiagHandler, this);
497 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
499 // Initialize the platform / file format parser.
500 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
501 case MCObjectFileInfo::IsCOFF:
502 PlatformParser = createCOFFAsmParser();
503 PlatformParser->Initialize(*this);
505 case MCObjectFileInfo::IsMachO:
506 PlatformParser = createDarwinAsmParser();
507 PlatformParser->Initialize(*this);
510 case MCObjectFileInfo::IsELF:
511 PlatformParser = createELFAsmParser();
512 PlatformParser->Initialize(*this);
516 initializeDirectiveKindMap();
519 AsmParser::~AsmParser() {
520 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
522 // Destroy any macros.
523 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
526 delete it->getValue();
528 delete PlatformParser;
531 void AsmParser::printMacroInstantiations() {
532 // Print the active macro instantiation stack.
533 for (std::vector<MacroInstantiation *>::const_reverse_iterator
534 it = ActiveMacros.rbegin(),
535 ie = ActiveMacros.rend();
537 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
538 "while in macro instantiation");
541 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
542 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
543 printMacroInstantiations();
546 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
547 if (FatalAssemblerWarnings)
548 return Error(L, Msg, Ranges);
549 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
550 printMacroInstantiations();
554 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
556 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
557 printMacroInstantiations();
561 bool AsmParser::enterIncludeFile(const std::string &Filename) {
562 std::string IncludedFile;
563 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
569 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
574 /// Process the specified .incbin file by searching for it in the include paths
575 /// then just emitting the byte contents of the file to the streamer. This
576 /// returns true on failure.
577 bool AsmParser::processIncbinFile(const std::string &Filename) {
578 std::string IncludedFile;
579 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
583 // Pick up the bytes from the file and emit them.
584 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
588 void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
589 if (InBuffer != -1) {
590 CurBuffer = InBuffer;
592 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
594 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
597 const AsmToken &AsmParser::Lex() {
598 const AsmToken *tok = &Lexer.Lex();
600 if (tok->is(AsmToken::Eof)) {
601 // If this is the end of an included file, pop the parent file off the
603 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
604 if (ParentIncludeLoc != SMLoc()) {
605 jumpToLoc(ParentIncludeLoc);
610 if (tok->is(AsmToken::Error))
611 Error(Lexer.getErrLoc(), Lexer.getErr());
616 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
617 // Create the initial section, if requested.
618 if (!NoInitialTextSection)
625 AsmCond StartingCondState = TheCondState;
627 // If we are generating dwarf for assembly source files save the initial text
628 // section and generate a .file directive.
629 if (getContext().getGenDwarfForAssembly()) {
630 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
631 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
632 getStreamer().EmitLabel(SectionStartSym);
633 getContext().setGenDwarfSectionStartSym(SectionStartSym);
634 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
636 getContext().getMainFileName());
639 // While we have input, parse each statement.
640 while (Lexer.isNot(AsmToken::Eof)) {
641 ParseStatementInfo Info;
642 if (!parseStatement(Info))
645 // We had an error, validate that one was emitted and recover by skipping to
647 assert(HadError && "Parse statement returned an error, but none emitted!");
648 eatToEndOfStatement();
651 if (TheCondState.TheCond != StartingCondState.TheCond ||
652 TheCondState.Ignore != StartingCondState.Ignore)
653 return TokError("unmatched .ifs or .elses");
655 // Check to see there are no empty DwarfFile slots.
656 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
657 getContext().getMCDwarfFiles();
658 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
659 if (!MCDwarfFiles[i])
660 TokError("unassigned file number: " + Twine(i) + " for .file directives");
663 // Check to see that all assembler local symbols were actually defined.
664 // Targets that don't do subsections via symbols may not want this, though,
665 // so conservatively exclude them. Only do this if we're finalizing, though,
666 // as otherwise we won't necessarilly have seen everything yet.
667 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
668 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
669 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
672 MCSymbol *Sym = i->getValue();
673 // Variable symbols may not be marked as defined, so check those
674 // explicitly. If we know it's a variable, we have a definition for
675 // the purposes of this check.
676 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
677 // FIXME: We would really like to refer back to where the symbol was
678 // first referenced for a source location. We need to add something
679 // to track that. Currently, we just point to the end of the file.
681 getLexer().getLoc(), SourceMgr::DK_Error,
682 "assembler local symbol '" + Sym->getName() + "' not defined");
686 // Callback to the target parser in case it needs to do anything.
688 getTargetParser().finishParse();
690 // Finalize the output stream if there are no errors and if the client wants
692 if (!HadError && !NoFinalize)
698 void AsmParser::checkForValidSection() {
699 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
700 TokError("expected section directive before assembly directive");
705 /// \brief Throw away the rest of the line for testing purposes.
706 void AsmParser::eatToEndOfStatement() {
707 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
711 if (Lexer.is(AsmToken::EndOfStatement))
715 StringRef AsmParser::parseStringToEndOfStatement() {
716 const char *Start = getTok().getLoc().getPointer();
718 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
721 const char *End = getTok().getLoc().getPointer();
722 return StringRef(Start, End - Start);
725 StringRef AsmParser::parseStringToComma() {
726 const char *Start = getTok().getLoc().getPointer();
728 while (Lexer.isNot(AsmToken::EndOfStatement) &&
729 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
732 const char *End = getTok().getLoc().getPointer();
733 return StringRef(Start, End - Start);
736 /// \brief Parse a paren expression and return it.
737 /// NOTE: This assumes the leading '(' has already been consumed.
739 /// parenexpr ::= expr)
741 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
742 if (parseExpression(Res))
744 if (Lexer.isNot(AsmToken::RParen))
745 return TokError("expected ')' in parentheses expression");
746 EndLoc = Lexer.getTok().getEndLoc();
751 /// \brief Parse a bracket expression and return it.
752 /// NOTE: This assumes the leading '[' has already been consumed.
754 /// bracketexpr ::= expr]
756 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
757 if (parseExpression(Res))
759 if (Lexer.isNot(AsmToken::RBrac))
760 return TokError("expected ']' in brackets expression");
761 EndLoc = Lexer.getTok().getEndLoc();
766 /// \brief Parse a primary expression and return it.
767 /// primaryexpr ::= (parenexpr
768 /// primaryexpr ::= symbol
769 /// primaryexpr ::= number
770 /// primaryexpr ::= '.'
771 /// primaryexpr ::= ~,+,- primaryexpr
772 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
773 SMLoc FirstTokenLoc = getLexer().getLoc();
774 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
775 switch (FirstTokenKind) {
777 return TokError("unknown token in expression");
778 // If we have an error assume that we've already handled it.
779 case AsmToken::Error:
781 case AsmToken::Exclaim:
782 Lex(); // Eat the operator.
783 if (parsePrimaryExpr(Res, EndLoc))
785 Res = MCUnaryExpr::CreateLNot(Res, getContext());
787 case AsmToken::Dollar:
789 case AsmToken::String:
790 case AsmToken::Identifier: {
791 StringRef Identifier;
792 if (parseIdentifier(Identifier)) {
793 if (FirstTokenKind == AsmToken::Dollar) {
794 if (Lexer.getMAI().getDollarIsPC()) {
795 // This is a '$' reference, which references the current PC. Emit a
796 // temporary label to the streamer and refer to it.
797 MCSymbol *Sym = Ctx.CreateTempSymbol();
799 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
801 EndLoc = FirstTokenLoc;
804 return Error(FirstTokenLoc, "invalid token in expression");
808 // Parse symbol variant
809 std::pair<StringRef, StringRef> Split;
810 if (!MAI.useParensForSymbolVariant()) {
811 Split = Identifier.split('@');
812 } else if (Lexer.is(AsmToken::LParen)) {
813 Lexer.Lex(); // eat (
815 parseIdentifier(VName);
816 if (Lexer.isNot(AsmToken::RParen)) {
817 return Error(Lexer.getTok().getLoc(),
818 "unexpected token in variant, expected ')'");
820 Lexer.Lex(); // eat )
821 Split = std::make_pair(Identifier, VName);
824 EndLoc = SMLoc::getFromPointer(Identifier.end());
826 // This is a symbol reference.
827 StringRef SymbolName = Identifier;
828 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
830 // Lookup the symbol variant if used.
831 if (Split.second.size()) {
832 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
833 if (Variant != MCSymbolRefExpr::VK_Invalid) {
834 SymbolName = Split.first;
835 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
836 Variant = MCSymbolRefExpr::VK_None;
838 Variant = MCSymbolRefExpr::VK_None;
839 return Error(SMLoc::getFromPointer(Split.second.begin()),
840 "invalid variant '" + Split.second + "'");
844 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
846 // If this is an absolute variable reference, substitute it now to preserve
847 // semantics in the face of reassignment.
848 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
850 return Error(EndLoc, "unexpected modifier on variable reference");
852 Res = Sym->getVariableValue();
856 // Otherwise create a symbol ref.
857 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
860 case AsmToken::Integer: {
861 SMLoc Loc = getTok().getLoc();
862 int64_t IntVal = getTok().getIntVal();
863 Res = MCConstantExpr::Create(IntVal, getContext());
864 EndLoc = Lexer.getTok().getEndLoc();
866 // Look for 'b' or 'f' following an Integer as a directional label
867 if (Lexer.getKind() == AsmToken::Identifier) {
868 StringRef IDVal = getTok().getString();
869 // Lookup the symbol variant if used.
870 std::pair<StringRef, StringRef> Split = IDVal.split('@');
871 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
872 if (Split.first.size() != IDVal.size()) {
873 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
874 if (Variant == MCSymbolRefExpr::VK_Invalid) {
875 Variant = MCSymbolRefExpr::VK_None;
876 return TokError("invalid variant '" + Split.second + "'");
880 if (IDVal == "f" || IDVal == "b") {
882 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "f" ? 1 : 0);
883 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
884 if (IDVal == "b" && Sym->isUndefined())
885 return Error(Loc, "invalid reference to undefined symbol");
886 EndLoc = Lexer.getTok().getEndLoc();
887 Lex(); // Eat identifier.
892 case AsmToken::Real: {
893 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
894 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
895 Res = MCConstantExpr::Create(IntVal, getContext());
896 EndLoc = Lexer.getTok().getEndLoc();
900 case AsmToken::Dot: {
901 // This is a '.' reference, which references the current PC. Emit a
902 // temporary label to the streamer and refer to it.
903 MCSymbol *Sym = Ctx.CreateTempSymbol();
905 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
906 EndLoc = Lexer.getTok().getEndLoc();
907 Lex(); // Eat identifier.
910 case AsmToken::LParen:
911 Lex(); // Eat the '('.
912 return parseParenExpr(Res, EndLoc);
913 case AsmToken::LBrac:
914 if (!PlatformParser->HasBracketExpressions())
915 return TokError("brackets expression not supported on this target");
916 Lex(); // Eat the '['.
917 return parseBracketExpr(Res, EndLoc);
918 case AsmToken::Minus:
919 Lex(); // Eat the operator.
920 if (parsePrimaryExpr(Res, EndLoc))
922 Res = MCUnaryExpr::CreateMinus(Res, getContext());
925 Lex(); // Eat the operator.
926 if (parsePrimaryExpr(Res, EndLoc))
928 Res = MCUnaryExpr::CreatePlus(Res, getContext());
930 case AsmToken::Tilde:
931 Lex(); // Eat the operator.
932 if (parsePrimaryExpr(Res, EndLoc))
934 Res = MCUnaryExpr::CreateNot(Res, getContext());
939 bool AsmParser::parseExpression(const MCExpr *&Res) {
941 return parseExpression(Res, EndLoc);
945 AsmParser::applyModifierToExpr(const MCExpr *E,
946 MCSymbolRefExpr::VariantKind Variant) {
947 // Ask the target implementation about this expression first.
948 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
951 // Recurse over the given expression, rebuilding it to apply the given variant
952 // if there is exactly one symbol.
953 switch (E->getKind()) {
955 case MCExpr::Constant:
958 case MCExpr::SymbolRef: {
959 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
961 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
962 TokError("invalid variant on expression '" + getTok().getIdentifier() +
963 "' (already modified)");
967 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
970 case MCExpr::Unary: {
971 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
972 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
975 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
978 case MCExpr::Binary: {
979 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
980 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
981 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
991 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
995 llvm_unreachable("Invalid expression kind!");
998 /// \brief Parse an expression and return it.
1000 /// expr ::= expr &&,|| expr -> lowest.
1001 /// expr ::= expr |,^,&,! expr
1002 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1003 /// expr ::= expr <<,>> expr
1004 /// expr ::= expr +,- expr
1005 /// expr ::= expr *,/,% expr -> highest.
1006 /// expr ::= primaryexpr
1008 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1009 // Parse the expression.
1011 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1014 // As a special case, we support 'a op b @ modifier' by rewriting the
1015 // expression to include the modifier. This is inefficient, but in general we
1016 // expect users to use 'a@modifier op b'.
1017 if (Lexer.getKind() == AsmToken::At) {
1020 if (Lexer.isNot(AsmToken::Identifier))
1021 return TokError("unexpected symbol modifier following '@'");
1023 MCSymbolRefExpr::VariantKind Variant =
1024 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1025 if (Variant == MCSymbolRefExpr::VK_Invalid)
1026 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1028 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1030 return TokError("invalid modifier '" + getTok().getIdentifier() +
1031 "' (no symbols present)");
1038 // Try to constant fold it up front, if possible.
1040 if (Res->EvaluateAsAbsolute(Value))
1041 Res = MCConstantExpr::Create(Value, getContext());
1046 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1048 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1051 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1054 SMLoc StartLoc = Lexer.getLoc();
1055 if (parseExpression(Expr))
1058 if (!Expr->EvaluateAsAbsolute(Res))
1059 return Error(StartLoc, "expected absolute expression");
1064 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1065 MCBinaryExpr::Opcode &Kind) {
1068 return 0; // not a binop.
1070 // Lowest Precedence: &&, ||
1071 case AsmToken::AmpAmp:
1072 Kind = MCBinaryExpr::LAnd;
1074 case AsmToken::PipePipe:
1075 Kind = MCBinaryExpr::LOr;
1078 // Low Precedence: |, &, ^
1080 // FIXME: gas seems to support '!' as an infix operator?
1081 case AsmToken::Pipe:
1082 Kind = MCBinaryExpr::Or;
1084 case AsmToken::Caret:
1085 Kind = MCBinaryExpr::Xor;
1088 Kind = MCBinaryExpr::And;
1091 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1092 case AsmToken::EqualEqual:
1093 Kind = MCBinaryExpr::EQ;
1095 case AsmToken::ExclaimEqual:
1096 case AsmToken::LessGreater:
1097 Kind = MCBinaryExpr::NE;
1099 case AsmToken::Less:
1100 Kind = MCBinaryExpr::LT;
1102 case AsmToken::LessEqual:
1103 Kind = MCBinaryExpr::LTE;
1105 case AsmToken::Greater:
1106 Kind = MCBinaryExpr::GT;
1108 case AsmToken::GreaterEqual:
1109 Kind = MCBinaryExpr::GTE;
1112 // Intermediate Precedence: <<, >>
1113 case AsmToken::LessLess:
1114 Kind = MCBinaryExpr::Shl;
1116 case AsmToken::GreaterGreater:
1117 Kind = MCBinaryExpr::Shr;
1120 // High Intermediate Precedence: +, -
1121 case AsmToken::Plus:
1122 Kind = MCBinaryExpr::Add;
1124 case AsmToken::Minus:
1125 Kind = MCBinaryExpr::Sub;
1128 // Highest Precedence: *, /, %
1129 case AsmToken::Star:
1130 Kind = MCBinaryExpr::Mul;
1132 case AsmToken::Slash:
1133 Kind = MCBinaryExpr::Div;
1135 case AsmToken::Percent:
1136 Kind = MCBinaryExpr::Mod;
1141 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1142 /// Res contains the LHS of the expression on input.
1143 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1146 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1147 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1149 // If the next token is lower precedence than we are allowed to eat, return
1150 // successfully with what we ate already.
1151 if (TokPrec < Precedence)
1156 // Eat the next primary expression.
1158 if (parsePrimaryExpr(RHS, EndLoc))
1161 // If BinOp binds less tightly with RHS than the operator after RHS, let
1162 // the pending operator take RHS as its LHS.
1163 MCBinaryExpr::Opcode Dummy;
1164 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1165 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1168 // Merge LHS and RHS according to operator.
1169 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1174 /// ::= EndOfStatement
1175 /// ::= Label* Directive ...Operands... EndOfStatement
1176 /// ::= Label* Identifier OperandList* EndOfStatement
1177 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1178 if (Lexer.is(AsmToken::EndOfStatement)) {
1184 // Statements always start with an identifier or are a full line comment.
1185 AsmToken ID = getTok();
1186 SMLoc IDLoc = ID.getLoc();
1188 int64_t LocalLabelVal = -1;
1189 // A full line comment is a '#' as the first token.
1190 if (Lexer.is(AsmToken::Hash))
1191 return parseCppHashLineFilenameComment(IDLoc);
1193 // Allow an integer followed by a ':' as a directional local label.
1194 if (Lexer.is(AsmToken::Integer)) {
1195 LocalLabelVal = getTok().getIntVal();
1196 if (LocalLabelVal < 0) {
1197 if (!TheCondState.Ignore)
1198 return TokError("unexpected token at start of statement");
1201 IDVal = getTok().getString();
1202 Lex(); // Consume the integer token to be used as an identifier token.
1203 if (Lexer.getKind() != AsmToken::Colon) {
1204 if (!TheCondState.Ignore)
1205 return TokError("unexpected token at start of statement");
1208 } else if (Lexer.is(AsmToken::Dot)) {
1209 // Treat '.' as a valid identifier in this context.
1212 } else if (parseIdentifier(IDVal)) {
1213 if (!TheCondState.Ignore)
1214 return TokError("unexpected token at start of statement");
1218 // Handle conditional assembly here before checking for skipping. We
1219 // have to do this so that .endif isn't skipped in a ".if 0" block for
1221 StringMap<DirectiveKind>::const_iterator DirKindIt =
1222 DirectiveKindMap.find(IDVal);
1223 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1225 : DirKindIt->getValue();
1230 return parseDirectiveIf(IDLoc);
1232 return parseDirectiveIfb(IDLoc, true);
1234 return parseDirectiveIfb(IDLoc, false);
1236 return parseDirectiveIfc(IDLoc, true);
1238 return parseDirectiveIfc(IDLoc, false);
1240 return parseDirectiveIfdef(IDLoc, true);
1243 return parseDirectiveIfdef(IDLoc, false);
1245 return parseDirectiveElseIf(IDLoc);
1247 return parseDirectiveElse(IDLoc);
1249 return parseDirectiveEndIf(IDLoc);
1252 // Ignore the statement if in the middle of inactive conditional
1254 if (TheCondState.Ignore) {
1255 eatToEndOfStatement();
1259 // FIXME: Recurse on local labels?
1261 // See what kind of statement we have.
1262 switch (Lexer.getKind()) {
1263 case AsmToken::Colon: {
1264 checkForValidSection();
1266 // identifier ':' -> Label.
1269 // Diagnose attempt to use '.' as a label.
1271 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1273 // Diagnose attempt to use a variable as a label.
1275 // FIXME: Diagnostics. Note the location of the definition as a label.
1276 // FIXME: This doesn't diagnose assignment to a symbol which has been
1277 // implicitly marked as external.
1279 if (LocalLabelVal == -1)
1280 Sym = getContext().GetOrCreateSymbol(IDVal);
1282 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1283 if (!Sym->isUndefined() || Sym->isVariable())
1284 return Error(IDLoc, "invalid symbol redefinition");
1287 if (!ParsingInlineAsm)
1290 // If we are generating dwarf for assembly source files then gather the
1291 // info to make a dwarf label entry for this label if needed.
1292 if (getContext().getGenDwarfForAssembly())
1293 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1296 getTargetParser().onLabelParsed(Sym);
1298 // Consume any end of statement token, if present, to avoid spurious
1299 // AddBlankLine calls().
1300 if (Lexer.is(AsmToken::EndOfStatement)) {
1302 if (Lexer.is(AsmToken::Eof))
1309 case AsmToken::Equal:
1310 // identifier '=' ... -> assignment statement
1313 return parseAssignment(IDVal, true);
1315 default: // Normal instruction or directive.
1319 // If macros are enabled, check to see if this is a macro instantiation.
1320 if (areMacrosEnabled())
1321 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1322 return handleMacroEntry(M, IDLoc);
1325 // Otherwise, we have a normal instruction or directive.
1327 // Directives start with "."
1328 if (IDVal[0] == '.' && IDVal != ".") {
1329 // There are several entities interested in parsing directives:
1331 // 1. The target-specific assembly parser. Some directives are target
1332 // specific or may potentially behave differently on certain targets.
1333 // 2. Asm parser extensions. For example, platform-specific parsers
1334 // (like the ELF parser) register themselves as extensions.
1335 // 3. The generic directive parser implemented by this class. These are
1336 // all the directives that behave in a target and platform independent
1337 // manner, or at least have a default behavior that's shared between
1338 // all targets and platforms.
1340 // First query the target-specific parser. It will return 'true' if it
1341 // isn't interested in this directive.
1342 if (!getTargetParser().ParseDirective(ID))
1345 // Next, check the extension directive map to see if any extension has
1346 // registered itself to parse this directive.
1347 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1348 ExtensionDirectiveMap.lookup(IDVal);
1350 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1352 // Finally, if no one else is interested in this directive, it must be
1353 // generic and familiar to this class.
1359 return parseDirectiveSet(IDVal, true);
1361 return parseDirectiveSet(IDVal, false);
1363 return parseDirectiveAscii(IDVal, false);
1366 return parseDirectiveAscii(IDVal, true);
1368 return parseDirectiveValue(1);
1372 return parseDirectiveValue(2);
1376 return parseDirectiveValue(4);
1379 return parseDirectiveValue(8);
1382 return parseDirectiveRealValue(APFloat::IEEEsingle);
1384 return parseDirectiveRealValue(APFloat::IEEEdouble);
1386 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1387 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1390 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1391 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1394 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1396 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1398 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1400 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1402 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1404 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1406 return parseDirectiveOrg();
1408 return parseDirectiveFill();
1410 return parseDirectiveZero();
1412 eatToEndOfStatement(); // .extern is the default, ignore it.
1416 return parseDirectiveSymbolAttribute(MCSA_Global);
1417 case DK_LAZY_REFERENCE:
1418 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1419 case DK_NO_DEAD_STRIP:
1420 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1421 case DK_SYMBOL_RESOLVER:
1422 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1423 case DK_PRIVATE_EXTERN:
1424 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1426 return parseDirectiveSymbolAttribute(MCSA_Reference);
1427 case DK_WEAK_DEFINITION:
1428 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1429 case DK_WEAK_REFERENCE:
1430 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1431 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1432 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1435 return parseDirectiveComm(/*IsLocal=*/false);
1437 return parseDirectiveComm(/*IsLocal=*/true);
1439 return parseDirectiveAbort();
1441 return parseDirectiveInclude();
1443 return parseDirectiveIncbin();
1446 return TokError(Twine(IDVal) + " not supported yet");
1448 return parseDirectiveRept(IDLoc, IDVal);
1450 return parseDirectiveIrp(IDLoc);
1452 return parseDirectiveIrpc(IDLoc);
1454 return parseDirectiveEndr(IDLoc);
1455 case DK_BUNDLE_ALIGN_MODE:
1456 return parseDirectiveBundleAlignMode();
1457 case DK_BUNDLE_LOCK:
1458 return parseDirectiveBundleLock();
1459 case DK_BUNDLE_UNLOCK:
1460 return parseDirectiveBundleUnlock();
1462 return parseDirectiveLEB128(true);
1464 return parseDirectiveLEB128(false);
1467 return parseDirectiveSpace(IDVal);
1469 return parseDirectiveFile(IDLoc);
1471 return parseDirectiveLine();
1473 return parseDirectiveLoc();
1475 return parseDirectiveStabs();
1476 case DK_CFI_SECTIONS:
1477 return parseDirectiveCFISections();
1478 case DK_CFI_STARTPROC:
1479 return parseDirectiveCFIStartProc();
1480 case DK_CFI_ENDPROC:
1481 return parseDirectiveCFIEndProc();
1482 case DK_CFI_DEF_CFA:
1483 return parseDirectiveCFIDefCfa(IDLoc);
1484 case DK_CFI_DEF_CFA_OFFSET:
1485 return parseDirectiveCFIDefCfaOffset();
1486 case DK_CFI_ADJUST_CFA_OFFSET:
1487 return parseDirectiveCFIAdjustCfaOffset();
1488 case DK_CFI_DEF_CFA_REGISTER:
1489 return parseDirectiveCFIDefCfaRegister(IDLoc);
1491 return parseDirectiveCFIOffset(IDLoc);
1492 case DK_CFI_REL_OFFSET:
1493 return parseDirectiveCFIRelOffset(IDLoc);
1494 case DK_CFI_PERSONALITY:
1495 return parseDirectiveCFIPersonalityOrLsda(true);
1497 return parseDirectiveCFIPersonalityOrLsda(false);
1498 case DK_CFI_REMEMBER_STATE:
1499 return parseDirectiveCFIRememberState();
1500 case DK_CFI_RESTORE_STATE:
1501 return parseDirectiveCFIRestoreState();
1502 case DK_CFI_SAME_VALUE:
1503 return parseDirectiveCFISameValue(IDLoc);
1504 case DK_CFI_RESTORE:
1505 return parseDirectiveCFIRestore(IDLoc);
1507 return parseDirectiveCFIEscape();
1508 case DK_CFI_SIGNAL_FRAME:
1509 return parseDirectiveCFISignalFrame();
1510 case DK_CFI_UNDEFINED:
1511 return parseDirectiveCFIUndefined(IDLoc);
1512 case DK_CFI_REGISTER:
1513 return parseDirectiveCFIRegister(IDLoc);
1514 case DK_CFI_WINDOW_SAVE:
1515 return parseDirectiveCFIWindowSave();
1518 return parseDirectiveMacrosOnOff(IDVal);
1520 return parseDirectiveMacro(IDLoc);
1523 return parseDirectiveEndMacro(IDVal);
1525 return parseDirectivePurgeMacro(IDLoc);
1527 return parseDirectiveEnd(IDLoc);
1530 return Error(IDLoc, "unknown directive");
1533 // __asm _emit or __asm __emit
1534 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1535 IDVal == "_EMIT" || IDVal == "__EMIT"))
1536 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1539 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1540 return parseDirectiveMSAlign(IDLoc, Info);
1542 checkForValidSection();
1544 // Canonicalize the opcode to lower case.
1545 std::string OpcodeStr = IDVal.lower();
1546 ParseInstructionInfo IInfo(Info.AsmRewrites);
1547 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1548 Info.ParsedOperands);
1549 Info.ParseError = HadError;
1551 // Dump the parsed representation, if requested.
1552 if (getShowParsedOperands()) {
1553 SmallString<256> Str;
1554 raw_svector_ostream OS(Str);
1555 OS << "parsed instruction: [";
1556 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1559 Info.ParsedOperands[i]->print(OS);
1563 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1566 // If we are generating dwarf for assembly source files and the current
1567 // section is the initial text section then generate a .loc directive for
1569 if (!HadError && getContext().getGenDwarfForAssembly() &&
1570 getContext().getGenDwarfSection() ==
1571 getStreamer().getCurrentSection().first) {
1573 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1575 // If we previously parsed a cpp hash file line comment then make sure the
1576 // current Dwarf File is for the CppHashFilename if not then emit the
1577 // Dwarf File table for it and adjust the line number for the .loc.
1578 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
1579 getContext().getMCDwarfFiles();
1580 if (CppHashFilename.size() != 0) {
1581 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1583 getStreamer().EmitDwarfFileDirective(
1584 getContext().nextGenDwarfFileNumber(), StringRef(),
1587 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1588 // cache with the different Loc from the call above we save the last
1589 // info we queried here with SrcMgr.FindLineNumber().
1590 unsigned CppHashLocLineNo;
1591 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1592 CppHashLocLineNo = LastQueryLine;
1594 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1595 LastQueryLine = CppHashLocLineNo;
1596 LastQueryIDLoc = CppHashLoc;
1597 LastQueryBuffer = CppHashBuf;
1599 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1602 getStreamer().EmitDwarfLocDirective(
1603 getContext().getGenDwarfFileNumber(), Line, 0,
1604 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1608 // If parsing succeeded, match the instruction.
1611 HadError = getTargetParser().MatchAndEmitInstruction(
1612 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
1616 // Don't skip the rest of the line, the instruction parser is responsible for
1621 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1622 /// since they may not be able to be tokenized to get to the end of line token.
1623 void AsmParser::eatToEndOfLine() {
1624 if (!Lexer.is(AsmToken::EndOfStatement))
1625 Lexer.LexUntilEndOfLine();
1630 /// parseCppHashLineFilenameComment as this:
1631 /// ::= # number "filename"
1632 /// or just as a full line comment if it doesn't have a number and a string.
1633 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1634 Lex(); // Eat the hash token.
1636 if (getLexer().isNot(AsmToken::Integer)) {
1637 // Consume the line since in cases it is not a well-formed line directive,
1638 // as if were simply a full line comment.
1643 int64_t LineNumber = getTok().getIntVal();
1646 if (getLexer().isNot(AsmToken::String)) {
1651 StringRef Filename = getTok().getString();
1652 // Get rid of the enclosing quotes.
1653 Filename = Filename.substr(1, Filename.size() - 2);
1655 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1657 CppHashFilename = Filename;
1658 CppHashLineNumber = LineNumber;
1659 CppHashBuf = CurBuffer;
1661 // Ignore any trailing characters, they're just comment.
1666 /// \brief will use the last parsed cpp hash line filename comment
1667 /// for the Filename and LineNo if any in the diagnostic.
1668 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1669 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1670 raw_ostream &OS = errs();
1672 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1673 const SMLoc &DiagLoc = Diag.getLoc();
1674 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1675 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1677 // Like SourceMgr::printMessage() we need to print the include stack if any
1678 // before printing the message.
1679 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1680 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1681 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1682 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1685 // If we have not parsed a cpp hash line filename comment or the source
1686 // manager changed or buffer changed (like in a nested include) then just
1687 // print the normal diagnostic using its Filename and LineNo.
1688 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1689 DiagBuf != CppHashBuf) {
1690 if (Parser->SavedDiagHandler)
1691 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1697 // Use the CppHashFilename and calculate a line number based on the
1698 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1700 const std::string &Filename = Parser->CppHashFilename;
1702 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1703 int CppHashLocLineNo =
1704 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1706 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1708 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1709 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1710 Diag.getLineContents(), Diag.getRanges());
1712 if (Parser->SavedDiagHandler)
1713 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1715 NewDiag.print(0, OS);
1718 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1719 // difference being that that function accepts '@' as part of identifiers and
1720 // we can't do that. AsmLexer.cpp should probably be changed to handle
1721 // '@' as a special case when needed.
1722 static bool isIdentifierChar(char c) {
1723 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1727 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1728 const MCAsmMacroParameters &Parameters,
1729 const MCAsmMacroArguments &A, const SMLoc &L) {
1730 unsigned NParameters = Parameters.size();
1731 if (NParameters != 0 && NParameters != A.size())
1732 return Error(L, "Wrong number of arguments");
1734 // A macro without parameters is handled differently on Darwin:
1735 // gas accepts no arguments and does no substitutions
1736 while (!Body.empty()) {
1737 // Scan for the next substitution.
1738 std::size_t End = Body.size(), Pos = 0;
1739 for (; Pos != End; ++Pos) {
1740 // Check for a substitution or escape.
1742 // This macro has no parameters, look for $0, $1, etc.
1743 if (Body[Pos] != '$' || Pos + 1 == End)
1746 char Next = Body[Pos + 1];
1747 if (Next == '$' || Next == 'n' ||
1748 isdigit(static_cast<unsigned char>(Next)))
1751 // This macro has parameters, look for \foo, \bar, etc.
1752 if (Body[Pos] == '\\' && Pos + 1 != End)
1758 OS << Body.slice(0, Pos);
1760 // Check if we reached the end.
1765 switch (Body[Pos + 1]) {
1771 // $n => number of arguments
1776 // $[0-9] => argument
1778 // Missing arguments are ignored.
1779 unsigned Index = Body[Pos + 1] - '0';
1780 if (Index >= A.size())
1783 // Otherwise substitute with the token values, with spaces eliminated.
1784 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1785 ie = A[Index].end();
1787 OS << it->getString();
1793 unsigned I = Pos + 1;
1794 while (isIdentifierChar(Body[I]) && I + 1 != End)
1797 const char *Begin = Body.data() + Pos + 1;
1798 StringRef Argument(Begin, I - (Pos + 1));
1800 for (; Index < NParameters; ++Index)
1801 if (Parameters[Index].first == Argument)
1804 if (Index == NParameters) {
1805 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1808 OS << '\\' << Argument;
1812 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1813 ie = A[Index].end();
1815 if (it->getKind() == AsmToken::String)
1816 OS << it->getStringContents();
1818 OS << it->getString();
1820 Pos += 1 + Argument.size();
1823 // Update the scan point.
1824 Body = Body.substr(Pos);
1830 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1831 SMLoc EL, MemoryBuffer *I)
1832 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1835 static bool isOperator(AsmToken::TokenKind kind) {
1839 case AsmToken::Plus:
1840 case AsmToken::Minus:
1841 case AsmToken::Tilde:
1842 case AsmToken::Slash:
1843 case AsmToken::Star:
1845 case AsmToken::Equal:
1846 case AsmToken::EqualEqual:
1847 case AsmToken::Pipe:
1848 case AsmToken::PipePipe:
1849 case AsmToken::Caret:
1851 case AsmToken::AmpAmp:
1852 case AsmToken::Exclaim:
1853 case AsmToken::ExclaimEqual:
1854 case AsmToken::Percent:
1855 case AsmToken::Less:
1856 case AsmToken::LessEqual:
1857 case AsmToken::LessLess:
1858 case AsmToken::LessGreater:
1859 case AsmToken::Greater:
1860 case AsmToken::GreaterEqual:
1861 case AsmToken::GreaterGreater:
1866 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA,
1867 AsmToken::TokenKind &ArgumentDelimiter) {
1868 unsigned ParenLevel = 0;
1869 unsigned AddTokens = 0;
1871 // gas accepts arguments separated by whitespace, except on Darwin
1873 Lexer.setSkipSpace(false);
1876 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1877 Lexer.setSkipSpace(true);
1878 return TokError("unexpected token in macro instantiation");
1881 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1882 // Spaces and commas cannot be mixed to delimit parameters
1883 if (ArgumentDelimiter == AsmToken::Eof)
1884 ArgumentDelimiter = AsmToken::Comma;
1885 else if (ArgumentDelimiter != AsmToken::Comma) {
1886 Lexer.setSkipSpace(true);
1887 return TokError("expected ' ' for macro argument separator");
1892 if (Lexer.is(AsmToken::Space)) {
1893 Lex(); // Eat spaces
1895 // Spaces can delimit parameters, but could also be part an expression.
1896 // If the token after a space is an operator, add the token and the next
1897 // one into this argument
1898 if (ArgumentDelimiter == AsmToken::Space ||
1899 ArgumentDelimiter == AsmToken::Eof) {
1900 if (isOperator(Lexer.getKind())) {
1901 // Check to see whether the token is used as an operator,
1902 // or part of an identifier
1903 const char *NextChar = getTok().getEndLoc().getPointer();
1904 if (*NextChar == ' ')
1908 if (!AddTokens && ParenLevel == 0) {
1909 if (ArgumentDelimiter == AsmToken::Eof &&
1910 !isOperator(Lexer.getKind()))
1911 ArgumentDelimiter = AsmToken::Space;
1917 // handleMacroEntry relies on not advancing the lexer here
1918 // to be able to fill in the remaining default parameter values
1919 if (Lexer.is(AsmToken::EndOfStatement))
1922 // Adjust the current parentheses level.
1923 if (Lexer.is(AsmToken::LParen))
1925 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1928 // Append the token to the current argument list.
1929 MA.push_back(getTok());
1935 Lexer.setSkipSpace(true);
1936 if (ParenLevel != 0)
1937 return TokError("unbalanced parentheses in macro argument");
1941 // Parse the macro instantiation arguments.
1942 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1943 MCAsmMacroArguments &A) {
1944 const unsigned NParameters = M ? M->Parameters.size() : 0;
1945 // Argument delimiter is initially unknown. It will be set by
1946 // parseMacroArgument()
1947 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1949 // Parse two kinds of macro invocations:
1950 // - macros defined without any parameters accept an arbitrary number of them
1951 // - macros defined with parameters accept at most that many of them
1952 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1954 MCAsmMacroArgument MA;
1956 if (parseMacroArgument(MA, ArgumentDelimiter))
1959 if (!MA.empty() || !NParameters)
1961 else if (NParameters) {
1962 if (!M->Parameters[Parameter].second.empty())
1963 A.push_back(M->Parameters[Parameter].second);
1966 // At the end of the statement, fill in remaining arguments that have
1967 // default values. If there aren't any, then the next argument is
1968 // required but missing
1969 if (Lexer.is(AsmToken::EndOfStatement)) {
1970 if (NParameters && Parameter < NParameters - 1) {
1971 if (M->Parameters[Parameter + 1].second.empty())
1972 return TokError("macro argument '" +
1973 Twine(M->Parameters[Parameter + 1].first) +
1981 if (Lexer.is(AsmToken::Comma))
1984 return TokError("Too many arguments");
1987 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
1988 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
1989 return (I == MacroMap.end()) ? NULL : I->getValue();
1992 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
1993 MacroMap[Name] = new MCAsmMacro(Macro);
1996 void AsmParser::undefineMacro(StringRef Name) {
1997 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
1998 if (I != MacroMap.end()) {
1999 delete I->getValue();
2004 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2005 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2006 // this, although we should protect against infinite loops.
2007 if (ActiveMacros.size() == 20)
2008 return TokError("macros cannot be nested more than 20 levels deep");
2010 MCAsmMacroArguments A;
2011 if (parseMacroArguments(M, A))
2014 // Remove any trailing empty arguments. Do this after-the-fact as we have
2015 // to keep empty arguments in the middle of the list or positionality
2016 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
2017 while (!A.empty() && A.back().empty())
2020 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2021 // to hold the macro body with substitutions.
2022 SmallString<256> Buf;
2023 StringRef Body = M->Body;
2024 raw_svector_ostream OS(Buf);
2026 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2029 // We include the .endmacro in the buffer as our cue to exit the macro
2031 OS << ".endmacro\n";
2033 MemoryBuffer *Instantiation =
2034 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2036 // Create the macro instantiation object and add to the current macro
2037 // instantiation stack.
2038 MacroInstantiation *MI = new MacroInstantiation(
2039 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
2040 ActiveMacros.push_back(MI);
2042 // Jump to the macro instantiation and prime the lexer.
2043 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2044 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2050 void AsmParser::handleMacroExit() {
2051 // Jump to the EndOfStatement we should return to, and consume it.
2052 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2055 // Pop the instantiation entry.
2056 delete ActiveMacros.back();
2057 ActiveMacros.pop_back();
2060 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2061 switch (Value->getKind()) {
2062 case MCExpr::Binary: {
2063 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2064 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2066 case MCExpr::Target:
2067 case MCExpr::Constant:
2069 case MCExpr::SymbolRef: {
2071 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2073 return isUsedIn(Sym, S.getVariableValue());
2077 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2080 llvm_unreachable("Unknown expr kind!");
2083 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2085 // FIXME: Use better location, we should use proper tokens.
2086 SMLoc EqualLoc = Lexer.getLoc();
2088 const MCExpr *Value;
2089 if (parseExpression(Value))
2092 // Note: we don't count b as used in "a = b". This is to allow
2096 if (Lexer.isNot(AsmToken::EndOfStatement))
2097 return TokError("unexpected token in assignment");
2099 // Error on assignment to '.'.
2101 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2102 "(use '.space' or '.org').)"));
2105 // Eat the end of statement marker.
2108 // Validate that the LHS is allowed to be a variable (either it has not been
2109 // used as a symbol, or it is an absolute symbol).
2110 MCSymbol *Sym = getContext().LookupSymbol(Name);
2112 // Diagnose assignment to a label.
2114 // FIXME: Diagnostics. Note the location of the definition as a label.
2115 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2116 if (isUsedIn(Sym, Value))
2117 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2118 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2119 ; // Allow redefinitions of undefined symbols only used in directives.
2120 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2121 ; // Allow redefinitions of variables that haven't yet been used.
2122 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2123 return Error(EqualLoc, "redefinition of '" + Name + "'");
2124 else if (!Sym->isVariable())
2125 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2126 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2127 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2130 // Don't count these checks as uses.
2131 Sym->setUsed(false);
2133 Sym = getContext().GetOrCreateSymbol(Name);
2135 // FIXME: Handle '.'.
2137 // Do the assignment.
2138 Out.EmitAssignment(Sym, Value);
2140 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2145 /// parseIdentifier:
2148 bool AsmParser::parseIdentifier(StringRef &Res) {
2149 // The assembler has relaxed rules for accepting identifiers, in particular we
2150 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2151 // separate tokens. At this level, we have already lexed so we cannot (currently)
2152 // handle this as a context dependent token, instead we detect adjacent tokens
2153 // and return the combined identifier.
2154 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2155 SMLoc PrefixLoc = getLexer().getLoc();
2157 // Consume the prefix character, and check for a following identifier.
2159 if (Lexer.isNot(AsmToken::Identifier))
2162 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2163 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2166 // Construct the joined identifier and consume the token.
2168 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2173 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2176 Res = getTok().getIdentifier();
2178 Lex(); // Consume the identifier token.
2183 /// parseDirectiveSet:
2184 /// ::= .equ identifier ',' expression
2185 /// ::= .equiv identifier ',' expression
2186 /// ::= .set identifier ',' expression
2187 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2190 if (parseIdentifier(Name))
2191 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2193 if (getLexer().isNot(AsmToken::Comma))
2194 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2197 return parseAssignment(Name, allow_redef, true);
2200 bool AsmParser::parseEscapedString(std::string &Data) {
2201 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2204 StringRef Str = getTok().getStringContents();
2205 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2206 if (Str[i] != '\\') {
2211 // Recognize escaped characters. Note that this escape semantics currently
2212 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2215 return TokError("unexpected backslash at end of string");
2217 // Recognize octal sequences.
2218 if ((unsigned)(Str[i] - '0') <= 7) {
2219 // Consume up to three octal characters.
2220 unsigned Value = Str[i] - '0';
2222 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2224 Value = Value * 8 + (Str[i] - '0');
2226 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2228 Value = Value * 8 + (Str[i] - '0');
2233 return TokError("invalid octal escape sequence (out of range)");
2235 Data += (unsigned char)Value;
2239 // Otherwise recognize individual escapes.
2242 // Just reject invalid escape sequences for now.
2243 return TokError("invalid escape sequence (unrecognized character)");
2245 case 'b': Data += '\b'; break;
2246 case 'f': Data += '\f'; break;
2247 case 'n': Data += '\n'; break;
2248 case 'r': Data += '\r'; break;
2249 case 't': Data += '\t'; break;
2250 case '"': Data += '"'; break;
2251 case '\\': Data += '\\'; break;
2258 /// parseDirectiveAscii:
2259 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2260 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2261 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2262 checkForValidSection();
2265 if (getLexer().isNot(AsmToken::String))
2266 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2269 if (parseEscapedString(Data))
2272 getStreamer().EmitBytes(Data);
2274 getStreamer().EmitBytes(StringRef("\0", 1));
2278 if (getLexer().is(AsmToken::EndOfStatement))
2281 if (getLexer().isNot(AsmToken::Comma))
2282 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2291 /// parseDirectiveValue
2292 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2293 bool AsmParser::parseDirectiveValue(unsigned Size) {
2294 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2295 checkForValidSection();
2298 const MCExpr *Value;
2299 SMLoc ExprLoc = getLexer().getLoc();
2300 if (parseExpression(Value))
2303 // Special case constant expressions to match code generator.
2304 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2305 assert(Size <= 8 && "Invalid size");
2306 uint64_t IntValue = MCE->getValue();
2307 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2308 return Error(ExprLoc, "literal value out of range for directive");
2309 getStreamer().EmitIntValue(IntValue, Size);
2311 getStreamer().EmitValue(Value, Size);
2313 if (getLexer().is(AsmToken::EndOfStatement))
2316 // FIXME: Improve diagnostic.
2317 if (getLexer().isNot(AsmToken::Comma))
2318 return TokError("unexpected token in directive");
2327 /// parseDirectiveRealValue
2328 /// ::= (.single | .double) [ expression (, expression)* ]
2329 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2330 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2331 checkForValidSection();
2334 // We don't truly support arithmetic on floating point expressions, so we
2335 // have to manually parse unary prefixes.
2337 if (getLexer().is(AsmToken::Minus)) {
2340 } else if (getLexer().is(AsmToken::Plus))
2343 if (getLexer().isNot(AsmToken::Integer) &&
2344 getLexer().isNot(AsmToken::Real) &&
2345 getLexer().isNot(AsmToken::Identifier))
2346 return TokError("unexpected token in directive");
2348 // Convert to an APFloat.
2349 APFloat Value(Semantics);
2350 StringRef IDVal = getTok().getString();
2351 if (getLexer().is(AsmToken::Identifier)) {
2352 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2353 Value = APFloat::getInf(Semantics);
2354 else if (!IDVal.compare_lower("nan"))
2355 Value = APFloat::getNaN(Semantics, false, ~0);
2357 return TokError("invalid floating point literal");
2358 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2359 APFloat::opInvalidOp)
2360 return TokError("invalid floating point literal");
2364 // Consume the numeric token.
2367 // Emit the value as an integer.
2368 APInt AsInt = Value.bitcastToAPInt();
2369 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2370 AsInt.getBitWidth() / 8);
2372 if (getLexer().is(AsmToken::EndOfStatement))
2375 if (getLexer().isNot(AsmToken::Comma))
2376 return TokError("unexpected token in directive");
2385 /// parseDirectiveZero
2386 /// ::= .zero expression
2387 bool AsmParser::parseDirectiveZero() {
2388 checkForValidSection();
2391 if (parseAbsoluteExpression(NumBytes))
2395 if (getLexer().is(AsmToken::Comma)) {
2397 if (parseAbsoluteExpression(Val))
2401 if (getLexer().isNot(AsmToken::EndOfStatement))
2402 return TokError("unexpected token in '.zero' directive");
2406 getStreamer().EmitFill(NumBytes, Val);
2411 /// parseDirectiveFill
2412 /// ::= .fill expression [ , expression [ , expression ] ]
2413 bool AsmParser::parseDirectiveFill() {
2414 checkForValidSection();
2417 if (parseAbsoluteExpression(NumValues))
2420 int64_t FillSize = 1;
2421 int64_t FillExpr = 0;
2423 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2424 if (getLexer().isNot(AsmToken::Comma))
2425 return TokError("unexpected token in '.fill' directive");
2428 if (parseAbsoluteExpression(FillSize))
2431 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2432 if (getLexer().isNot(AsmToken::Comma))
2433 return TokError("unexpected token in '.fill' directive");
2436 if (parseAbsoluteExpression(FillExpr))
2439 if (getLexer().isNot(AsmToken::EndOfStatement))
2440 return TokError("unexpected token in '.fill' directive");
2446 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2447 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2449 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2450 getStreamer().EmitIntValue(FillExpr, FillSize);
2455 /// parseDirectiveOrg
2456 /// ::= .org expression [ , expression ]
2457 bool AsmParser::parseDirectiveOrg() {
2458 checkForValidSection();
2460 const MCExpr *Offset;
2461 SMLoc Loc = getTok().getLoc();
2462 if (parseExpression(Offset))
2465 // Parse optional fill expression.
2466 int64_t FillExpr = 0;
2467 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2468 if (getLexer().isNot(AsmToken::Comma))
2469 return TokError("unexpected token in '.org' directive");
2472 if (parseAbsoluteExpression(FillExpr))
2475 if (getLexer().isNot(AsmToken::EndOfStatement))
2476 return TokError("unexpected token in '.org' directive");
2481 // Only limited forms of relocatable expressions are accepted here, it
2482 // has to be relative to the current section. The streamer will return
2483 // 'true' if the expression wasn't evaluatable.
2484 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2485 return Error(Loc, "expected assembly-time absolute expression");
2490 /// parseDirectiveAlign
2491 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2492 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2493 checkForValidSection();
2495 SMLoc AlignmentLoc = getLexer().getLoc();
2497 if (parseAbsoluteExpression(Alignment))
2501 bool HasFillExpr = false;
2502 int64_t FillExpr = 0;
2503 int64_t MaxBytesToFill = 0;
2504 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2505 if (getLexer().isNot(AsmToken::Comma))
2506 return TokError("unexpected token in directive");
2509 // The fill expression can be omitted while specifying a maximum number of
2510 // alignment bytes, e.g:
2512 if (getLexer().isNot(AsmToken::Comma)) {
2514 if (parseAbsoluteExpression(FillExpr))
2518 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2519 if (getLexer().isNot(AsmToken::Comma))
2520 return TokError("unexpected token in directive");
2523 MaxBytesLoc = getLexer().getLoc();
2524 if (parseAbsoluteExpression(MaxBytesToFill))
2527 if (getLexer().isNot(AsmToken::EndOfStatement))
2528 return TokError("unexpected token in directive");
2537 // Compute alignment in bytes.
2539 // FIXME: Diagnose overflow.
2540 if (Alignment >= 32) {
2541 Error(AlignmentLoc, "invalid alignment value");
2545 Alignment = 1ULL << Alignment;
2547 // Reject alignments that aren't a power of two, for gas compatibility.
2548 if (!isPowerOf2_64(Alignment))
2549 Error(AlignmentLoc, "alignment must be a power of 2");
2552 // Diagnose non-sensical max bytes to align.
2553 if (MaxBytesLoc.isValid()) {
2554 if (MaxBytesToFill < 1) {
2555 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2556 "many bytes, ignoring maximum bytes expression");
2560 if (MaxBytesToFill >= Alignment) {
2561 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2567 // Check whether we should use optimal code alignment for this .align
2569 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2570 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2571 ValueSize == 1 && UseCodeAlign) {
2572 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2574 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2575 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2582 /// parseDirectiveFile
2583 /// ::= .file [number] filename
2584 /// ::= .file number directory filename
2585 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2586 // FIXME: I'm not sure what this is.
2587 int64_t FileNumber = -1;
2588 SMLoc FileNumberLoc = getLexer().getLoc();
2589 if (getLexer().is(AsmToken::Integer)) {
2590 FileNumber = getTok().getIntVal();
2594 return TokError("file number less than one");
2597 if (getLexer().isNot(AsmToken::String))
2598 return TokError("unexpected token in '.file' directive");
2600 // Usually the directory and filename together, otherwise just the directory.
2601 // Allow the strings to have escaped octal character sequence.
2602 std::string Path = getTok().getString();
2603 if (parseEscapedString(Path))
2607 StringRef Directory;
2609 std::string FilenameData;
2610 if (getLexer().is(AsmToken::String)) {
2611 if (FileNumber == -1)
2612 return TokError("explicit path specified, but no file number");
2613 if (parseEscapedString(FilenameData))
2615 Filename = FilenameData;
2622 if (getLexer().isNot(AsmToken::EndOfStatement))
2623 return TokError("unexpected token in '.file' directive");
2625 if (FileNumber == -1)
2626 getStreamer().EmitFileDirective(Filename);
2628 if (getContext().getGenDwarfForAssembly() == true)
2630 "input can't have .file dwarf directives when -g is "
2631 "used to generate dwarf debug info for assembly code");
2633 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2634 Error(FileNumberLoc, "file number already allocated");
2640 /// parseDirectiveLine
2641 /// ::= .line [number]
2642 bool AsmParser::parseDirectiveLine() {
2643 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2644 if (getLexer().isNot(AsmToken::Integer))
2645 return TokError("unexpected token in '.line' directive");
2647 int64_t LineNumber = getTok().getIntVal();
2651 // FIXME: Do something with the .line.
2654 if (getLexer().isNot(AsmToken::EndOfStatement))
2655 return TokError("unexpected token in '.line' directive");
2660 /// parseDirectiveLoc
2661 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2662 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2663 /// The first number is a file number, must have been previously assigned with
2664 /// a .file directive, the second number is the line number and optionally the
2665 /// third number is a column position (zero if not specified). The remaining
2666 /// optional items are .loc sub-directives.
2667 bool AsmParser::parseDirectiveLoc() {
2668 if (getLexer().isNot(AsmToken::Integer))
2669 return TokError("unexpected token in '.loc' directive");
2670 int64_t FileNumber = getTok().getIntVal();
2672 return TokError("file number less than one in '.loc' directive");
2673 if (!getContext().isValidDwarfFileNumber(FileNumber))
2674 return TokError("unassigned file number in '.loc' directive");
2677 int64_t LineNumber = 0;
2678 if (getLexer().is(AsmToken::Integer)) {
2679 LineNumber = getTok().getIntVal();
2681 return TokError("line number less than zero in '.loc' directive");
2685 int64_t ColumnPos = 0;
2686 if (getLexer().is(AsmToken::Integer)) {
2687 ColumnPos = getTok().getIntVal();
2689 return TokError("column position less than zero in '.loc' directive");
2693 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2695 int64_t Discriminator = 0;
2696 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2698 if (getLexer().is(AsmToken::EndOfStatement))
2702 SMLoc Loc = getTok().getLoc();
2703 if (parseIdentifier(Name))
2704 return TokError("unexpected token in '.loc' directive");
2706 if (Name == "basic_block")
2707 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2708 else if (Name == "prologue_end")
2709 Flags |= DWARF2_FLAG_PROLOGUE_END;
2710 else if (Name == "epilogue_begin")
2711 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2712 else if (Name == "is_stmt") {
2713 Loc = getTok().getLoc();
2714 const MCExpr *Value;
2715 if (parseExpression(Value))
2717 // The expression must be the constant 0 or 1.
2718 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2719 int Value = MCE->getValue();
2721 Flags &= ~DWARF2_FLAG_IS_STMT;
2722 else if (Value == 1)
2723 Flags |= DWARF2_FLAG_IS_STMT;
2725 return Error(Loc, "is_stmt value not 0 or 1");
2727 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2729 } else if (Name == "isa") {
2730 Loc = getTok().getLoc();
2731 const MCExpr *Value;
2732 if (parseExpression(Value))
2734 // The expression must be a constant greater or equal to 0.
2735 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2736 int Value = MCE->getValue();
2738 return Error(Loc, "isa number less than zero");
2741 return Error(Loc, "isa number not a constant value");
2743 } else if (Name == "discriminator") {
2744 if (parseAbsoluteExpression(Discriminator))
2747 return Error(Loc, "unknown sub-directive in '.loc' directive");
2750 if (getLexer().is(AsmToken::EndOfStatement))
2755 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2756 Isa, Discriminator, StringRef());
2761 /// parseDirectiveStabs
2762 /// ::= .stabs string, number, number, number
2763 bool AsmParser::parseDirectiveStabs() {
2764 return TokError("unsupported directive '.stabs'");
2767 /// parseDirectiveCFISections
2768 /// ::= .cfi_sections section [, section]
2769 bool AsmParser::parseDirectiveCFISections() {
2774 if (parseIdentifier(Name))
2775 return TokError("Expected an identifier");
2777 if (Name == ".eh_frame")
2779 else if (Name == ".debug_frame")
2782 if (getLexer().is(AsmToken::Comma)) {
2785 if (parseIdentifier(Name))
2786 return TokError("Expected an identifier");
2788 if (Name == ".eh_frame")
2790 else if (Name == ".debug_frame")
2794 getStreamer().EmitCFISections(EH, Debug);
2798 /// parseDirectiveCFIStartProc
2799 /// ::= .cfi_startproc [simple]
2800 bool AsmParser::parseDirectiveCFIStartProc() {
2802 if (getLexer().isNot(AsmToken::EndOfStatement))
2803 if (parseIdentifier(Simple) || Simple != "simple")
2804 return TokError("unexpected token in .cfi_startproc directive");
2806 getStreamer().EmitCFIStartProc(!Simple.empty());
2810 /// parseDirectiveCFIEndProc
2811 /// ::= .cfi_endproc
2812 bool AsmParser::parseDirectiveCFIEndProc() {
2813 getStreamer().EmitCFIEndProc();
2817 /// \brief parse register name or number.
2818 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2819 SMLoc DirectiveLoc) {
2822 if (getLexer().isNot(AsmToken::Integer)) {
2823 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2825 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2827 return parseAbsoluteExpression(Register);
2832 /// parseDirectiveCFIDefCfa
2833 /// ::= .cfi_def_cfa register, offset
2834 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2835 int64_t Register = 0;
2836 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2839 if (getLexer().isNot(AsmToken::Comma))
2840 return TokError("unexpected token in directive");
2844 if (parseAbsoluteExpression(Offset))
2847 getStreamer().EmitCFIDefCfa(Register, Offset);
2851 /// parseDirectiveCFIDefCfaOffset
2852 /// ::= .cfi_def_cfa_offset offset
2853 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2855 if (parseAbsoluteExpression(Offset))
2858 getStreamer().EmitCFIDefCfaOffset(Offset);
2862 /// parseDirectiveCFIRegister
2863 /// ::= .cfi_register register, register
2864 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2865 int64_t Register1 = 0;
2866 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2869 if (getLexer().isNot(AsmToken::Comma))
2870 return TokError("unexpected token in directive");
2873 int64_t Register2 = 0;
2874 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2877 getStreamer().EmitCFIRegister(Register1, Register2);
2881 /// parseDirectiveCFIWindowSave
2882 /// ::= .cfi_window_save
2883 bool AsmParser::parseDirectiveCFIWindowSave() {
2884 getStreamer().EmitCFIWindowSave();
2888 /// parseDirectiveCFIAdjustCfaOffset
2889 /// ::= .cfi_adjust_cfa_offset adjustment
2890 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
2891 int64_t Adjustment = 0;
2892 if (parseAbsoluteExpression(Adjustment))
2895 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2899 /// parseDirectiveCFIDefCfaRegister
2900 /// ::= .cfi_def_cfa_register register
2901 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2902 int64_t Register = 0;
2903 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2906 getStreamer().EmitCFIDefCfaRegister(Register);
2910 /// parseDirectiveCFIOffset
2911 /// ::= .cfi_offset register, offset
2912 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2913 int64_t Register = 0;
2916 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2919 if (getLexer().isNot(AsmToken::Comma))
2920 return TokError("unexpected token in directive");
2923 if (parseAbsoluteExpression(Offset))
2926 getStreamer().EmitCFIOffset(Register, Offset);
2930 /// parseDirectiveCFIRelOffset
2931 /// ::= .cfi_rel_offset register, offset
2932 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2933 int64_t Register = 0;
2935 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2938 if (getLexer().isNot(AsmToken::Comma))
2939 return TokError("unexpected token in directive");
2943 if (parseAbsoluteExpression(Offset))
2946 getStreamer().EmitCFIRelOffset(Register, Offset);
2950 static bool isValidEncoding(int64_t Encoding) {
2951 if (Encoding & ~0xff)
2954 if (Encoding == dwarf::DW_EH_PE_omit)
2957 const unsigned Format = Encoding & 0xf;
2958 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2959 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2960 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2961 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2964 const unsigned Application = Encoding & 0x70;
2965 if (Application != dwarf::DW_EH_PE_absptr &&
2966 Application != dwarf::DW_EH_PE_pcrel)
2972 /// parseDirectiveCFIPersonalityOrLsda
2973 /// IsPersonality true for cfi_personality, false for cfi_lsda
2974 /// ::= .cfi_personality encoding, [symbol_name]
2975 /// ::= .cfi_lsda encoding, [symbol_name]
2976 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2977 int64_t Encoding = 0;
2978 if (parseAbsoluteExpression(Encoding))
2980 if (Encoding == dwarf::DW_EH_PE_omit)
2983 if (!isValidEncoding(Encoding))
2984 return TokError("unsupported encoding.");
2986 if (getLexer().isNot(AsmToken::Comma))
2987 return TokError("unexpected token in directive");
2991 if (parseIdentifier(Name))
2992 return TokError("expected identifier in directive");
2994 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2997 getStreamer().EmitCFIPersonality(Sym, Encoding);
2999 getStreamer().EmitCFILsda(Sym, Encoding);
3003 /// parseDirectiveCFIRememberState
3004 /// ::= .cfi_remember_state
3005 bool AsmParser::parseDirectiveCFIRememberState() {
3006 getStreamer().EmitCFIRememberState();
3010 /// parseDirectiveCFIRestoreState
3011 /// ::= .cfi_remember_state
3012 bool AsmParser::parseDirectiveCFIRestoreState() {
3013 getStreamer().EmitCFIRestoreState();
3017 /// parseDirectiveCFISameValue
3018 /// ::= .cfi_same_value register
3019 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3020 int64_t Register = 0;
3022 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3025 getStreamer().EmitCFISameValue(Register);
3029 /// parseDirectiveCFIRestore
3030 /// ::= .cfi_restore register
3031 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3032 int64_t Register = 0;
3033 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3036 getStreamer().EmitCFIRestore(Register);
3040 /// parseDirectiveCFIEscape
3041 /// ::= .cfi_escape expression[,...]
3042 bool AsmParser::parseDirectiveCFIEscape() {
3045 if (parseAbsoluteExpression(CurrValue))
3048 Values.push_back((uint8_t)CurrValue);
3050 while (getLexer().is(AsmToken::Comma)) {
3053 if (parseAbsoluteExpression(CurrValue))
3056 Values.push_back((uint8_t)CurrValue);
3059 getStreamer().EmitCFIEscape(Values);
3063 /// parseDirectiveCFISignalFrame
3064 /// ::= .cfi_signal_frame
3065 bool AsmParser::parseDirectiveCFISignalFrame() {
3066 if (getLexer().isNot(AsmToken::EndOfStatement))
3067 return Error(getLexer().getLoc(),
3068 "unexpected token in '.cfi_signal_frame'");
3070 getStreamer().EmitCFISignalFrame();
3074 /// parseDirectiveCFIUndefined
3075 /// ::= .cfi_undefined register
3076 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3077 int64_t Register = 0;
3079 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3082 getStreamer().EmitCFIUndefined(Register);
3086 /// parseDirectiveMacrosOnOff
3089 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3090 if (getLexer().isNot(AsmToken::EndOfStatement))
3091 return Error(getLexer().getLoc(),
3092 "unexpected token in '" + Directive + "' directive");
3094 setMacrosEnabled(Directive == ".macros_on");
3098 /// parseDirectiveMacro
3099 /// ::= .macro name [parameters]
3100 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3102 if (parseIdentifier(Name))
3103 return TokError("expected identifier in '.macro' directive");
3105 MCAsmMacroParameters Parameters;
3106 // Argument delimiter is initially unknown. It will be set by
3107 // parseMacroArgument()
3108 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3109 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3111 MCAsmMacroParameter Parameter;
3112 if (parseIdentifier(Parameter.first))
3113 return TokError("expected identifier in '.macro' directive");
3115 if (getLexer().is(AsmToken::Equal)) {
3117 if (parseMacroArgument(Parameter.second, ArgumentDelimiter))
3121 Parameters.push_back(Parameter);
3123 if (getLexer().is(AsmToken::Comma))
3125 else if (getLexer().is(AsmToken::EndOfStatement))
3130 // Eat the end of statement.
3133 AsmToken EndToken, StartToken = getTok();
3135 // Lex the macro definition.
3137 // Check whether we have reached the end of the file.
3138 if (getLexer().is(AsmToken::Eof))
3139 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3141 // Otherwise, check whether we have reach the .endmacro.
3142 if (getLexer().is(AsmToken::Identifier) &&
3143 (getTok().getIdentifier() == ".endm" ||
3144 getTok().getIdentifier() == ".endmacro")) {
3145 EndToken = getTok();
3147 if (getLexer().isNot(AsmToken::EndOfStatement))
3148 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3153 // Otherwise, scan til the end of the statement.
3154 eatToEndOfStatement();
3157 if (lookupMacro(Name)) {
3158 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3161 const char *BodyStart = StartToken.getLoc().getPointer();
3162 const char *BodyEnd = EndToken.getLoc().getPointer();
3163 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3164 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3165 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3169 /// checkForBadMacro
3171 /// With the support added for named parameters there may be code out there that
3172 /// is transitioning from positional parameters. In versions of gas that did
3173 /// not support named parameters they would be ignored on the macro definition.
3174 /// But to support both styles of parameters this is not possible so if a macro
3175 /// definition has named parameters but does not use them and has what appears
3176 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3177 /// warning that the positional parameter found in body which have no effect.
3178 /// Hoping the developer will either remove the named parameters from the macro
3179 /// definition so the positional parameters get used if that was what was
3180 /// intended or change the macro to use the named parameters. It is possible
3181 /// this warning will trigger when the none of the named parameters are used
3182 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3183 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3185 MCAsmMacroParameters Parameters) {
3186 // If this macro is not defined with named parameters the warning we are
3187 // checking for here doesn't apply.
3188 unsigned NParameters = Parameters.size();
3189 if (NParameters == 0)
3192 bool NamedParametersFound = false;
3193 bool PositionalParametersFound = false;
3195 // Look at the body of the macro for use of both the named parameters and what
3196 // are likely to be positional parameters. This is what expandMacro() is
3197 // doing when it finds the parameters in the body.
3198 while (!Body.empty()) {
3199 // Scan for the next possible parameter.
3200 std::size_t End = Body.size(), Pos = 0;
3201 for (; Pos != End; ++Pos) {
3202 // Check for a substitution or escape.
3203 // This macro is defined with parameters, look for \foo, \bar, etc.
3204 if (Body[Pos] == '\\' && Pos + 1 != End)
3207 // This macro should have parameters, but look for $0, $1, ..., $n too.
3208 if (Body[Pos] != '$' || Pos + 1 == End)
3210 char Next = Body[Pos + 1];
3211 if (Next == '$' || Next == 'n' ||
3212 isdigit(static_cast<unsigned char>(Next)))
3216 // Check if we reached the end.
3220 if (Body[Pos] == '$') {
3221 switch (Body[Pos + 1]) {
3226 // $n => number of arguments
3228 PositionalParametersFound = true;
3231 // $[0-9] => argument
3233 PositionalParametersFound = true;
3239 unsigned I = Pos + 1;
3240 while (isIdentifierChar(Body[I]) && I + 1 != End)
3243 const char *Begin = Body.data() + Pos + 1;
3244 StringRef Argument(Begin, I - (Pos + 1));
3246 for (; Index < NParameters; ++Index)
3247 if (Parameters[Index].first == Argument)
3250 if (Index == NParameters) {
3251 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3257 NamedParametersFound = true;
3258 Pos += 1 + Argument.size();
3261 // Update the scan point.
3262 Body = Body.substr(Pos);
3265 if (!NamedParametersFound && PositionalParametersFound)
3266 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3267 "used in macro body, possible positional parameter "
3268 "found in body which will have no effect");
3271 /// parseDirectiveEndMacro
3274 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3275 if (getLexer().isNot(AsmToken::EndOfStatement))
3276 return TokError("unexpected token in '" + Directive + "' directive");
3278 // If we are inside a macro instantiation, terminate the current
3280 if (isInsideMacroInstantiation()) {
3285 // Otherwise, this .endmacro is a stray entry in the file; well formed
3286 // .endmacro directives are handled during the macro definition parsing.
3287 return TokError("unexpected '" + Directive + "' in file, "
3288 "no current macro definition");
3291 /// parseDirectivePurgeMacro
3293 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3295 if (parseIdentifier(Name))
3296 return TokError("expected identifier in '.purgem' directive");
3298 if (getLexer().isNot(AsmToken::EndOfStatement))
3299 return TokError("unexpected token in '.purgem' directive");
3301 if (!lookupMacro(Name))
3302 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3304 undefineMacro(Name);
3308 /// parseDirectiveBundleAlignMode
3309 /// ::= {.bundle_align_mode} expression
3310 bool AsmParser::parseDirectiveBundleAlignMode() {
3311 checkForValidSection();
3313 // Expect a single argument: an expression that evaluates to a constant
3314 // in the inclusive range 0-30.
3315 SMLoc ExprLoc = getLexer().getLoc();
3316 int64_t AlignSizePow2;
3317 if (parseAbsoluteExpression(AlignSizePow2))
3319 else if (getLexer().isNot(AsmToken::EndOfStatement))
3320 return TokError("unexpected token after expression in"
3321 " '.bundle_align_mode' directive");
3322 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3323 return Error(ExprLoc,
3324 "invalid bundle alignment size (expected between 0 and 30)");
3328 // Because of AlignSizePow2's verified range we can safely truncate it to
3330 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3334 /// parseDirectiveBundleLock
3335 /// ::= {.bundle_lock} [align_to_end]
3336 bool AsmParser::parseDirectiveBundleLock() {
3337 checkForValidSection();
3338 bool AlignToEnd = false;
3340 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3342 SMLoc Loc = getTok().getLoc();
3343 const char *kInvalidOptionError =
3344 "invalid option for '.bundle_lock' directive";
3346 if (parseIdentifier(Option))
3347 return Error(Loc, kInvalidOptionError);
3349 if (Option != "align_to_end")
3350 return Error(Loc, kInvalidOptionError);
3351 else if (getLexer().isNot(AsmToken::EndOfStatement))
3353 "unexpected token after '.bundle_lock' directive option");
3359 getStreamer().EmitBundleLock(AlignToEnd);
3363 /// parseDirectiveBundleLock
3364 /// ::= {.bundle_lock}
3365 bool AsmParser::parseDirectiveBundleUnlock() {
3366 checkForValidSection();
3368 if (getLexer().isNot(AsmToken::EndOfStatement))
3369 return TokError("unexpected token in '.bundle_unlock' directive");
3372 getStreamer().EmitBundleUnlock();
3376 /// parseDirectiveSpace
3377 /// ::= (.skip | .space) expression [ , expression ]
3378 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3379 checkForValidSection();
3382 if (parseAbsoluteExpression(NumBytes))
3385 int64_t FillExpr = 0;
3386 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3387 if (getLexer().isNot(AsmToken::Comma))
3388 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3391 if (parseAbsoluteExpression(FillExpr))
3394 if (getLexer().isNot(AsmToken::EndOfStatement))
3395 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3401 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3404 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3405 getStreamer().EmitFill(NumBytes, FillExpr);
3410 /// parseDirectiveLEB128
3411 /// ::= (.sleb128 | .uleb128) expression
3412 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3413 checkForValidSection();
3414 const MCExpr *Value;
3416 if (parseExpression(Value))
3419 if (getLexer().isNot(AsmToken::EndOfStatement))
3420 return TokError("unexpected token in directive");
3423 getStreamer().EmitSLEB128Value(Value);
3425 getStreamer().EmitULEB128Value(Value);
3430 /// parseDirectiveSymbolAttribute
3431 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3432 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3433 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3436 SMLoc Loc = getTok().getLoc();
3438 if (parseIdentifier(Name))
3439 return Error(Loc, "expected identifier in directive");
3441 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3443 // Assembler local symbols don't make any sense here. Complain loudly.
3444 if (Sym->isTemporary())
3445 return Error(Loc, "non-local symbol required in directive");
3447 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3448 return Error(Loc, "unable to emit symbol attribute");
3450 if (getLexer().is(AsmToken::EndOfStatement))
3453 if (getLexer().isNot(AsmToken::Comma))
3454 return TokError("unexpected token in directive");
3463 /// parseDirectiveComm
3464 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3465 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3466 checkForValidSection();
3468 SMLoc IDLoc = getLexer().getLoc();
3470 if (parseIdentifier(Name))
3471 return TokError("expected identifier in directive");
3473 // Handle the identifier as the key symbol.
3474 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3476 if (getLexer().isNot(AsmToken::Comma))
3477 return TokError("unexpected token in directive");
3481 SMLoc SizeLoc = getLexer().getLoc();
3482 if (parseAbsoluteExpression(Size))
3485 int64_t Pow2Alignment = 0;
3486 SMLoc Pow2AlignmentLoc;
3487 if (getLexer().is(AsmToken::Comma)) {
3489 Pow2AlignmentLoc = getLexer().getLoc();
3490 if (parseAbsoluteExpression(Pow2Alignment))
3493 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3494 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3495 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3497 // If this target takes alignments in bytes (not log) validate and convert.
3498 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3499 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3500 if (!isPowerOf2_64(Pow2Alignment))
3501 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3502 Pow2Alignment = Log2_64(Pow2Alignment);
3506 if (getLexer().isNot(AsmToken::EndOfStatement))
3507 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3511 // NOTE: a size of zero for a .comm should create a undefined symbol
3512 // but a size of .lcomm creates a bss symbol of size zero.
3514 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3515 "be less than zero");
3517 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3518 // may internally end up wanting an alignment in bytes.
3519 // FIXME: Diagnose overflow.
3520 if (Pow2Alignment < 0)
3521 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3522 "alignment, can't be less than zero");
3524 if (!Sym->isUndefined())
3525 return Error(IDLoc, "invalid symbol redefinition");
3527 // Create the Symbol as a common or local common with Size and Pow2Alignment
3529 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3533 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3537 /// parseDirectiveAbort
3538 /// ::= .abort [... message ...]
3539 bool AsmParser::parseDirectiveAbort() {
3540 // FIXME: Use loc from directive.
3541 SMLoc Loc = getLexer().getLoc();
3543 StringRef Str = parseStringToEndOfStatement();
3544 if (getLexer().isNot(AsmToken::EndOfStatement))
3545 return TokError("unexpected token in '.abort' directive");
3550 Error(Loc, ".abort detected. Assembly stopping.");
3552 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3553 // FIXME: Actually abort assembly here.
3558 /// parseDirectiveInclude
3559 /// ::= .include "filename"
3560 bool AsmParser::parseDirectiveInclude() {
3561 if (getLexer().isNot(AsmToken::String))
3562 return TokError("expected string in '.include' directive");
3564 // Allow the strings to have escaped octal character sequence.
3565 std::string Filename;
3566 if (parseEscapedString(Filename))
3568 SMLoc IncludeLoc = getLexer().getLoc();
3571 if (getLexer().isNot(AsmToken::EndOfStatement))
3572 return TokError("unexpected token in '.include' directive");
3574 // Attempt to switch the lexer to the included file before consuming the end
3575 // of statement to avoid losing it when we switch.
3576 if (enterIncludeFile(Filename)) {
3577 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3584 /// parseDirectiveIncbin
3585 /// ::= .incbin "filename"
3586 bool AsmParser::parseDirectiveIncbin() {
3587 if (getLexer().isNot(AsmToken::String))
3588 return TokError("expected string in '.incbin' directive");
3590 // Allow the strings to have escaped octal character sequence.
3591 std::string Filename;
3592 if (parseEscapedString(Filename))
3594 SMLoc IncbinLoc = getLexer().getLoc();
3597 if (getLexer().isNot(AsmToken::EndOfStatement))
3598 return TokError("unexpected token in '.incbin' directive");
3600 // Attempt to process the included file.
3601 if (processIncbinFile(Filename)) {
3602 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3609 /// parseDirectiveIf
3610 /// ::= .if expression
3611 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3612 TheCondStack.push_back(TheCondState);
3613 TheCondState.TheCond = AsmCond::IfCond;
3614 if (TheCondState.Ignore) {
3615 eatToEndOfStatement();
3618 if (parseAbsoluteExpression(ExprValue))
3621 if (getLexer().isNot(AsmToken::EndOfStatement))
3622 return TokError("unexpected token in '.if' directive");
3626 TheCondState.CondMet = ExprValue;
3627 TheCondState.Ignore = !TheCondState.CondMet;
3633 /// parseDirectiveIfb
3635 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3636 TheCondStack.push_back(TheCondState);
3637 TheCondState.TheCond = AsmCond::IfCond;
3639 if (TheCondState.Ignore) {
3640 eatToEndOfStatement();
3642 StringRef Str = parseStringToEndOfStatement();
3644 if (getLexer().isNot(AsmToken::EndOfStatement))
3645 return TokError("unexpected token in '.ifb' directive");
3649 TheCondState.CondMet = ExpectBlank == Str.empty();
3650 TheCondState.Ignore = !TheCondState.CondMet;
3656 /// parseDirectiveIfc
3657 /// ::= .ifc string1, string2
3658 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3659 TheCondStack.push_back(TheCondState);
3660 TheCondState.TheCond = AsmCond::IfCond;
3662 if (TheCondState.Ignore) {
3663 eatToEndOfStatement();
3665 StringRef Str1 = parseStringToComma();
3667 if (getLexer().isNot(AsmToken::Comma))
3668 return TokError("unexpected token in '.ifc' directive");
3672 StringRef Str2 = parseStringToEndOfStatement();
3674 if (getLexer().isNot(AsmToken::EndOfStatement))
3675 return TokError("unexpected token in '.ifc' directive");
3679 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3680 TheCondState.Ignore = !TheCondState.CondMet;
3686 /// parseDirectiveIfdef
3687 /// ::= .ifdef symbol
3688 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3690 TheCondStack.push_back(TheCondState);
3691 TheCondState.TheCond = AsmCond::IfCond;
3693 if (TheCondState.Ignore) {
3694 eatToEndOfStatement();
3696 if (parseIdentifier(Name))
3697 return TokError("expected identifier after '.ifdef'");
3701 MCSymbol *Sym = getContext().LookupSymbol(Name);
3704 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3706 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3707 TheCondState.Ignore = !TheCondState.CondMet;
3713 /// parseDirectiveElseIf
3714 /// ::= .elseif expression
3715 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3716 if (TheCondState.TheCond != AsmCond::IfCond &&
3717 TheCondState.TheCond != AsmCond::ElseIfCond)
3718 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3720 TheCondState.TheCond = AsmCond::ElseIfCond;
3722 bool LastIgnoreState = false;
3723 if (!TheCondStack.empty())
3724 LastIgnoreState = TheCondStack.back().Ignore;
3725 if (LastIgnoreState || TheCondState.CondMet) {
3726 TheCondState.Ignore = true;
3727 eatToEndOfStatement();
3730 if (parseAbsoluteExpression(ExprValue))
3733 if (getLexer().isNot(AsmToken::EndOfStatement))
3734 return TokError("unexpected token in '.elseif' directive");
3737 TheCondState.CondMet = ExprValue;
3738 TheCondState.Ignore = !TheCondState.CondMet;
3744 /// parseDirectiveElse
3746 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3747 if (getLexer().isNot(AsmToken::EndOfStatement))
3748 return TokError("unexpected token in '.else' directive");
3752 if (TheCondState.TheCond != AsmCond::IfCond &&
3753 TheCondState.TheCond != AsmCond::ElseIfCond)
3754 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3756 TheCondState.TheCond = AsmCond::ElseCond;
3757 bool LastIgnoreState = false;
3758 if (!TheCondStack.empty())
3759 LastIgnoreState = TheCondStack.back().Ignore;
3760 if (LastIgnoreState || TheCondState.CondMet)
3761 TheCondState.Ignore = true;
3763 TheCondState.Ignore = false;
3768 /// parseDirectiveEnd
3770 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
3771 if (getLexer().isNot(AsmToken::EndOfStatement))
3772 return TokError("unexpected token in '.end' directive");
3776 while (Lexer.isNot(AsmToken::Eof))
3782 /// parseDirectiveEndIf
3784 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
3785 if (getLexer().isNot(AsmToken::EndOfStatement))
3786 return TokError("unexpected token in '.endif' directive");
3790 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
3791 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3793 if (!TheCondStack.empty()) {
3794 TheCondState = TheCondStack.back();
3795 TheCondStack.pop_back();
3801 void AsmParser::initializeDirectiveKindMap() {
3802 DirectiveKindMap[".set"] = DK_SET;
3803 DirectiveKindMap[".equ"] = DK_EQU;
3804 DirectiveKindMap[".equiv"] = DK_EQUIV;
3805 DirectiveKindMap[".ascii"] = DK_ASCII;
3806 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3807 DirectiveKindMap[".string"] = DK_STRING;
3808 DirectiveKindMap[".byte"] = DK_BYTE;
3809 DirectiveKindMap[".short"] = DK_SHORT;
3810 DirectiveKindMap[".value"] = DK_VALUE;
3811 DirectiveKindMap[".2byte"] = DK_2BYTE;
3812 DirectiveKindMap[".long"] = DK_LONG;
3813 DirectiveKindMap[".int"] = DK_INT;
3814 DirectiveKindMap[".4byte"] = DK_4BYTE;
3815 DirectiveKindMap[".quad"] = DK_QUAD;
3816 DirectiveKindMap[".8byte"] = DK_8BYTE;
3817 DirectiveKindMap[".single"] = DK_SINGLE;
3818 DirectiveKindMap[".float"] = DK_FLOAT;
3819 DirectiveKindMap[".double"] = DK_DOUBLE;
3820 DirectiveKindMap[".align"] = DK_ALIGN;
3821 DirectiveKindMap[".align32"] = DK_ALIGN32;
3822 DirectiveKindMap[".balign"] = DK_BALIGN;
3823 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3824 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3825 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3826 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3827 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3828 DirectiveKindMap[".org"] = DK_ORG;
3829 DirectiveKindMap[".fill"] = DK_FILL;
3830 DirectiveKindMap[".zero"] = DK_ZERO;
3831 DirectiveKindMap[".extern"] = DK_EXTERN;
3832 DirectiveKindMap[".globl"] = DK_GLOBL;
3833 DirectiveKindMap[".global"] = DK_GLOBAL;
3834 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3835 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3836 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3837 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3838 DirectiveKindMap[".reference"] = DK_REFERENCE;
3839 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3840 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3841 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3842 DirectiveKindMap[".comm"] = DK_COMM;
3843 DirectiveKindMap[".common"] = DK_COMMON;
3844 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3845 DirectiveKindMap[".abort"] = DK_ABORT;
3846 DirectiveKindMap[".include"] = DK_INCLUDE;
3847 DirectiveKindMap[".incbin"] = DK_INCBIN;
3848 DirectiveKindMap[".code16"] = DK_CODE16;
3849 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3850 DirectiveKindMap[".rept"] = DK_REPT;
3851 DirectiveKindMap[".rep"] = DK_REPT;
3852 DirectiveKindMap[".irp"] = DK_IRP;
3853 DirectiveKindMap[".irpc"] = DK_IRPC;
3854 DirectiveKindMap[".endr"] = DK_ENDR;
3855 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3856 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3857 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3858 DirectiveKindMap[".if"] = DK_IF;
3859 DirectiveKindMap[".ifb"] = DK_IFB;
3860 DirectiveKindMap[".ifnb"] = DK_IFNB;
3861 DirectiveKindMap[".ifc"] = DK_IFC;
3862 DirectiveKindMap[".ifnc"] = DK_IFNC;
3863 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3864 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3865 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3866 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3867 DirectiveKindMap[".else"] = DK_ELSE;
3868 DirectiveKindMap[".end"] = DK_END;
3869 DirectiveKindMap[".endif"] = DK_ENDIF;
3870 DirectiveKindMap[".skip"] = DK_SKIP;
3871 DirectiveKindMap[".space"] = DK_SPACE;
3872 DirectiveKindMap[".file"] = DK_FILE;
3873 DirectiveKindMap[".line"] = DK_LINE;
3874 DirectiveKindMap[".loc"] = DK_LOC;
3875 DirectiveKindMap[".stabs"] = DK_STABS;
3876 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3877 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3878 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3879 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3880 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3881 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3882 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3883 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3884 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3885 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3886 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3887 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3888 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3889 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3890 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3891 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3892 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3893 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3894 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3895 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3896 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3897 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
3898 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3899 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3900 DirectiveKindMap[".macro"] = DK_MACRO;
3901 DirectiveKindMap[".endm"] = DK_ENDM;
3902 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3903 DirectiveKindMap[".purgem"] = DK_PURGEM;
3906 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
3907 AsmToken EndToken, StartToken = getTok();
3909 unsigned NestLevel = 0;
3911 // Check whether we have reached the end of the file.
3912 if (getLexer().is(AsmToken::Eof)) {
3913 Error(DirectiveLoc, "no matching '.endr' in definition");
3917 if (Lexer.is(AsmToken::Identifier) &&
3918 (getTok().getIdentifier() == ".rept")) {
3922 // Otherwise, check whether we have reached the .endr.
3923 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
3924 if (NestLevel == 0) {
3925 EndToken = getTok();
3927 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3928 TokError("unexpected token in '.endr' directive");
3936 // Otherwise, scan till the end of the statement.
3937 eatToEndOfStatement();
3940 const char *BodyStart = StartToken.getLoc().getPointer();
3941 const char *BodyEnd = EndToken.getLoc().getPointer();
3942 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3944 // We Are Anonymous.
3946 MCAsmMacroParameters Parameters;
3947 MacroLikeBodies.push_back(MCAsmMacro(Name, Body, Parameters));
3948 return &MacroLikeBodies.back();
3951 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
3952 raw_svector_ostream &OS) {
3955 MemoryBuffer *Instantiation =
3956 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3958 // Create the macro instantiation object and add to the current macro
3959 // instantiation stack.
3960 MacroInstantiation *MI = new MacroInstantiation(
3961 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
3962 ActiveMacros.push_back(MI);
3964 // Jump to the macro instantiation and prime the lexer.
3965 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3966 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3970 /// parseDirectiveRept
3971 /// ::= .rep | .rept count
3972 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
3973 const MCExpr *CountExpr;
3974 SMLoc CountLoc = getTok().getLoc();
3975 if (parseExpression(CountExpr))
3979 if (!CountExpr->EvaluateAsAbsolute(Count)) {
3980 eatToEndOfStatement();
3981 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
3985 return Error(CountLoc, "Count is negative");
3987 if (Lexer.isNot(AsmToken::EndOfStatement))
3988 return TokError("unexpected token in '" + Dir + "' directive");
3990 // Eat the end of statement.
3993 // Lex the rept definition.
3994 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
3998 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3999 // to hold the macro body with substitutions.
4000 SmallString<256> Buf;
4001 MCAsmMacroParameters Parameters;
4002 MCAsmMacroArguments A;
4003 raw_svector_ostream OS(Buf);
4005 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
4008 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4013 /// parseDirectiveIrp
4014 /// ::= .irp symbol,values
4015 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4016 MCAsmMacroParameters Parameters;
4017 MCAsmMacroParameter Parameter;
4019 if (parseIdentifier(Parameter.first))
4020 return TokError("expected identifier in '.irp' directive");
4022 Parameters.push_back(Parameter);
4024 if (Lexer.isNot(AsmToken::Comma))
4025 return TokError("expected comma in '.irp' directive");
4029 MCAsmMacroArguments A;
4030 if (parseMacroArguments(0, A))
4033 // Eat the end of statement.
4036 // Lex the irp definition.
4037 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4041 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4042 // to hold the macro body with substitutions.
4043 SmallString<256> Buf;
4044 raw_svector_ostream OS(Buf);
4046 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4047 MCAsmMacroArguments Args;
4050 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4054 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4059 /// parseDirectiveIrpc
4060 /// ::= .irpc symbol,values
4061 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4062 MCAsmMacroParameters Parameters;
4063 MCAsmMacroParameter Parameter;
4065 if (parseIdentifier(Parameter.first))
4066 return TokError("expected identifier in '.irpc' directive");
4068 Parameters.push_back(Parameter);
4070 if (Lexer.isNot(AsmToken::Comma))
4071 return TokError("expected comma in '.irpc' directive");
4075 MCAsmMacroArguments A;
4076 if (parseMacroArguments(0, A))
4079 if (A.size() != 1 || A.front().size() != 1)
4080 return TokError("unexpected token in '.irpc' directive");
4082 // Eat the end of statement.
4085 // Lex the irpc definition.
4086 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4090 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4091 // to hold the macro body with substitutions.
4092 SmallString<256> Buf;
4093 raw_svector_ostream OS(Buf);
4095 StringRef Values = A.front().front().getString();
4096 std::size_t I, End = Values.size();
4097 for (I = 0; I < End; ++I) {
4098 MCAsmMacroArgument Arg;
4099 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4101 MCAsmMacroArguments Args;
4102 Args.push_back(Arg);
4104 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4108 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4113 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4114 if (ActiveMacros.empty())
4115 return TokError("unmatched '.endr' directive");
4117 // The only .repl that should get here are the ones created by
4118 // instantiateMacroLikeBody.
4119 assert(getLexer().is(AsmToken::EndOfStatement));
4125 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4127 const MCExpr *Value;
4128 SMLoc ExprLoc = getLexer().getLoc();
4129 if (parseExpression(Value))
4131 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4133 return Error(ExprLoc, "unexpected expression in _emit");
4134 uint64_t IntValue = MCE->getValue();
4135 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4136 return Error(ExprLoc, "literal value out of range for directive");
4138 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4142 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4143 const MCExpr *Value;
4144 SMLoc ExprLoc = getLexer().getLoc();
4145 if (parseExpression(Value))
4147 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4149 return Error(ExprLoc, "unexpected expression in align");
4150 uint64_t IntValue = MCE->getValue();
4151 if (!isPowerOf2_64(IntValue))
4152 return Error(ExprLoc, "literal value not a power of two greater then zero");
4154 Info.AsmRewrites->push_back(
4155 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4159 // We are comparing pointers, but the pointers are relative to a single string.
4160 // Thus, this should always be deterministic.
4161 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4162 const AsmRewrite *AsmRewriteB) {
4163 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4165 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4168 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4169 // rewrite to the same location. Make sure the SizeDirective rewrite is
4170 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4171 // ensures the sort algorithm is stable.
4172 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4173 AsmRewritePrecedence[AsmRewriteB->Kind])
4176 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4177 AsmRewritePrecedence[AsmRewriteB->Kind])
4179 llvm_unreachable("Unstable rewrite sort.");
4182 bool AsmParser::parseMSInlineAsm(
4183 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4184 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4185 SmallVectorImpl<std::string> &Constraints,
4186 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4187 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4188 SmallVector<void *, 4> InputDecls;
4189 SmallVector<void *, 4> OutputDecls;
4190 SmallVector<bool, 4> InputDeclsAddressOf;
4191 SmallVector<bool, 4> OutputDeclsAddressOf;
4192 SmallVector<std::string, 4> InputConstraints;
4193 SmallVector<std::string, 4> OutputConstraints;
4194 SmallVector<unsigned, 4> ClobberRegs;
4196 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4201 // While we have input, parse each statement.
4202 unsigned InputIdx = 0;
4203 unsigned OutputIdx = 0;
4204 while (getLexer().isNot(AsmToken::Eof)) {
4205 ParseStatementInfo Info(&AsmStrRewrites);
4206 if (parseStatement(Info))
4209 if (Info.ParseError)
4212 if (Info.Opcode == ~0U)
4215 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4217 // Build the list of clobbers, outputs and inputs.
4218 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4219 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4222 if (Operand->isImm())
4225 // Register operand.
4226 if (Operand->isReg() && !Operand->needAddressOf()) {
4227 unsigned NumDefs = Desc.getNumDefs();
4229 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4230 ClobberRegs.push_back(Operand->getReg());
4234 // Expr/Input or Output.
4235 StringRef SymName = Operand->getSymName();
4236 if (SymName.empty())
4239 void *OpDecl = Operand->getOpDecl();
4243 bool isOutput = (i == 1) && Desc.mayStore();
4244 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4247 OutputDecls.push_back(OpDecl);
4248 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4249 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4250 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4252 InputDecls.push_back(OpDecl);
4253 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4254 InputConstraints.push_back(Operand->getConstraint().str());
4255 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4259 // Consider implicit defs to be clobbers. Think of cpuid and push.
4260 const uint16_t *ImpDefs = Desc.getImplicitDefs();
4261 for (unsigned I = 0, E = Desc.getNumImplicitDefs(); I != E; ++I)
4262 ClobberRegs.push_back(ImpDefs[I]);
4265 // Set the number of Outputs and Inputs.
4266 NumOutputs = OutputDecls.size();
4267 NumInputs = InputDecls.size();
4269 // Set the unique clobbers.
4270 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4271 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4273 Clobbers.assign(ClobberRegs.size(), std::string());
4274 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4275 raw_string_ostream OS(Clobbers[I]);
4276 IP->printRegName(OS, ClobberRegs[I]);
4279 // Merge the various outputs and inputs. Output are expected first.
4280 if (NumOutputs || NumInputs) {
4281 unsigned NumExprs = NumOutputs + NumInputs;
4282 OpDecls.resize(NumExprs);
4283 Constraints.resize(NumExprs);
4284 for (unsigned i = 0; i < NumOutputs; ++i) {
4285 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4286 Constraints[i] = OutputConstraints[i];
4288 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4289 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4290 Constraints[j] = InputConstraints[i];
4294 // Build the IR assembly string.
4295 std::string AsmStringIR;
4296 raw_string_ostream OS(AsmStringIR);
4297 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4298 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4299 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4300 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4301 E = AsmStrRewrites.end();
4303 AsmRewriteKind Kind = (*I).Kind;
4304 if (Kind == AOK_Delete)
4307 const char *Loc = (*I).Loc.getPointer();
4308 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4310 // Emit everything up to the immediate/expression.
4311 unsigned Len = Loc - AsmStart;
4313 OS << StringRef(AsmStart, Len);
4315 // Skip the original expression.
4316 if (Kind == AOK_Skip) {
4317 AsmStart = Loc + (*I).Len;
4321 unsigned AdditionalSkip = 0;
4322 // Rewrite expressions in $N notation.
4327 OS << "$$" << (*I).Val;
4333 OS << '$' << InputIdx++;
4336 OS << '$' << OutputIdx++;
4338 case AOK_SizeDirective:
4341 case 8: OS << "byte ptr "; break;
4342 case 16: OS << "word ptr "; break;
4343 case 32: OS << "dword ptr "; break;
4344 case 64: OS << "qword ptr "; break;
4345 case 80: OS << "xword ptr "; break;
4346 case 128: OS << "xmmword ptr "; break;
4347 case 256: OS << "ymmword ptr "; break;
4354 unsigned Val = (*I).Val;
4355 OS << ".align " << Val;
4357 // Skip the original immediate.
4358 assert(Val < 10 && "Expected alignment less then 2^10.");
4359 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4362 case AOK_DotOperator:
4367 // Skip the original expression.
4368 AsmStart = Loc + (*I).Len + AdditionalSkip;
4371 // Emit the remainder of the asm string.
4372 if (AsmStart != AsmEnd)
4373 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4375 AsmString = OS.str();
4379 /// \brief Create an MCAsmParser instance.
4380 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4381 MCStreamer &Out, const MCAsmInfo &MAI) {
4382 return new AsmParser(SM, C, Out, MAI);