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
2800 bool AsmParser::parseDirectiveCFIStartProc() {
2801 getStreamer().EmitCFIStartProc();
2805 /// parseDirectiveCFIEndProc
2806 /// ::= .cfi_endproc
2807 bool AsmParser::parseDirectiveCFIEndProc() {
2808 getStreamer().EmitCFIEndProc();
2812 /// \brief parse register name or number.
2813 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2814 SMLoc DirectiveLoc) {
2817 if (getLexer().isNot(AsmToken::Integer)) {
2818 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2820 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2822 return parseAbsoluteExpression(Register);
2827 /// parseDirectiveCFIDefCfa
2828 /// ::= .cfi_def_cfa register, offset
2829 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2830 int64_t Register = 0;
2831 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2834 if (getLexer().isNot(AsmToken::Comma))
2835 return TokError("unexpected token in directive");
2839 if (parseAbsoluteExpression(Offset))
2842 getStreamer().EmitCFIDefCfa(Register, Offset);
2846 /// parseDirectiveCFIDefCfaOffset
2847 /// ::= .cfi_def_cfa_offset offset
2848 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2850 if (parseAbsoluteExpression(Offset))
2853 getStreamer().EmitCFIDefCfaOffset(Offset);
2857 /// parseDirectiveCFIRegister
2858 /// ::= .cfi_register register, register
2859 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2860 int64_t Register1 = 0;
2861 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2864 if (getLexer().isNot(AsmToken::Comma))
2865 return TokError("unexpected token in directive");
2868 int64_t Register2 = 0;
2869 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2872 getStreamer().EmitCFIRegister(Register1, Register2);
2876 /// parseDirectiveCFIWindowSave
2877 /// ::= .cfi_window_save
2878 bool AsmParser::parseDirectiveCFIWindowSave() {
2879 getStreamer().EmitCFIWindowSave();
2883 /// parseDirectiveCFIAdjustCfaOffset
2884 /// ::= .cfi_adjust_cfa_offset adjustment
2885 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
2886 int64_t Adjustment = 0;
2887 if (parseAbsoluteExpression(Adjustment))
2890 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2894 /// parseDirectiveCFIDefCfaRegister
2895 /// ::= .cfi_def_cfa_register register
2896 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2897 int64_t Register = 0;
2898 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2901 getStreamer().EmitCFIDefCfaRegister(Register);
2905 /// parseDirectiveCFIOffset
2906 /// ::= .cfi_offset register, offset
2907 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2908 int64_t Register = 0;
2911 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2914 if (getLexer().isNot(AsmToken::Comma))
2915 return TokError("unexpected token in directive");
2918 if (parseAbsoluteExpression(Offset))
2921 getStreamer().EmitCFIOffset(Register, Offset);
2925 /// parseDirectiveCFIRelOffset
2926 /// ::= .cfi_rel_offset register, offset
2927 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2928 int64_t Register = 0;
2930 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2933 if (getLexer().isNot(AsmToken::Comma))
2934 return TokError("unexpected token in directive");
2938 if (parseAbsoluteExpression(Offset))
2941 getStreamer().EmitCFIRelOffset(Register, Offset);
2945 static bool isValidEncoding(int64_t Encoding) {
2946 if (Encoding & ~0xff)
2949 if (Encoding == dwarf::DW_EH_PE_omit)
2952 const unsigned Format = Encoding & 0xf;
2953 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2954 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2955 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2956 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2959 const unsigned Application = Encoding & 0x70;
2960 if (Application != dwarf::DW_EH_PE_absptr &&
2961 Application != dwarf::DW_EH_PE_pcrel)
2967 /// parseDirectiveCFIPersonalityOrLsda
2968 /// IsPersonality true for cfi_personality, false for cfi_lsda
2969 /// ::= .cfi_personality encoding, [symbol_name]
2970 /// ::= .cfi_lsda encoding, [symbol_name]
2971 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2972 int64_t Encoding = 0;
2973 if (parseAbsoluteExpression(Encoding))
2975 if (Encoding == dwarf::DW_EH_PE_omit)
2978 if (!isValidEncoding(Encoding))
2979 return TokError("unsupported encoding.");
2981 if (getLexer().isNot(AsmToken::Comma))
2982 return TokError("unexpected token in directive");
2986 if (parseIdentifier(Name))
2987 return TokError("expected identifier in directive");
2989 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2992 getStreamer().EmitCFIPersonality(Sym, Encoding);
2994 getStreamer().EmitCFILsda(Sym, Encoding);
2998 /// parseDirectiveCFIRememberState
2999 /// ::= .cfi_remember_state
3000 bool AsmParser::parseDirectiveCFIRememberState() {
3001 getStreamer().EmitCFIRememberState();
3005 /// parseDirectiveCFIRestoreState
3006 /// ::= .cfi_remember_state
3007 bool AsmParser::parseDirectiveCFIRestoreState() {
3008 getStreamer().EmitCFIRestoreState();
3012 /// parseDirectiveCFISameValue
3013 /// ::= .cfi_same_value register
3014 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3015 int64_t Register = 0;
3017 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3020 getStreamer().EmitCFISameValue(Register);
3024 /// parseDirectiveCFIRestore
3025 /// ::= .cfi_restore register
3026 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3027 int64_t Register = 0;
3028 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3031 getStreamer().EmitCFIRestore(Register);
3035 /// parseDirectiveCFIEscape
3036 /// ::= .cfi_escape expression[,...]
3037 bool AsmParser::parseDirectiveCFIEscape() {
3040 if (parseAbsoluteExpression(CurrValue))
3043 Values.push_back((uint8_t)CurrValue);
3045 while (getLexer().is(AsmToken::Comma)) {
3048 if (parseAbsoluteExpression(CurrValue))
3051 Values.push_back((uint8_t)CurrValue);
3054 getStreamer().EmitCFIEscape(Values);
3058 /// parseDirectiveCFISignalFrame
3059 /// ::= .cfi_signal_frame
3060 bool AsmParser::parseDirectiveCFISignalFrame() {
3061 if (getLexer().isNot(AsmToken::EndOfStatement))
3062 return Error(getLexer().getLoc(),
3063 "unexpected token in '.cfi_signal_frame'");
3065 getStreamer().EmitCFISignalFrame();
3069 /// parseDirectiveCFIUndefined
3070 /// ::= .cfi_undefined register
3071 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3072 int64_t Register = 0;
3074 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3077 getStreamer().EmitCFIUndefined(Register);
3081 /// parseDirectiveMacrosOnOff
3084 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3085 if (getLexer().isNot(AsmToken::EndOfStatement))
3086 return Error(getLexer().getLoc(),
3087 "unexpected token in '" + Directive + "' directive");
3089 setMacrosEnabled(Directive == ".macros_on");
3093 /// parseDirectiveMacro
3094 /// ::= .macro name [parameters]
3095 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3097 if (parseIdentifier(Name))
3098 return TokError("expected identifier in '.macro' directive");
3100 MCAsmMacroParameters Parameters;
3101 // Argument delimiter is initially unknown. It will be set by
3102 // parseMacroArgument()
3103 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3104 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3106 MCAsmMacroParameter Parameter;
3107 if (parseIdentifier(Parameter.first))
3108 return TokError("expected identifier in '.macro' directive");
3110 if (getLexer().is(AsmToken::Equal)) {
3112 if (parseMacroArgument(Parameter.second, ArgumentDelimiter))
3116 Parameters.push_back(Parameter);
3118 if (getLexer().is(AsmToken::Comma))
3120 else if (getLexer().is(AsmToken::EndOfStatement))
3125 // Eat the end of statement.
3128 AsmToken EndToken, StartToken = getTok();
3130 // Lex the macro definition.
3132 // Check whether we have reached the end of the file.
3133 if (getLexer().is(AsmToken::Eof))
3134 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3136 // Otherwise, check whether we have reach the .endmacro.
3137 if (getLexer().is(AsmToken::Identifier) &&
3138 (getTok().getIdentifier() == ".endm" ||
3139 getTok().getIdentifier() == ".endmacro")) {
3140 EndToken = getTok();
3142 if (getLexer().isNot(AsmToken::EndOfStatement))
3143 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3148 // Otherwise, scan til the end of the statement.
3149 eatToEndOfStatement();
3152 if (lookupMacro(Name)) {
3153 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3156 const char *BodyStart = StartToken.getLoc().getPointer();
3157 const char *BodyEnd = EndToken.getLoc().getPointer();
3158 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3159 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3160 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3164 /// checkForBadMacro
3166 /// With the support added for named parameters there may be code out there that
3167 /// is transitioning from positional parameters. In versions of gas that did
3168 /// not support named parameters they would be ignored on the macro definition.
3169 /// But to support both styles of parameters this is not possible so if a macro
3170 /// definition has named parameters but does not use them and has what appears
3171 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3172 /// warning that the positional parameter found in body which have no effect.
3173 /// Hoping the developer will either remove the named parameters from the macro
3174 /// definition so the positional parameters get used if that was what was
3175 /// intended or change the macro to use the named parameters. It is possible
3176 /// this warning will trigger when the none of the named parameters are used
3177 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3178 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3180 MCAsmMacroParameters Parameters) {
3181 // If this macro is not defined with named parameters the warning we are
3182 // checking for here doesn't apply.
3183 unsigned NParameters = Parameters.size();
3184 if (NParameters == 0)
3187 bool NamedParametersFound = false;
3188 bool PositionalParametersFound = false;
3190 // Look at the body of the macro for use of both the named parameters and what
3191 // are likely to be positional parameters. This is what expandMacro() is
3192 // doing when it finds the parameters in the body.
3193 while (!Body.empty()) {
3194 // Scan for the next possible parameter.
3195 std::size_t End = Body.size(), Pos = 0;
3196 for (; Pos != End; ++Pos) {
3197 // Check for a substitution or escape.
3198 // This macro is defined with parameters, look for \foo, \bar, etc.
3199 if (Body[Pos] == '\\' && Pos + 1 != End)
3202 // This macro should have parameters, but look for $0, $1, ..., $n too.
3203 if (Body[Pos] != '$' || Pos + 1 == End)
3205 char Next = Body[Pos + 1];
3206 if (Next == '$' || Next == 'n' ||
3207 isdigit(static_cast<unsigned char>(Next)))
3211 // Check if we reached the end.
3215 if (Body[Pos] == '$') {
3216 switch (Body[Pos + 1]) {
3221 // $n => number of arguments
3223 PositionalParametersFound = true;
3226 // $[0-9] => argument
3228 PositionalParametersFound = true;
3234 unsigned I = Pos + 1;
3235 while (isIdentifierChar(Body[I]) && I + 1 != End)
3238 const char *Begin = Body.data() + Pos + 1;
3239 StringRef Argument(Begin, I - (Pos + 1));
3241 for (; Index < NParameters; ++Index)
3242 if (Parameters[Index].first == Argument)
3245 if (Index == NParameters) {
3246 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3252 NamedParametersFound = true;
3253 Pos += 1 + Argument.size();
3256 // Update the scan point.
3257 Body = Body.substr(Pos);
3260 if (!NamedParametersFound && PositionalParametersFound)
3261 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3262 "used in macro body, possible positional parameter "
3263 "found in body which will have no effect");
3266 /// parseDirectiveEndMacro
3269 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3270 if (getLexer().isNot(AsmToken::EndOfStatement))
3271 return TokError("unexpected token in '" + Directive + "' directive");
3273 // If we are inside a macro instantiation, terminate the current
3275 if (isInsideMacroInstantiation()) {
3280 // Otherwise, this .endmacro is a stray entry in the file; well formed
3281 // .endmacro directives are handled during the macro definition parsing.
3282 return TokError("unexpected '" + Directive + "' in file, "
3283 "no current macro definition");
3286 /// parseDirectivePurgeMacro
3288 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3290 if (parseIdentifier(Name))
3291 return TokError("expected identifier in '.purgem' directive");
3293 if (getLexer().isNot(AsmToken::EndOfStatement))
3294 return TokError("unexpected token in '.purgem' directive");
3296 if (!lookupMacro(Name))
3297 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3299 undefineMacro(Name);
3303 /// parseDirectiveBundleAlignMode
3304 /// ::= {.bundle_align_mode} expression
3305 bool AsmParser::parseDirectiveBundleAlignMode() {
3306 checkForValidSection();
3308 // Expect a single argument: an expression that evaluates to a constant
3309 // in the inclusive range 0-30.
3310 SMLoc ExprLoc = getLexer().getLoc();
3311 int64_t AlignSizePow2;
3312 if (parseAbsoluteExpression(AlignSizePow2))
3314 else if (getLexer().isNot(AsmToken::EndOfStatement))
3315 return TokError("unexpected token after expression in"
3316 " '.bundle_align_mode' directive");
3317 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3318 return Error(ExprLoc,
3319 "invalid bundle alignment size (expected between 0 and 30)");
3323 // Because of AlignSizePow2's verified range we can safely truncate it to
3325 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3329 /// parseDirectiveBundleLock
3330 /// ::= {.bundle_lock} [align_to_end]
3331 bool AsmParser::parseDirectiveBundleLock() {
3332 checkForValidSection();
3333 bool AlignToEnd = false;
3335 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3337 SMLoc Loc = getTok().getLoc();
3338 const char *kInvalidOptionError =
3339 "invalid option for '.bundle_lock' directive";
3341 if (parseIdentifier(Option))
3342 return Error(Loc, kInvalidOptionError);
3344 if (Option != "align_to_end")
3345 return Error(Loc, kInvalidOptionError);
3346 else if (getLexer().isNot(AsmToken::EndOfStatement))
3348 "unexpected token after '.bundle_lock' directive option");
3354 getStreamer().EmitBundleLock(AlignToEnd);
3358 /// parseDirectiveBundleLock
3359 /// ::= {.bundle_lock}
3360 bool AsmParser::parseDirectiveBundleUnlock() {
3361 checkForValidSection();
3363 if (getLexer().isNot(AsmToken::EndOfStatement))
3364 return TokError("unexpected token in '.bundle_unlock' directive");
3367 getStreamer().EmitBundleUnlock();
3371 /// parseDirectiveSpace
3372 /// ::= (.skip | .space) expression [ , expression ]
3373 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3374 checkForValidSection();
3377 if (parseAbsoluteExpression(NumBytes))
3380 int64_t FillExpr = 0;
3381 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3382 if (getLexer().isNot(AsmToken::Comma))
3383 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3386 if (parseAbsoluteExpression(FillExpr))
3389 if (getLexer().isNot(AsmToken::EndOfStatement))
3390 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3396 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3399 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3400 getStreamer().EmitFill(NumBytes, FillExpr);
3405 /// parseDirectiveLEB128
3406 /// ::= (.sleb128 | .uleb128) expression
3407 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3408 checkForValidSection();
3409 const MCExpr *Value;
3411 if (parseExpression(Value))
3414 if (getLexer().isNot(AsmToken::EndOfStatement))
3415 return TokError("unexpected token in directive");
3418 getStreamer().EmitSLEB128Value(Value);
3420 getStreamer().EmitULEB128Value(Value);
3425 /// parseDirectiveSymbolAttribute
3426 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3427 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3428 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3431 SMLoc Loc = getTok().getLoc();
3433 if (parseIdentifier(Name))
3434 return Error(Loc, "expected identifier in directive");
3436 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3438 // Assembler local symbols don't make any sense here. Complain loudly.
3439 if (Sym->isTemporary())
3440 return Error(Loc, "non-local symbol required in directive");
3442 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3443 return Error(Loc, "unable to emit symbol attribute");
3445 if (getLexer().is(AsmToken::EndOfStatement))
3448 if (getLexer().isNot(AsmToken::Comma))
3449 return TokError("unexpected token in directive");
3458 /// parseDirectiveComm
3459 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3460 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3461 checkForValidSection();
3463 SMLoc IDLoc = getLexer().getLoc();
3465 if (parseIdentifier(Name))
3466 return TokError("expected identifier in directive");
3468 // Handle the identifier as the key symbol.
3469 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3471 if (getLexer().isNot(AsmToken::Comma))
3472 return TokError("unexpected token in directive");
3476 SMLoc SizeLoc = getLexer().getLoc();
3477 if (parseAbsoluteExpression(Size))
3480 int64_t Pow2Alignment = 0;
3481 SMLoc Pow2AlignmentLoc;
3482 if (getLexer().is(AsmToken::Comma)) {
3484 Pow2AlignmentLoc = getLexer().getLoc();
3485 if (parseAbsoluteExpression(Pow2Alignment))
3488 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3489 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3490 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3492 // If this target takes alignments in bytes (not log) validate and convert.
3493 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3494 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3495 if (!isPowerOf2_64(Pow2Alignment))
3496 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3497 Pow2Alignment = Log2_64(Pow2Alignment);
3501 if (getLexer().isNot(AsmToken::EndOfStatement))
3502 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3506 // NOTE: a size of zero for a .comm should create a undefined symbol
3507 // but a size of .lcomm creates a bss symbol of size zero.
3509 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3510 "be less than zero");
3512 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3513 // may internally end up wanting an alignment in bytes.
3514 // FIXME: Diagnose overflow.
3515 if (Pow2Alignment < 0)
3516 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3517 "alignment, can't be less than zero");
3519 if (!Sym->isUndefined())
3520 return Error(IDLoc, "invalid symbol redefinition");
3522 // Create the Symbol as a common or local common with Size and Pow2Alignment
3524 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3528 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3532 /// parseDirectiveAbort
3533 /// ::= .abort [... message ...]
3534 bool AsmParser::parseDirectiveAbort() {
3535 // FIXME: Use loc from directive.
3536 SMLoc Loc = getLexer().getLoc();
3538 StringRef Str = parseStringToEndOfStatement();
3539 if (getLexer().isNot(AsmToken::EndOfStatement))
3540 return TokError("unexpected token in '.abort' directive");
3545 Error(Loc, ".abort detected. Assembly stopping.");
3547 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3548 // FIXME: Actually abort assembly here.
3553 /// parseDirectiveInclude
3554 /// ::= .include "filename"
3555 bool AsmParser::parseDirectiveInclude() {
3556 if (getLexer().isNot(AsmToken::String))
3557 return TokError("expected string in '.include' directive");
3559 // Allow the strings to have escaped octal character sequence.
3560 std::string Filename;
3561 if (parseEscapedString(Filename))
3563 SMLoc IncludeLoc = getLexer().getLoc();
3566 if (getLexer().isNot(AsmToken::EndOfStatement))
3567 return TokError("unexpected token in '.include' directive");
3569 // Attempt to switch the lexer to the included file before consuming the end
3570 // of statement to avoid losing it when we switch.
3571 if (enterIncludeFile(Filename)) {
3572 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3579 /// parseDirectiveIncbin
3580 /// ::= .incbin "filename"
3581 bool AsmParser::parseDirectiveIncbin() {
3582 if (getLexer().isNot(AsmToken::String))
3583 return TokError("expected string in '.incbin' directive");
3585 // Allow the strings to have escaped octal character sequence.
3586 std::string Filename;
3587 if (parseEscapedString(Filename))
3589 SMLoc IncbinLoc = getLexer().getLoc();
3592 if (getLexer().isNot(AsmToken::EndOfStatement))
3593 return TokError("unexpected token in '.incbin' directive");
3595 // Attempt to process the included file.
3596 if (processIncbinFile(Filename)) {
3597 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3604 /// parseDirectiveIf
3605 /// ::= .if expression
3606 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3607 TheCondStack.push_back(TheCondState);
3608 TheCondState.TheCond = AsmCond::IfCond;
3609 if (TheCondState.Ignore) {
3610 eatToEndOfStatement();
3613 if (parseAbsoluteExpression(ExprValue))
3616 if (getLexer().isNot(AsmToken::EndOfStatement))
3617 return TokError("unexpected token in '.if' directive");
3621 TheCondState.CondMet = ExprValue;
3622 TheCondState.Ignore = !TheCondState.CondMet;
3628 /// parseDirectiveIfb
3630 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3631 TheCondStack.push_back(TheCondState);
3632 TheCondState.TheCond = AsmCond::IfCond;
3634 if (TheCondState.Ignore) {
3635 eatToEndOfStatement();
3637 StringRef Str = parseStringToEndOfStatement();
3639 if (getLexer().isNot(AsmToken::EndOfStatement))
3640 return TokError("unexpected token in '.ifb' directive");
3644 TheCondState.CondMet = ExpectBlank == Str.empty();
3645 TheCondState.Ignore = !TheCondState.CondMet;
3651 /// parseDirectiveIfc
3652 /// ::= .ifc string1, string2
3653 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3654 TheCondStack.push_back(TheCondState);
3655 TheCondState.TheCond = AsmCond::IfCond;
3657 if (TheCondState.Ignore) {
3658 eatToEndOfStatement();
3660 StringRef Str1 = parseStringToComma();
3662 if (getLexer().isNot(AsmToken::Comma))
3663 return TokError("unexpected token in '.ifc' directive");
3667 StringRef Str2 = parseStringToEndOfStatement();
3669 if (getLexer().isNot(AsmToken::EndOfStatement))
3670 return TokError("unexpected token in '.ifc' directive");
3674 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3675 TheCondState.Ignore = !TheCondState.CondMet;
3681 /// parseDirectiveIfdef
3682 /// ::= .ifdef symbol
3683 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3685 TheCondStack.push_back(TheCondState);
3686 TheCondState.TheCond = AsmCond::IfCond;
3688 if (TheCondState.Ignore) {
3689 eatToEndOfStatement();
3691 if (parseIdentifier(Name))
3692 return TokError("expected identifier after '.ifdef'");
3696 MCSymbol *Sym = getContext().LookupSymbol(Name);
3699 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3701 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3702 TheCondState.Ignore = !TheCondState.CondMet;
3708 /// parseDirectiveElseIf
3709 /// ::= .elseif expression
3710 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3711 if (TheCondState.TheCond != AsmCond::IfCond &&
3712 TheCondState.TheCond != AsmCond::ElseIfCond)
3713 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3715 TheCondState.TheCond = AsmCond::ElseIfCond;
3717 bool LastIgnoreState = false;
3718 if (!TheCondStack.empty())
3719 LastIgnoreState = TheCondStack.back().Ignore;
3720 if (LastIgnoreState || TheCondState.CondMet) {
3721 TheCondState.Ignore = true;
3722 eatToEndOfStatement();
3725 if (parseAbsoluteExpression(ExprValue))
3728 if (getLexer().isNot(AsmToken::EndOfStatement))
3729 return TokError("unexpected token in '.elseif' directive");
3732 TheCondState.CondMet = ExprValue;
3733 TheCondState.Ignore = !TheCondState.CondMet;
3739 /// parseDirectiveElse
3741 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3742 if (getLexer().isNot(AsmToken::EndOfStatement))
3743 return TokError("unexpected token in '.else' directive");
3747 if (TheCondState.TheCond != AsmCond::IfCond &&
3748 TheCondState.TheCond != AsmCond::ElseIfCond)
3749 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3751 TheCondState.TheCond = AsmCond::ElseCond;
3752 bool LastIgnoreState = false;
3753 if (!TheCondStack.empty())
3754 LastIgnoreState = TheCondStack.back().Ignore;
3755 if (LastIgnoreState || TheCondState.CondMet)
3756 TheCondState.Ignore = true;
3758 TheCondState.Ignore = false;
3763 /// parseDirectiveEnd
3765 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
3766 if (getLexer().isNot(AsmToken::EndOfStatement))
3767 return TokError("unexpected token in '.end' directive");
3771 while (Lexer.isNot(AsmToken::Eof))
3777 /// parseDirectiveEndIf
3779 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
3780 if (getLexer().isNot(AsmToken::EndOfStatement))
3781 return TokError("unexpected token in '.endif' directive");
3785 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
3786 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3788 if (!TheCondStack.empty()) {
3789 TheCondState = TheCondStack.back();
3790 TheCondStack.pop_back();
3796 void AsmParser::initializeDirectiveKindMap() {
3797 DirectiveKindMap[".set"] = DK_SET;
3798 DirectiveKindMap[".equ"] = DK_EQU;
3799 DirectiveKindMap[".equiv"] = DK_EQUIV;
3800 DirectiveKindMap[".ascii"] = DK_ASCII;
3801 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3802 DirectiveKindMap[".string"] = DK_STRING;
3803 DirectiveKindMap[".byte"] = DK_BYTE;
3804 DirectiveKindMap[".short"] = DK_SHORT;
3805 DirectiveKindMap[".value"] = DK_VALUE;
3806 DirectiveKindMap[".2byte"] = DK_2BYTE;
3807 DirectiveKindMap[".long"] = DK_LONG;
3808 DirectiveKindMap[".int"] = DK_INT;
3809 DirectiveKindMap[".4byte"] = DK_4BYTE;
3810 DirectiveKindMap[".quad"] = DK_QUAD;
3811 DirectiveKindMap[".8byte"] = DK_8BYTE;
3812 DirectiveKindMap[".single"] = DK_SINGLE;
3813 DirectiveKindMap[".float"] = DK_FLOAT;
3814 DirectiveKindMap[".double"] = DK_DOUBLE;
3815 DirectiveKindMap[".align"] = DK_ALIGN;
3816 DirectiveKindMap[".align32"] = DK_ALIGN32;
3817 DirectiveKindMap[".balign"] = DK_BALIGN;
3818 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3819 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3820 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3821 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3822 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3823 DirectiveKindMap[".org"] = DK_ORG;
3824 DirectiveKindMap[".fill"] = DK_FILL;
3825 DirectiveKindMap[".zero"] = DK_ZERO;
3826 DirectiveKindMap[".extern"] = DK_EXTERN;
3827 DirectiveKindMap[".globl"] = DK_GLOBL;
3828 DirectiveKindMap[".global"] = DK_GLOBAL;
3829 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3830 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3831 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3832 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3833 DirectiveKindMap[".reference"] = DK_REFERENCE;
3834 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3835 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3836 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3837 DirectiveKindMap[".comm"] = DK_COMM;
3838 DirectiveKindMap[".common"] = DK_COMMON;
3839 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3840 DirectiveKindMap[".abort"] = DK_ABORT;
3841 DirectiveKindMap[".include"] = DK_INCLUDE;
3842 DirectiveKindMap[".incbin"] = DK_INCBIN;
3843 DirectiveKindMap[".code16"] = DK_CODE16;
3844 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3845 DirectiveKindMap[".rept"] = DK_REPT;
3846 DirectiveKindMap[".rep"] = DK_REPT;
3847 DirectiveKindMap[".irp"] = DK_IRP;
3848 DirectiveKindMap[".irpc"] = DK_IRPC;
3849 DirectiveKindMap[".endr"] = DK_ENDR;
3850 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3851 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3852 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3853 DirectiveKindMap[".if"] = DK_IF;
3854 DirectiveKindMap[".ifb"] = DK_IFB;
3855 DirectiveKindMap[".ifnb"] = DK_IFNB;
3856 DirectiveKindMap[".ifc"] = DK_IFC;
3857 DirectiveKindMap[".ifnc"] = DK_IFNC;
3858 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3859 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3860 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3861 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3862 DirectiveKindMap[".else"] = DK_ELSE;
3863 DirectiveKindMap[".end"] = DK_END;
3864 DirectiveKindMap[".endif"] = DK_ENDIF;
3865 DirectiveKindMap[".skip"] = DK_SKIP;
3866 DirectiveKindMap[".space"] = DK_SPACE;
3867 DirectiveKindMap[".file"] = DK_FILE;
3868 DirectiveKindMap[".line"] = DK_LINE;
3869 DirectiveKindMap[".loc"] = DK_LOC;
3870 DirectiveKindMap[".stabs"] = DK_STABS;
3871 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3872 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3873 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3874 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3875 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3876 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3877 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3878 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3879 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3880 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3881 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3882 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3883 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3884 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3885 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3886 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3887 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3888 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3889 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3890 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3891 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3892 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
3893 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3894 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3895 DirectiveKindMap[".macro"] = DK_MACRO;
3896 DirectiveKindMap[".endm"] = DK_ENDM;
3897 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3898 DirectiveKindMap[".purgem"] = DK_PURGEM;
3901 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
3902 AsmToken EndToken, StartToken = getTok();
3904 unsigned NestLevel = 0;
3906 // Check whether we have reached the end of the file.
3907 if (getLexer().is(AsmToken::Eof)) {
3908 Error(DirectiveLoc, "no matching '.endr' in definition");
3912 if (Lexer.is(AsmToken::Identifier) &&
3913 (getTok().getIdentifier() == ".rept")) {
3917 // Otherwise, check whether we have reached the .endr.
3918 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
3919 if (NestLevel == 0) {
3920 EndToken = getTok();
3922 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3923 TokError("unexpected token in '.endr' directive");
3931 // Otherwise, scan till the end of the statement.
3932 eatToEndOfStatement();
3935 const char *BodyStart = StartToken.getLoc().getPointer();
3936 const char *BodyEnd = EndToken.getLoc().getPointer();
3937 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3939 // We Are Anonymous.
3941 MCAsmMacroParameters Parameters;
3942 MacroLikeBodies.push_back(MCAsmMacro(Name, Body, Parameters));
3943 return &MacroLikeBodies.back();
3946 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
3947 raw_svector_ostream &OS) {
3950 MemoryBuffer *Instantiation =
3951 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3953 // Create the macro instantiation object and add to the current macro
3954 // instantiation stack.
3955 MacroInstantiation *MI = new MacroInstantiation(
3956 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
3957 ActiveMacros.push_back(MI);
3959 // Jump to the macro instantiation and prime the lexer.
3960 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3961 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3965 /// parseDirectiveRept
3966 /// ::= .rep | .rept count
3967 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
3968 const MCExpr *CountExpr;
3969 SMLoc CountLoc = getTok().getLoc();
3970 if (parseExpression(CountExpr))
3974 if (!CountExpr->EvaluateAsAbsolute(Count)) {
3975 eatToEndOfStatement();
3976 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
3980 return Error(CountLoc, "Count is negative");
3982 if (Lexer.isNot(AsmToken::EndOfStatement))
3983 return TokError("unexpected token in '" + Dir + "' directive");
3985 // Eat the end of statement.
3988 // Lex the rept definition.
3989 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
3993 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3994 // to hold the macro body with substitutions.
3995 SmallString<256> Buf;
3996 MCAsmMacroParameters Parameters;
3997 MCAsmMacroArguments A;
3998 raw_svector_ostream OS(Buf);
4000 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
4003 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4008 /// parseDirectiveIrp
4009 /// ::= .irp symbol,values
4010 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4011 MCAsmMacroParameters Parameters;
4012 MCAsmMacroParameter Parameter;
4014 if (parseIdentifier(Parameter.first))
4015 return TokError("expected identifier in '.irp' directive");
4017 Parameters.push_back(Parameter);
4019 if (Lexer.isNot(AsmToken::Comma))
4020 return TokError("expected comma in '.irp' directive");
4024 MCAsmMacroArguments A;
4025 if (parseMacroArguments(0, A))
4028 // Eat the end of statement.
4031 // Lex the irp definition.
4032 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4036 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4037 // to hold the macro body with substitutions.
4038 SmallString<256> Buf;
4039 raw_svector_ostream OS(Buf);
4041 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4042 MCAsmMacroArguments Args;
4045 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4049 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4054 /// parseDirectiveIrpc
4055 /// ::= .irpc symbol,values
4056 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4057 MCAsmMacroParameters Parameters;
4058 MCAsmMacroParameter Parameter;
4060 if (parseIdentifier(Parameter.first))
4061 return TokError("expected identifier in '.irpc' directive");
4063 Parameters.push_back(Parameter);
4065 if (Lexer.isNot(AsmToken::Comma))
4066 return TokError("expected comma in '.irpc' directive");
4070 MCAsmMacroArguments A;
4071 if (parseMacroArguments(0, A))
4074 if (A.size() != 1 || A.front().size() != 1)
4075 return TokError("unexpected token in '.irpc' directive");
4077 // Eat the end of statement.
4080 // Lex the irpc definition.
4081 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4085 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4086 // to hold the macro body with substitutions.
4087 SmallString<256> Buf;
4088 raw_svector_ostream OS(Buf);
4090 StringRef Values = A.front().front().getString();
4091 std::size_t I, End = Values.size();
4092 for (I = 0; I < End; ++I) {
4093 MCAsmMacroArgument Arg;
4094 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4096 MCAsmMacroArguments Args;
4097 Args.push_back(Arg);
4099 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4103 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4108 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4109 if (ActiveMacros.empty())
4110 return TokError("unmatched '.endr' directive");
4112 // The only .repl that should get here are the ones created by
4113 // instantiateMacroLikeBody.
4114 assert(getLexer().is(AsmToken::EndOfStatement));
4120 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4122 const MCExpr *Value;
4123 SMLoc ExprLoc = getLexer().getLoc();
4124 if (parseExpression(Value))
4126 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4128 return Error(ExprLoc, "unexpected expression in _emit");
4129 uint64_t IntValue = MCE->getValue();
4130 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4131 return Error(ExprLoc, "literal value out of range for directive");
4133 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4137 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4138 const MCExpr *Value;
4139 SMLoc ExprLoc = getLexer().getLoc();
4140 if (parseExpression(Value))
4142 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4144 return Error(ExprLoc, "unexpected expression in align");
4145 uint64_t IntValue = MCE->getValue();
4146 if (!isPowerOf2_64(IntValue))
4147 return Error(ExprLoc, "literal value not a power of two greater then zero");
4149 Info.AsmRewrites->push_back(
4150 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4154 // We are comparing pointers, but the pointers are relative to a single string.
4155 // Thus, this should always be deterministic.
4156 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4157 const AsmRewrite *AsmRewriteB) {
4158 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4160 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4163 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4164 // rewrite to the same location. Make sure the SizeDirective rewrite is
4165 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4166 // ensures the sort algorithm is stable.
4167 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4168 AsmRewritePrecedence[AsmRewriteB->Kind])
4171 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4172 AsmRewritePrecedence[AsmRewriteB->Kind])
4174 llvm_unreachable("Unstable rewrite sort.");
4177 bool AsmParser::parseMSInlineAsm(
4178 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4179 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4180 SmallVectorImpl<std::string> &Constraints,
4181 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4182 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4183 SmallVector<void *, 4> InputDecls;
4184 SmallVector<void *, 4> OutputDecls;
4185 SmallVector<bool, 4> InputDeclsAddressOf;
4186 SmallVector<bool, 4> OutputDeclsAddressOf;
4187 SmallVector<std::string, 4> InputConstraints;
4188 SmallVector<std::string, 4> OutputConstraints;
4189 SmallVector<unsigned, 4> ClobberRegs;
4191 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4196 // While we have input, parse each statement.
4197 unsigned InputIdx = 0;
4198 unsigned OutputIdx = 0;
4199 while (getLexer().isNot(AsmToken::Eof)) {
4200 ParseStatementInfo Info(&AsmStrRewrites);
4201 if (parseStatement(Info))
4204 if (Info.ParseError)
4207 if (Info.Opcode == ~0U)
4210 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4212 // Build the list of clobbers, outputs and inputs.
4213 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4214 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4217 if (Operand->isImm())
4220 // Register operand.
4221 if (Operand->isReg() && !Operand->needAddressOf()) {
4222 unsigned NumDefs = Desc.getNumDefs();
4224 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4225 ClobberRegs.push_back(Operand->getReg());
4229 // Expr/Input or Output.
4230 StringRef SymName = Operand->getSymName();
4231 if (SymName.empty())
4234 void *OpDecl = Operand->getOpDecl();
4238 bool isOutput = (i == 1) && Desc.mayStore();
4239 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4242 OutputDecls.push_back(OpDecl);
4243 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4244 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4245 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4247 InputDecls.push_back(OpDecl);
4248 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4249 InputConstraints.push_back(Operand->getConstraint().str());
4250 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4254 // Consider implicit defs to be clobbers. Think of cpuid and push.
4255 const uint16_t *ImpDefs = Desc.getImplicitDefs();
4256 for (unsigned I = 0, E = Desc.getNumImplicitDefs(); I != E; ++I)
4257 ClobberRegs.push_back(ImpDefs[I]);
4260 // Set the number of Outputs and Inputs.
4261 NumOutputs = OutputDecls.size();
4262 NumInputs = InputDecls.size();
4264 // Set the unique clobbers.
4265 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4266 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4268 Clobbers.assign(ClobberRegs.size(), std::string());
4269 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4270 raw_string_ostream OS(Clobbers[I]);
4271 IP->printRegName(OS, ClobberRegs[I]);
4274 // Merge the various outputs and inputs. Output are expected first.
4275 if (NumOutputs || NumInputs) {
4276 unsigned NumExprs = NumOutputs + NumInputs;
4277 OpDecls.resize(NumExprs);
4278 Constraints.resize(NumExprs);
4279 for (unsigned i = 0; i < NumOutputs; ++i) {
4280 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4281 Constraints[i] = OutputConstraints[i];
4283 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4284 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4285 Constraints[j] = InputConstraints[i];
4289 // Build the IR assembly string.
4290 std::string AsmStringIR;
4291 raw_string_ostream OS(AsmStringIR);
4292 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4293 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4294 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4295 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4296 E = AsmStrRewrites.end();
4298 AsmRewriteKind Kind = (*I).Kind;
4299 if (Kind == AOK_Delete)
4302 const char *Loc = (*I).Loc.getPointer();
4303 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4305 // Emit everything up to the immediate/expression.
4306 unsigned Len = Loc - AsmStart;
4308 OS << StringRef(AsmStart, Len);
4310 // Skip the original expression.
4311 if (Kind == AOK_Skip) {
4312 AsmStart = Loc + (*I).Len;
4316 unsigned AdditionalSkip = 0;
4317 // Rewrite expressions in $N notation.
4322 OS << "$$" << (*I).Val;
4328 OS << '$' << InputIdx++;
4331 OS << '$' << OutputIdx++;
4333 case AOK_SizeDirective:
4336 case 8: OS << "byte ptr "; break;
4337 case 16: OS << "word ptr "; break;
4338 case 32: OS << "dword ptr "; break;
4339 case 64: OS << "qword ptr "; break;
4340 case 80: OS << "xword ptr "; break;
4341 case 128: OS << "xmmword ptr "; break;
4342 case 256: OS << "ymmword ptr "; break;
4349 unsigned Val = (*I).Val;
4350 OS << ".align " << Val;
4352 // Skip the original immediate.
4353 assert(Val < 10 && "Expected alignment less then 2^10.");
4354 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4357 case AOK_DotOperator:
4362 // Skip the original expression.
4363 AsmStart = Loc + (*I).Len + AdditionalSkip;
4366 // Emit the remainder of the asm string.
4367 if (AsmStart != AsmEnd)
4368 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4370 AsmString = OS.str();
4374 /// \brief Create an MCAsmParser instance.
4375 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4376 MCStreamer &Out, const MCAsmInfo &MAI) {
4377 return new AsmParser(SM, C, Out, MAI);