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/SmallString.h"
16 #include "llvm/ADT/STLExtras.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/MCParser/AsmCond.h"
26 #include "llvm/MC/MCParser/AsmLexer.h"
27 #include "llvm/MC/MCParser/MCAsmParser.h"
28 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
29 #include "llvm/MC/MCRegisterInfo.h"
30 #include "llvm/MC/MCSectionMachO.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/MC/MCTargetAsmParser.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/raw_ostream.h"
47 FatalAssemblerWarnings("fatal-assembler-warnings",
48 cl::desc("Consider warnings as error"));
50 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
54 /// \brief Helper types for tracking macro definitions.
55 typedef std::vector<AsmToken> MCAsmMacroArgument;
56 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
57 typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
58 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
63 MCAsmMacroParameters Parameters;
66 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
67 Name(N), Body(B), Parameters(P) {}
69 MCAsmMacro(const MCAsmMacro& Other)
70 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
73 /// \brief Helper class for storing information about an active macro
75 struct MacroInstantiation {
76 /// The macro being instantiated.
77 const MCAsmMacro *TheMacro;
79 /// The macro instantiation with substitutions.
80 MemoryBuffer *Instantiation;
82 /// The location of the instantiation.
83 SMLoc InstantiationLoc;
85 /// The buffer where parsing should resume upon instantiation completion.
88 /// The location where parsing should resume upon instantiation completion.
92 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
96 struct ParseStatementInfo {
97 /// ParsedOperands - The parsed operands from the last parsed statement.
98 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
100 /// Opcode - The opcode from the last parsed instruction.
103 /// Error - Was there an error parsing the inline assembly?
106 SmallVectorImpl<AsmRewrite> *AsmRewrites;
108 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
109 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
110 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
112 ~ParseStatementInfo() {
113 // Free any parsed operands.
114 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
115 delete ParsedOperands[i];
116 ParsedOperands.clear();
120 /// \brief The concrete assembly parser instance.
121 class AsmParser : public MCAsmParser {
122 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
123 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
128 const MCAsmInfo &MAI;
130 SourceMgr::DiagHandlerTy SavedDiagHandler;
131 void *SavedDiagContext;
132 MCAsmParserExtension *PlatformParser;
134 /// This is the current buffer index we're lexing from as managed by the
135 /// SourceMgr object.
138 AsmCond TheCondState;
139 std::vector<AsmCond> TheCondStack;
141 /// ExtensionDirectiveMap - maps directive names to handler methods in parser
142 /// extensions. Extensions register themselves in this map by calling
143 /// addDirectiveHandler.
144 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
146 /// MacroMap - Map of currently defined macros.
147 StringMap<MCAsmMacro*> MacroMap;
149 /// ActiveMacros - Stack of active macro instantiations.
150 std::vector<MacroInstantiation*> ActiveMacros;
152 /// Boolean tracking whether macro substitution is enabled.
153 unsigned MacrosEnabledFlag : 1;
155 /// Flag tracking whether any errors have been encountered.
156 unsigned HadError : 1;
158 /// The values from the last parsed cpp hash file line comment if any.
159 StringRef CppHashFilename;
160 int64_t CppHashLineNumber;
163 /// When generating dwarf for assembly source files we need to calculate the
164 /// logical line number based on the last parsed cpp hash file line comment
165 /// and current line. Since this is slow and messes up the SourceMgr's
166 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
167 SMLoc LastQueryIDLoc;
169 unsigned LastQueryLine;
171 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
172 unsigned AssemblerDialect;
174 /// IsDarwin - is Darwin compatibility enabled?
177 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
178 bool ParsingInlineAsm;
181 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
182 const MCAsmInfo &MAI);
183 virtual ~AsmParser();
185 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
187 virtual void addDirectiveHandler(StringRef Directive,
188 ExtensionDirectiveHandler Handler) {
189 ExtensionDirectiveMap[Directive] = Handler;
193 /// @name MCAsmParser Interface
196 virtual SourceMgr &getSourceManager() { return SrcMgr; }
197 virtual MCAsmLexer &getLexer() { return Lexer; }
198 virtual MCContext &getContext() { return Ctx; }
199 virtual MCStreamer &getStreamer() { return Out; }
200 virtual unsigned getAssemblerDialect() {
201 if (AssemblerDialect == ~0U)
202 return MAI.getAssemblerDialect();
204 return AssemblerDialect;
206 virtual void setAssemblerDialect(unsigned i) {
207 AssemblerDialect = i;
210 virtual bool Warning(SMLoc L, const Twine &Msg,
211 ArrayRef<SMRange> Ranges = None);
212 virtual bool Error(SMLoc L, const Twine &Msg,
213 ArrayRef<SMRange> Ranges = None);
215 virtual const AsmToken &Lex();
217 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
218 bool isParsingInlineAsm() { return ParsingInlineAsm; }
220 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
221 unsigned &NumOutputs, unsigned &NumInputs,
222 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
223 SmallVectorImpl<std::string> &Constraints,
224 SmallVectorImpl<std::string> &Clobbers,
225 const MCInstrInfo *MII,
226 const MCInstPrinter *IP,
227 MCAsmParserSemaCallback &SI);
229 bool parseExpression(const MCExpr *&Res);
230 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
231 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
232 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
233 virtual bool parseAbsoluteExpression(int64_t &Res);
235 /// parseIdentifier - Parse an identifier or string (as a quoted identifier)
236 /// and set \p Res to the identifier contents.
237 virtual bool parseIdentifier(StringRef &Res);
238 virtual void eatToEndOfStatement();
240 virtual void checkForValidSection();
245 bool ParseStatement(ParseStatementInfo &Info);
246 void EatToEndOfLine();
247 bool ParseCppHashLineFilenameComment(const SMLoc &L);
249 void CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
250 MCAsmMacroParameters Parameters);
251 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
252 const MCAsmMacroParameters &Parameters,
253 const MCAsmMacroArguments &A,
256 /// \brief Are macros enabled in the parser?
257 bool MacrosEnabled() {return MacrosEnabledFlag;}
259 /// \brief Control a flag in the parser that enables or disables macros.
260 void SetMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
262 /// \brief Lookup a previously defined macro.
263 /// \param Name Macro name.
264 /// \returns Pointer to macro. NULL if no such macro was defined.
265 const MCAsmMacro* LookupMacro(StringRef Name);
267 /// \brief Define a new macro with the given name and information.
268 void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
270 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
271 void UndefineMacro(StringRef Name);
273 /// \brief Are we inside a macro instantiation?
274 bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
276 /// \brief Handle entry to macro instantiation.
278 /// \param M The macro.
279 /// \param NameLoc Instantiation location.
280 bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
282 /// \brief Handle exit from macro instantiation.
283 void HandleMacroExit();
285 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
286 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
287 /// correct delimiter by the method.
288 bool ParseMacroArgument(MCAsmMacroArgument &MA,
289 AsmToken::TokenKind &ArgumentDelimiter);
291 /// \brief Parse all macro arguments for a given macro.
292 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
294 void PrintMacroInstantiations();
295 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
296 ArrayRef<SMRange> Ranges = None) const {
297 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
299 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
301 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
302 bool EnterIncludeFile(const std::string &Filename);
303 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
304 /// This returns true on failure.
305 bool ProcessIncbinFile(const std::string &Filename);
307 /// \brief Reset the current lexer position to that given by \p Loc. The
308 /// current token is not set; clients should ensure Lex() is called
311 /// \param InBuffer If not -1, should be the known buffer id that contains the
313 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
315 /// \brief Parse up to the end of statement and a return the contents from the
316 /// current token until the end of the statement; the current token on exit
317 /// will be either the EndOfStatement or EOF.
318 virtual StringRef parseStringToEndOfStatement();
320 /// \brief Parse until the end of a statement or a comma is encountered,
321 /// return the contents from the current token up to the end or comma.
322 StringRef ParseStringToComma();
324 bool ParseAssignment(StringRef Name, bool allow_redef,
325 bool NoDeadStrip = false);
327 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
328 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
329 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
330 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
332 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
334 // Generic (target and platform independent) directive parsing.
336 DK_NO_DIRECTIVE, // Placeholder
337 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
338 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
339 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
340 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
341 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
342 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
343 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
344 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
345 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
346 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
347 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
348 DK_ELSEIF, DK_ELSE, DK_ENDIF,
349 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
350 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
351 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
352 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
353 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
354 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
356 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
357 DK_SLEB128, DK_ULEB128
360 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
361 /// directives parsed by this class.
362 StringMap<DirectiveKind> DirectiveKindMap;
364 // ".ascii", ".asciz", ".string"
365 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
366 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
367 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
368 bool ParseDirectiveFill(); // ".fill"
369 bool ParseDirectiveZero(); // ".zero"
370 // ".set", ".equ", ".equiv"
371 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
372 bool ParseDirectiveOrg(); // ".org"
373 // ".align{,32}", ".p2align{,w,l}"
374 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
376 // ".file", ".line", ".loc", ".stabs"
377 bool ParseDirectiveFile(SMLoc DirectiveLoc);
378 bool ParseDirectiveLine();
379 bool ParseDirectiveLoc();
380 bool ParseDirectiveStabs();
383 bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
384 bool ParseDirectiveCFISections();
385 bool ParseDirectiveCFIStartProc();
386 bool ParseDirectiveCFIEndProc();
387 bool ParseDirectiveCFIDefCfaOffset();
388 bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
389 bool ParseDirectiveCFIAdjustCfaOffset();
390 bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
391 bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
392 bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
393 bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
394 bool ParseDirectiveCFIRememberState();
395 bool ParseDirectiveCFIRestoreState();
396 bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
397 bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
398 bool ParseDirectiveCFIEscape();
399 bool ParseDirectiveCFISignalFrame();
400 bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
403 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
404 bool ParseDirectiveEndMacro(StringRef Directive);
405 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
406 bool ParseDirectiveMacrosOnOff(StringRef Directive);
408 // ".bundle_align_mode"
409 bool ParseDirectiveBundleAlignMode();
411 bool ParseDirectiveBundleLock();
413 bool ParseDirectiveBundleUnlock();
416 bool ParseDirectiveSpace(StringRef IDVal);
418 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
419 bool ParseDirectiveLEB128(bool Signed);
421 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
422 /// accepts a single symbol (which should be a label or an external).
423 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
425 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
427 bool ParseDirectiveAbort(); // ".abort"
428 bool ParseDirectiveInclude(); // ".include"
429 bool ParseDirectiveIncbin(); // ".incbin"
431 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
432 // ".ifb" or ".ifnb", depending on ExpectBlank.
433 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
434 // ".ifc" or ".ifnc", depending on ExpectEqual.
435 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
436 // ".ifdef" or ".ifndef", depending on expect_defined
437 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
438 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
439 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
440 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
441 virtual bool parseEscapedString(std::string &Data);
443 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
444 MCSymbolRefExpr::VariantKind Variant);
446 // Macro-like directives
447 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
448 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
449 raw_svector_ostream &OS);
450 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
451 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
452 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
453 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
455 // "_emit" or "__emit"
456 bool ParseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
460 bool ParseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
462 void initializeDirectiveKindMap();
468 extern MCAsmParserExtension *createDarwinAsmParser();
469 extern MCAsmParserExtension *createELFAsmParser();
470 extern MCAsmParserExtension *createCOFFAsmParser();
474 enum { DEFAULT_ADDRSPACE = 0 };
476 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
477 MCStreamer &_Out, const MCAsmInfo &_MAI)
478 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
480 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
481 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
482 // Save the old handler.
483 SavedDiagHandler = SrcMgr.getDiagHandler();
484 SavedDiagContext = SrcMgr.getDiagContext();
485 // Set our own handler which calls the saved handler.
486 SrcMgr.setDiagHandler(DiagHandler, this);
487 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
489 // Initialize the platform / file format parser.
491 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
493 if (_MAI.hasMicrosoftFastStdCallMangling()) {
494 PlatformParser = createCOFFAsmParser();
495 PlatformParser->Initialize(*this);
496 } else if (_MAI.hasSubsectionsViaSymbols()) {
497 PlatformParser = createDarwinAsmParser();
498 PlatformParser->Initialize(*this);
501 PlatformParser = createELFAsmParser();
502 PlatformParser->Initialize(*this);
505 initializeDirectiveKindMap();
508 AsmParser::~AsmParser() {
509 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
511 // Destroy any macros.
512 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
513 ie = MacroMap.end(); it != ie; ++it)
514 delete it->getValue();
516 delete PlatformParser;
519 void AsmParser::PrintMacroInstantiations() {
520 // Print the active macro instantiation stack.
521 for (std::vector<MacroInstantiation*>::const_reverse_iterator
522 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
523 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
524 "while in macro instantiation");
527 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
528 if (FatalAssemblerWarnings)
529 return Error(L, Msg, Ranges);
530 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
531 PrintMacroInstantiations();
535 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
537 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
538 PrintMacroInstantiations();
542 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
543 std::string IncludedFile;
544 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
550 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
555 /// Process the specified .incbin file by searching for it in the include paths
556 /// then just emitting the byte contents of the file to the streamer. This
557 /// returns true on failure.
558 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
559 std::string IncludedFile;
560 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
564 // Pick up the bytes from the file and emit them.
565 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
569 void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
570 if (InBuffer != -1) {
571 CurBuffer = InBuffer;
573 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
575 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
578 const AsmToken &AsmParser::Lex() {
579 const AsmToken *tok = &Lexer.Lex();
581 if (tok->is(AsmToken::Eof)) {
582 // If this is the end of an included file, pop the parent file off the
584 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
585 if (ParentIncludeLoc != SMLoc()) {
586 JumpToLoc(ParentIncludeLoc);
591 if (tok->is(AsmToken::Error))
592 Error(Lexer.getErrLoc(), Lexer.getErr());
597 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
598 // Create the initial section, if requested.
599 if (!NoInitialTextSection)
606 AsmCond StartingCondState = TheCondState;
608 // If we are generating dwarf for assembly source files save the initial text
609 // section and generate a .file directive.
610 if (getContext().getGenDwarfForAssembly()) {
611 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
612 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
613 getStreamer().EmitLabel(SectionStartSym);
614 getContext().setGenDwarfSectionStartSym(SectionStartSym);
615 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
617 getContext().getMainFileName());
620 // While we have input, parse each statement.
621 while (Lexer.isNot(AsmToken::Eof)) {
622 ParseStatementInfo Info;
623 if (!ParseStatement(Info)) continue;
625 // We had an error, validate that one was emitted and recover by skipping to
627 assert(HadError && "Parse statement returned an error, but none emitted!");
628 eatToEndOfStatement();
631 if (TheCondState.TheCond != StartingCondState.TheCond ||
632 TheCondState.Ignore != StartingCondState.Ignore)
633 return TokError("unmatched .ifs or .elses");
635 // Check to see there are no empty DwarfFile slots.
636 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
637 getContext().getMCDwarfFiles();
638 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
639 if (!MCDwarfFiles[i])
640 TokError("unassigned file number: " + Twine(i) + " for .file directives");
643 // Check to see that all assembler local symbols were actually defined.
644 // Targets that don't do subsections via symbols may not want this, though,
645 // so conservatively exclude them. Only do this if we're finalizing, though,
646 // as otherwise we won't necessarilly have seen everything yet.
647 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
648 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
649 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
652 MCSymbol *Sym = i->getValue();
653 // Variable symbols may not be marked as defined, so check those
654 // explicitly. If we know it's a variable, we have a definition for
655 // the purposes of this check.
656 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
657 // FIXME: We would really like to refer back to where the symbol was
658 // first referenced for a source location. We need to add something
659 // to track that. Currently, we just point to the end of the file.
660 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
661 "assembler local symbol '" + Sym->getName() +
667 // Finalize the output stream if there are no errors and if the client wants
669 if (!HadError && !NoFinalize)
675 void AsmParser::checkForValidSection() {
676 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
677 TokError("expected section directive before assembly directive");
678 Out.InitToTextSection();
682 /// eatToEndOfStatement - Throw away the rest of the line for testing purposes.
683 void AsmParser::eatToEndOfStatement() {
684 while (Lexer.isNot(AsmToken::EndOfStatement) &&
685 Lexer.isNot(AsmToken::Eof))
689 if (Lexer.is(AsmToken::EndOfStatement))
693 StringRef AsmParser::parseStringToEndOfStatement() {
694 const char *Start = getTok().getLoc().getPointer();
696 while (Lexer.isNot(AsmToken::EndOfStatement) &&
697 Lexer.isNot(AsmToken::Eof))
700 const char *End = getTok().getLoc().getPointer();
701 return StringRef(Start, End - Start);
704 StringRef AsmParser::ParseStringToComma() {
705 const char *Start = getTok().getLoc().getPointer();
707 while (Lexer.isNot(AsmToken::EndOfStatement) &&
708 Lexer.isNot(AsmToken::Comma) &&
709 Lexer.isNot(AsmToken::Eof))
712 const char *End = getTok().getLoc().getPointer();
713 return StringRef(Start, End - Start);
716 /// ParseParenExpr - Parse a paren expression and return it.
717 /// NOTE: This assumes the leading '(' has already been consumed.
719 /// parenexpr ::= expr)
721 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
722 if (parseExpression(Res)) return true;
723 if (Lexer.isNot(AsmToken::RParen))
724 return TokError("expected ')' in parentheses expression");
725 EndLoc = Lexer.getTok().getEndLoc();
730 /// ParseBracketExpr - Parse a bracket expression and return it.
731 /// NOTE: This assumes the leading '[' has already been consumed.
733 /// bracketexpr ::= expr]
735 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
736 if (parseExpression(Res)) return true;
737 if (Lexer.isNot(AsmToken::RBrac))
738 return TokError("expected ']' in brackets expression");
739 EndLoc = Lexer.getTok().getEndLoc();
744 /// ParsePrimaryExpr - Parse a primary expression and return it.
745 /// primaryexpr ::= (parenexpr
746 /// primaryexpr ::= symbol
747 /// primaryexpr ::= number
748 /// primaryexpr ::= '.'
749 /// primaryexpr ::= ~,+,- primaryexpr
750 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
751 SMLoc FirstTokenLoc = getLexer().getLoc();
752 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
753 switch (FirstTokenKind) {
755 return TokError("unknown token in expression");
756 // If we have an error assume that we've already handled it.
757 case AsmToken::Error:
759 case AsmToken::Exclaim:
760 Lex(); // Eat the operator.
761 if (ParsePrimaryExpr(Res, EndLoc))
763 Res = MCUnaryExpr::CreateLNot(Res, getContext());
765 case AsmToken::Dollar:
766 case AsmToken::String:
767 case AsmToken::Identifier: {
768 StringRef Identifier;
769 if (parseIdentifier(Identifier)) {
770 if (FirstTokenKind == AsmToken::Dollar)
771 return Error(FirstTokenLoc, "invalid token in expression");
775 EndLoc = SMLoc::getFromPointer(Identifier.end());
777 // This is a symbol reference.
778 std::pair<StringRef, StringRef> Split = Identifier.split('@');
779 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
781 // Lookup the symbol variant if used.
782 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
783 if (Split.first.size() != Identifier.size()) {
784 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
785 if (Variant == MCSymbolRefExpr::VK_Invalid) {
786 Variant = MCSymbolRefExpr::VK_None;
787 return TokError("invalid variant '" + Split.second + "'");
791 // If this is an absolute variable reference, substitute it now to preserve
792 // semantics in the face of reassignment.
793 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
795 return Error(EndLoc, "unexpected modifier on variable reference");
797 Res = Sym->getVariableValue();
801 // Otherwise create a symbol ref.
802 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
805 case AsmToken::Integer: {
806 SMLoc Loc = getTok().getLoc();
807 int64_t IntVal = getTok().getIntVal();
808 Res = MCConstantExpr::Create(IntVal, getContext());
809 EndLoc = Lexer.getTok().getEndLoc();
811 // Look for 'b' or 'f' following an Integer as a directional label
812 if (Lexer.getKind() == AsmToken::Identifier) {
813 StringRef IDVal = getTok().getString();
814 // Lookup the symbol variant if used.
815 std::pair<StringRef, StringRef> Split = IDVal.split('@');
816 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
817 if (Split.first.size() != IDVal.size()) {
818 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
819 if (Variant == MCSymbolRefExpr::VK_Invalid) {
820 Variant = MCSymbolRefExpr::VK_None;
821 return TokError("invalid variant '" + Split.second + "'");
825 if (IDVal == "f" || IDVal == "b"){
826 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
827 IDVal == "f" ? 1 : 0);
828 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
829 if (IDVal == "b" && Sym->isUndefined())
830 return Error(Loc, "invalid reference to undefined symbol");
831 EndLoc = Lexer.getTok().getEndLoc();
832 Lex(); // Eat identifier.
837 case AsmToken::Real: {
838 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
839 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
840 Res = MCConstantExpr::Create(IntVal, getContext());
841 EndLoc = Lexer.getTok().getEndLoc();
845 case AsmToken::Dot: {
846 // This is a '.' reference, which references the current PC. Emit a
847 // temporary label to the streamer and refer to it.
848 MCSymbol *Sym = Ctx.CreateTempSymbol();
850 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
851 EndLoc = Lexer.getTok().getEndLoc();
852 Lex(); // Eat identifier.
855 case AsmToken::LParen:
856 Lex(); // Eat the '('.
857 return ParseParenExpr(Res, EndLoc);
858 case AsmToken::LBrac:
859 if (!PlatformParser->HasBracketExpressions())
860 return TokError("brackets expression not supported on this target");
861 Lex(); // Eat the '['.
862 return ParseBracketExpr(Res, EndLoc);
863 case AsmToken::Minus:
864 Lex(); // Eat the operator.
865 if (ParsePrimaryExpr(Res, EndLoc))
867 Res = MCUnaryExpr::CreateMinus(Res, getContext());
870 Lex(); // Eat the operator.
871 if (ParsePrimaryExpr(Res, EndLoc))
873 Res = MCUnaryExpr::CreatePlus(Res, getContext());
875 case AsmToken::Tilde:
876 Lex(); // Eat the operator.
877 if (ParsePrimaryExpr(Res, EndLoc))
879 Res = MCUnaryExpr::CreateNot(Res, getContext());
884 bool AsmParser::parseExpression(const MCExpr *&Res) {
886 return parseExpression(Res, EndLoc);
889 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
890 return ParsePrimaryExpr(Res, EndLoc);
894 AsmParser::ApplyModifierToExpr(const MCExpr *E,
895 MCSymbolRefExpr::VariantKind Variant) {
896 // Recurse over the given expression, rebuilding it to apply the given variant
897 // if there is exactly one symbol.
898 switch (E->getKind()) {
900 case MCExpr::Constant:
903 case MCExpr::SymbolRef: {
904 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
906 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
907 TokError("invalid variant on expression '" +
908 getTok().getIdentifier() + "' (already modified)");
912 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
915 case MCExpr::Unary: {
916 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
917 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
920 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
923 case MCExpr::Binary: {
924 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
925 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
926 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
931 if (!LHS) LHS = BE->getLHS();
932 if (!RHS) RHS = BE->getRHS();
934 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
938 llvm_unreachable("Invalid expression kind!");
941 /// parseExpression - Parse an expression and return it.
943 /// expr ::= expr &&,|| expr -> lowest.
944 /// expr ::= expr |,^,&,! expr
945 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
946 /// expr ::= expr <<,>> expr
947 /// expr ::= expr +,- expr
948 /// expr ::= expr *,/,% expr -> highest.
949 /// expr ::= primaryexpr
951 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
952 // Parse the expression.
954 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
957 // As a special case, we support 'a op b @ modifier' by rewriting the
958 // expression to include the modifier. This is inefficient, but in general we
959 // expect users to use 'a@modifier op b'.
960 if (Lexer.getKind() == AsmToken::At) {
963 if (Lexer.isNot(AsmToken::Identifier))
964 return TokError("unexpected symbol modifier following '@'");
966 MCSymbolRefExpr::VariantKind Variant =
967 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
968 if (Variant == MCSymbolRefExpr::VK_Invalid)
969 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
971 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
973 return TokError("invalid modifier '" + getTok().getIdentifier() +
974 "' (no symbols present)");
981 // Try to constant fold it up front, if possible.
983 if (Res->EvaluateAsAbsolute(Value))
984 Res = MCConstantExpr::Create(Value, getContext());
989 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
991 return ParseParenExpr(Res, EndLoc) ||
992 ParseBinOpRHS(1, Res, EndLoc);
995 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
998 SMLoc StartLoc = Lexer.getLoc();
999 if (parseExpression(Expr))
1002 if (!Expr->EvaluateAsAbsolute(Res))
1003 return Error(StartLoc, "expected absolute expression");
1008 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1009 MCBinaryExpr::Opcode &Kind) {
1012 return 0; // not a binop.
1014 // Lowest Precedence: &&, ||
1015 case AsmToken::AmpAmp:
1016 Kind = MCBinaryExpr::LAnd;
1018 case AsmToken::PipePipe:
1019 Kind = MCBinaryExpr::LOr;
1023 // Low Precedence: |, &, ^
1025 // FIXME: gas seems to support '!' as an infix operator?
1026 case AsmToken::Pipe:
1027 Kind = MCBinaryExpr::Or;
1029 case AsmToken::Caret:
1030 Kind = MCBinaryExpr::Xor;
1033 Kind = MCBinaryExpr::And;
1036 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1037 case AsmToken::EqualEqual:
1038 Kind = MCBinaryExpr::EQ;
1040 case AsmToken::ExclaimEqual:
1041 case AsmToken::LessGreater:
1042 Kind = MCBinaryExpr::NE;
1044 case AsmToken::Less:
1045 Kind = MCBinaryExpr::LT;
1047 case AsmToken::LessEqual:
1048 Kind = MCBinaryExpr::LTE;
1050 case AsmToken::Greater:
1051 Kind = MCBinaryExpr::GT;
1053 case AsmToken::GreaterEqual:
1054 Kind = MCBinaryExpr::GTE;
1057 // Intermediate Precedence: <<, >>
1058 case AsmToken::LessLess:
1059 Kind = MCBinaryExpr::Shl;
1061 case AsmToken::GreaterGreater:
1062 Kind = MCBinaryExpr::Shr;
1065 // High Intermediate Precedence: +, -
1066 case AsmToken::Plus:
1067 Kind = MCBinaryExpr::Add;
1069 case AsmToken::Minus:
1070 Kind = MCBinaryExpr::Sub;
1073 // Highest Precedence: *, /, %
1074 case AsmToken::Star:
1075 Kind = MCBinaryExpr::Mul;
1077 case AsmToken::Slash:
1078 Kind = MCBinaryExpr::Div;
1080 case AsmToken::Percent:
1081 Kind = MCBinaryExpr::Mod;
1087 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1088 /// Res contains the LHS of the expression on input.
1089 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1092 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1093 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1095 // If the next token is lower precedence than we are allowed to eat, return
1096 // successfully with what we ate already.
1097 if (TokPrec < Precedence)
1102 // Eat the next primary expression.
1104 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1106 // If BinOp binds less tightly with RHS than the operator after RHS, let
1107 // the pending operator take RHS as its LHS.
1108 MCBinaryExpr::Opcode Dummy;
1109 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1110 if (TokPrec < NextTokPrec) {
1111 if (ParseBinOpRHS(TokPrec+1, RHS, EndLoc)) return true;
1114 // Merge LHS and RHS according to operator.
1115 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1120 /// ::= EndOfStatement
1121 /// ::= Label* Directive ...Operands... EndOfStatement
1122 /// ::= Label* Identifier OperandList* EndOfStatement
1123 bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
1124 if (Lexer.is(AsmToken::EndOfStatement)) {
1130 // Statements always start with an identifier or are a full line comment.
1131 AsmToken ID = getTok();
1132 SMLoc IDLoc = ID.getLoc();
1134 int64_t LocalLabelVal = -1;
1135 // A full line comment is a '#' as the first token.
1136 if (Lexer.is(AsmToken::Hash))
1137 return ParseCppHashLineFilenameComment(IDLoc);
1139 // Allow an integer followed by a ':' as a directional local label.
1140 if (Lexer.is(AsmToken::Integer)) {
1141 LocalLabelVal = getTok().getIntVal();
1142 if (LocalLabelVal < 0) {
1143 if (!TheCondState.Ignore)
1144 return TokError("unexpected token at start of statement");
1147 IDVal = getTok().getString();
1148 Lex(); // Consume the integer token to be used as an identifier token.
1149 if (Lexer.getKind() != AsmToken::Colon) {
1150 if (!TheCondState.Ignore)
1151 return TokError("unexpected token at start of statement");
1154 } else if (Lexer.is(AsmToken::Dot)) {
1155 // Treat '.' as a valid identifier in this context.
1158 } else if (parseIdentifier(IDVal)) {
1159 if (!TheCondState.Ignore)
1160 return TokError("unexpected token at start of statement");
1164 // Handle conditional assembly here before checking for skipping. We
1165 // have to do this so that .endif isn't skipped in a ".if 0" block for
1167 StringMap<DirectiveKind>::const_iterator DirKindIt =
1168 DirectiveKindMap.find(IDVal);
1169 DirectiveKind DirKind =
1170 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1171 DirKindIt->getValue();
1176 return ParseDirectiveIf(IDLoc);
1178 return ParseDirectiveIfb(IDLoc, true);
1180 return ParseDirectiveIfb(IDLoc, false);
1182 return ParseDirectiveIfc(IDLoc, true);
1184 return ParseDirectiveIfc(IDLoc, false);
1186 return ParseDirectiveIfdef(IDLoc, true);
1189 return ParseDirectiveIfdef(IDLoc, false);
1191 return ParseDirectiveElseIf(IDLoc);
1193 return ParseDirectiveElse(IDLoc);
1195 return ParseDirectiveEndIf(IDLoc);
1198 // Ignore the statement if in the middle of inactive conditional
1200 if (TheCondState.Ignore) {
1201 eatToEndOfStatement();
1205 // FIXME: Recurse on local labels?
1207 // See what kind of statement we have.
1208 switch (Lexer.getKind()) {
1209 case AsmToken::Colon: {
1210 checkForValidSection();
1212 // identifier ':' -> Label.
1215 // Diagnose attempt to use '.' as a label.
1217 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1219 // Diagnose attempt to use a variable as a label.
1221 // FIXME: Diagnostics. Note the location of the definition as a label.
1222 // FIXME: This doesn't diagnose assignment to a symbol which has been
1223 // implicitly marked as external.
1225 if (LocalLabelVal == -1)
1226 Sym = getContext().GetOrCreateSymbol(IDVal);
1228 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1229 if (!Sym->isUndefined() || Sym->isVariable())
1230 return Error(IDLoc, "invalid symbol redefinition");
1233 if (!ParsingInlineAsm)
1236 // If we are generating dwarf for assembly source files then gather the
1237 // info to make a dwarf label entry for this label if needed.
1238 if (getContext().getGenDwarfForAssembly())
1239 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1242 // Consume any end of statement token, if present, to avoid spurious
1243 // AddBlankLine calls().
1244 if (Lexer.is(AsmToken::EndOfStatement)) {
1246 if (Lexer.is(AsmToken::Eof))
1253 case AsmToken::Equal:
1254 // identifier '=' ... -> assignment statement
1257 return ParseAssignment(IDVal, true);
1259 default: // Normal instruction or directive.
1263 // If macros are enabled, check to see if this is a macro instantiation.
1264 if (MacrosEnabled())
1265 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1266 return HandleMacroEntry(M, IDLoc);
1269 // Otherwise, we have a normal instruction or directive.
1271 // Directives start with "."
1272 if (IDVal[0] == '.' && IDVal != ".") {
1273 // There are several entities interested in parsing directives:
1275 // 1. The target-specific assembly parser. Some directives are target
1276 // specific or may potentially behave differently on certain targets.
1277 // 2. Asm parser extensions. For example, platform-specific parsers
1278 // (like the ELF parser) register themselves as extensions.
1279 // 3. The generic directive parser implemented by this class. These are
1280 // all the directives that behave in a target and platform independent
1281 // manner, or at least have a default behavior that's shared between
1282 // all targets and platforms.
1284 // First query the target-specific parser. It will return 'true' if it
1285 // isn't interested in this directive.
1286 if (!getTargetParser().ParseDirective(ID))
1289 // Next, check the extention directive map to see if any extension has
1290 // registered itself to parse this directive.
1291 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1292 ExtensionDirectiveMap.lookup(IDVal);
1294 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1296 // Finally, if no one else is interested in this directive, it must be
1297 // generic and familiar to this class.
1303 return ParseDirectiveSet(IDVal, true);
1305 return ParseDirectiveSet(IDVal, false);
1307 return ParseDirectiveAscii(IDVal, false);
1310 return ParseDirectiveAscii(IDVal, true);
1312 return ParseDirectiveValue(1);
1316 return ParseDirectiveValue(2);
1320 return ParseDirectiveValue(4);
1323 return ParseDirectiveValue(8);
1326 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1328 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1330 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1331 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1334 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1335 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1338 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1340 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1342 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1344 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1346 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1348 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1350 return ParseDirectiveOrg();
1352 return ParseDirectiveFill();
1354 return ParseDirectiveZero();
1356 eatToEndOfStatement(); // .extern is the default, ignore it.
1360 return ParseDirectiveSymbolAttribute(MCSA_Global);
1361 case DK_INDIRECT_SYMBOL:
1362 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1363 case DK_LAZY_REFERENCE:
1364 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1365 case DK_NO_DEAD_STRIP:
1366 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1367 case DK_SYMBOL_RESOLVER:
1368 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1369 case DK_PRIVATE_EXTERN:
1370 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1372 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1373 case DK_WEAK_DEFINITION:
1374 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1375 case DK_WEAK_REFERENCE:
1376 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1377 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1378 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1381 return ParseDirectiveComm(/*IsLocal=*/false);
1383 return ParseDirectiveComm(/*IsLocal=*/true);
1385 return ParseDirectiveAbort();
1387 return ParseDirectiveInclude();
1389 return ParseDirectiveIncbin();
1392 return TokError(Twine(IDVal) + " not supported yet");
1394 return ParseDirectiveRept(IDLoc);
1396 return ParseDirectiveIrp(IDLoc);
1398 return ParseDirectiveIrpc(IDLoc);
1400 return ParseDirectiveEndr(IDLoc);
1401 case DK_BUNDLE_ALIGN_MODE:
1402 return ParseDirectiveBundleAlignMode();
1403 case DK_BUNDLE_LOCK:
1404 return ParseDirectiveBundleLock();
1405 case DK_BUNDLE_UNLOCK:
1406 return ParseDirectiveBundleUnlock();
1408 return ParseDirectiveLEB128(true);
1410 return ParseDirectiveLEB128(false);
1413 return ParseDirectiveSpace(IDVal);
1415 return ParseDirectiveFile(IDLoc);
1417 return ParseDirectiveLine();
1419 return ParseDirectiveLoc();
1421 return ParseDirectiveStabs();
1422 case DK_CFI_SECTIONS:
1423 return ParseDirectiveCFISections();
1424 case DK_CFI_STARTPROC:
1425 return ParseDirectiveCFIStartProc();
1426 case DK_CFI_ENDPROC:
1427 return ParseDirectiveCFIEndProc();
1428 case DK_CFI_DEF_CFA:
1429 return ParseDirectiveCFIDefCfa(IDLoc);
1430 case DK_CFI_DEF_CFA_OFFSET:
1431 return ParseDirectiveCFIDefCfaOffset();
1432 case DK_CFI_ADJUST_CFA_OFFSET:
1433 return ParseDirectiveCFIAdjustCfaOffset();
1434 case DK_CFI_DEF_CFA_REGISTER:
1435 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1437 return ParseDirectiveCFIOffset(IDLoc);
1438 case DK_CFI_REL_OFFSET:
1439 return ParseDirectiveCFIRelOffset(IDLoc);
1440 case DK_CFI_PERSONALITY:
1441 return ParseDirectiveCFIPersonalityOrLsda(true);
1443 return ParseDirectiveCFIPersonalityOrLsda(false);
1444 case DK_CFI_REMEMBER_STATE:
1445 return ParseDirectiveCFIRememberState();
1446 case DK_CFI_RESTORE_STATE:
1447 return ParseDirectiveCFIRestoreState();
1448 case DK_CFI_SAME_VALUE:
1449 return ParseDirectiveCFISameValue(IDLoc);
1450 case DK_CFI_RESTORE:
1451 return ParseDirectiveCFIRestore(IDLoc);
1453 return ParseDirectiveCFIEscape();
1454 case DK_CFI_SIGNAL_FRAME:
1455 return ParseDirectiveCFISignalFrame();
1456 case DK_CFI_UNDEFINED:
1457 return ParseDirectiveCFIUndefined(IDLoc);
1458 case DK_CFI_REGISTER:
1459 return ParseDirectiveCFIRegister(IDLoc);
1462 return ParseDirectiveMacrosOnOff(IDVal);
1464 return ParseDirectiveMacro(IDLoc);
1467 return ParseDirectiveEndMacro(IDVal);
1469 return ParseDirectivePurgeMacro(IDLoc);
1472 return Error(IDLoc, "unknown directive");
1475 // __asm _emit or __asm __emit
1476 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1477 IDVal == "_EMIT" || IDVal == "__EMIT"))
1478 return ParseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1481 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1482 return ParseDirectiveMSAlign(IDLoc, Info);
1484 checkForValidSection();
1486 // Canonicalize the opcode to lower case.
1487 std::string OpcodeStr = IDVal.lower();
1488 ParseInstructionInfo IInfo(Info.AsmRewrites);
1489 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
1490 IDLoc, Info.ParsedOperands);
1491 Info.ParseError = HadError;
1493 // Dump the parsed representation, if requested.
1494 if (getShowParsedOperands()) {
1495 SmallString<256> Str;
1496 raw_svector_ostream OS(Str);
1497 OS << "parsed instruction: [";
1498 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1501 Info.ParsedOperands[i]->print(OS);
1505 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1508 // If we are generating dwarf for assembly source files and the current
1509 // section is the initial text section then generate a .loc directive for
1511 if (!HadError && getContext().getGenDwarfForAssembly() &&
1512 getContext().getGenDwarfSection() ==
1513 getStreamer().getCurrentSection().first) {
1515 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1517 // If we previously parsed a cpp hash file line comment then make sure the
1518 // current Dwarf File is for the CppHashFilename if not then emit the
1519 // Dwarf File table for it and adjust the line number for the .loc.
1520 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
1521 getContext().getMCDwarfFiles();
1522 if (CppHashFilename.size() != 0) {
1523 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1525 getStreamer().EmitDwarfFileDirective(
1526 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1528 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1529 // cache with the different Loc from the call above we save the last
1530 // info we queried here with SrcMgr.FindLineNumber().
1531 unsigned CppHashLocLineNo;
1532 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1533 CppHashLocLineNo = LastQueryLine;
1535 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1536 LastQueryLine = CppHashLocLineNo;
1537 LastQueryIDLoc = CppHashLoc;
1538 LastQueryBuffer = CppHashBuf;
1540 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1543 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1544 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1545 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1549 // If parsing succeeded, match the instruction.
1552 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1553 Info.ParsedOperands,
1558 // Don't skip the rest of the line, the instruction parser is responsible for
1563 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1564 /// since they may not be able to be tokenized to get to the end of line token.
1565 void AsmParser::EatToEndOfLine() {
1566 if (!Lexer.is(AsmToken::EndOfStatement))
1567 Lexer.LexUntilEndOfLine();
1572 /// ParseCppHashLineFilenameComment as this:
1573 /// ::= # number "filename"
1574 /// or just as a full line comment if it doesn't have a number and a string.
1575 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1576 Lex(); // Eat the hash token.
1578 if (getLexer().isNot(AsmToken::Integer)) {
1579 // Consume the line since in cases it is not a well-formed line directive,
1580 // as if were simply a full line comment.
1585 int64_t LineNumber = getTok().getIntVal();
1588 if (getLexer().isNot(AsmToken::String)) {
1593 StringRef Filename = getTok().getString();
1594 // Get rid of the enclosing quotes.
1595 Filename = Filename.substr(1, Filename.size()-2);
1597 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1599 CppHashFilename = Filename;
1600 CppHashLineNumber = LineNumber;
1601 CppHashBuf = CurBuffer;
1603 // Ignore any trailing characters, they're just comment.
1608 /// DiagHandler - will use the last parsed cpp hash line filename comment
1609 /// for the Filename and LineNo if any in the diagnostic.
1610 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1611 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1612 raw_ostream &OS = errs();
1614 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1615 const SMLoc &DiagLoc = Diag.getLoc();
1616 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1617 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1619 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1620 // before printing the message.
1621 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1622 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1623 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1624 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1627 // If we have not parsed a cpp hash line filename comment or the source
1628 // manager changed or buffer changed (like in a nested include) then just
1629 // print the normal diagnostic using its Filename and LineNo.
1630 if (!Parser->CppHashLineNumber ||
1631 &DiagSrcMgr != &Parser->SrcMgr ||
1632 DiagBuf != CppHashBuf) {
1633 if (Parser->SavedDiagHandler)
1634 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1640 // Use the CppHashFilename and calculate a line number based on the
1641 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1643 const std::string Filename = Parser->CppHashFilename;
1645 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1646 int CppHashLocLineNo =
1647 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1648 int LineNo = Parser->CppHashLineNumber - 1 +
1649 (DiagLocLineNo - CppHashLocLineNo);
1651 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1652 Filename, LineNo, Diag.getColumnNo(),
1653 Diag.getKind(), Diag.getMessage(),
1654 Diag.getLineContents(), Diag.getRanges());
1656 if (Parser->SavedDiagHandler)
1657 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1659 NewDiag.print(0, OS);
1662 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1663 // difference being that that function accepts '@' as part of identifiers and
1664 // we can't do that. AsmLexer.cpp should probably be changed to handle
1665 // '@' as a special case when needed.
1666 static bool isIdentifierChar(char c) {
1667 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1671 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1672 const MCAsmMacroParameters &Parameters,
1673 const MCAsmMacroArguments &A,
1675 unsigned NParameters = Parameters.size();
1676 if (NParameters != 0 && NParameters != A.size())
1677 return Error(L, "Wrong number of arguments");
1679 // A macro without parameters is handled differently on Darwin:
1680 // gas accepts no arguments and does no substitutions
1681 while (!Body.empty()) {
1682 // Scan for the next substitution.
1683 std::size_t End = Body.size(), Pos = 0;
1684 for (; Pos != End; ++Pos) {
1685 // Check for a substitution or escape.
1687 // This macro has no parameters, look for $0, $1, etc.
1688 if (Body[Pos] != '$' || Pos + 1 == End)
1691 char Next = Body[Pos + 1];
1692 if (Next == '$' || Next == 'n' ||
1693 isdigit(static_cast<unsigned char>(Next)))
1696 // This macro has parameters, look for \foo, \bar, etc.
1697 if (Body[Pos] == '\\' && Pos + 1 != End)
1703 OS << Body.slice(0, Pos);
1705 // Check if we reached the end.
1710 switch (Body[Pos+1]) {
1716 // $n => number of arguments
1721 // $[0-9] => argument
1723 // Missing arguments are ignored.
1724 unsigned Index = Body[Pos+1] - '0';
1725 if (Index >= A.size())
1728 // Otherwise substitute with the token values, with spaces eliminated.
1729 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1730 ie = A[Index].end(); it != ie; ++it)
1731 OS << it->getString();
1737 unsigned I = Pos + 1;
1738 while (isIdentifierChar(Body[I]) && I + 1 != End)
1741 const char *Begin = Body.data() + Pos +1;
1742 StringRef Argument(Begin, I - (Pos +1));
1744 for (; Index < NParameters; ++Index)
1745 if (Parameters[Index].first == Argument)
1748 if (Index == NParameters) {
1749 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1752 OS << '\\' << Argument;
1756 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1757 ie = A[Index].end(); it != ie; ++it)
1758 if (it->getKind() == AsmToken::String)
1759 OS << it->getStringContents();
1761 OS << it->getString();
1763 Pos += 1 + Argument.size();
1766 // Update the scan point.
1767 Body = Body.substr(Pos);
1773 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
1776 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1781 static bool IsOperator(AsmToken::TokenKind kind)
1787 case AsmToken::Plus:
1788 case AsmToken::Minus:
1789 case AsmToken::Tilde:
1790 case AsmToken::Slash:
1791 case AsmToken::Star:
1793 case AsmToken::Equal:
1794 case AsmToken::EqualEqual:
1795 case AsmToken::Pipe:
1796 case AsmToken::PipePipe:
1797 case AsmToken::Caret:
1799 case AsmToken::AmpAmp:
1800 case AsmToken::Exclaim:
1801 case AsmToken::ExclaimEqual:
1802 case AsmToken::Percent:
1803 case AsmToken::Less:
1804 case AsmToken::LessEqual:
1805 case AsmToken::LessLess:
1806 case AsmToken::LessGreater:
1807 case AsmToken::Greater:
1808 case AsmToken::GreaterEqual:
1809 case AsmToken::GreaterGreater:
1814 bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
1815 AsmToken::TokenKind &ArgumentDelimiter) {
1816 unsigned ParenLevel = 0;
1817 unsigned AddTokens = 0;
1819 // gas accepts arguments separated by whitespace, except on Darwin
1821 Lexer.setSkipSpace(false);
1824 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1825 Lexer.setSkipSpace(true);
1826 return TokError("unexpected token in macro instantiation");
1829 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1830 // Spaces and commas cannot be mixed to delimit parameters
1831 if (ArgumentDelimiter == AsmToken::Eof)
1832 ArgumentDelimiter = AsmToken::Comma;
1833 else if (ArgumentDelimiter != AsmToken::Comma) {
1834 Lexer.setSkipSpace(true);
1835 return TokError("expected ' ' for macro argument separator");
1840 if (Lexer.is(AsmToken::Space)) {
1841 Lex(); // Eat spaces
1843 // Spaces can delimit parameters, but could also be part an expression.
1844 // If the token after a space is an operator, add the token and the next
1845 // one into this argument
1846 if (ArgumentDelimiter == AsmToken::Space ||
1847 ArgumentDelimiter == AsmToken::Eof) {
1848 if (IsOperator(Lexer.getKind())) {
1849 // Check to see whether the token is used as an operator,
1850 // or part of an identifier
1851 const char *NextChar = getTok().getEndLoc().getPointer();
1852 if (*NextChar == ' ')
1856 if (!AddTokens && ParenLevel == 0) {
1857 if (ArgumentDelimiter == AsmToken::Eof &&
1858 !IsOperator(Lexer.getKind()))
1859 ArgumentDelimiter = AsmToken::Space;
1865 // HandleMacroEntry relies on not advancing the lexer here
1866 // to be able to fill in the remaining default parameter values
1867 if (Lexer.is(AsmToken::EndOfStatement))
1870 // Adjust the current parentheses level.
1871 if (Lexer.is(AsmToken::LParen))
1873 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1876 // Append the token to the current argument list.
1877 MA.push_back(getTok());
1883 Lexer.setSkipSpace(true);
1884 if (ParenLevel != 0)
1885 return TokError("unbalanced parentheses in macro argument");
1889 // Parse the macro instantiation arguments.
1890 bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
1891 const unsigned NParameters = M ? M->Parameters.size() : 0;
1892 // Argument delimiter is initially unknown. It will be set by
1893 // ParseMacroArgument()
1894 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1896 // Parse two kinds of macro invocations:
1897 // - macros defined without any parameters accept an arbitrary number of them
1898 // - macros defined with parameters accept at most that many of them
1899 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1901 MCAsmMacroArgument MA;
1903 if (ParseMacroArgument(MA, ArgumentDelimiter))
1906 if (!MA.empty() || !NParameters)
1908 else if (NParameters) {
1909 if (!M->Parameters[Parameter].second.empty())
1910 A.push_back(M->Parameters[Parameter].second);
1913 // At the end of the statement, fill in remaining arguments that have
1914 // default values. If there aren't any, then the next argument is
1915 // required but missing
1916 if (Lexer.is(AsmToken::EndOfStatement)) {
1917 if (NParameters && Parameter < NParameters - 1) {
1918 if (M->Parameters[Parameter + 1].second.empty())
1919 return TokError("macro argument '" +
1920 Twine(M->Parameters[Parameter + 1].first) +
1928 if (Lexer.is(AsmToken::Comma))
1931 return TokError("Too many arguments");
1934 const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1935 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1936 return (I == MacroMap.end()) ? NULL : I->getValue();
1939 void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1940 MacroMap[Name] = new MCAsmMacro(Macro);
1943 void AsmParser::UndefineMacro(StringRef Name) {
1944 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1945 if (I != MacroMap.end()) {
1946 delete I->getValue();
1951 bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
1952 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1953 // this, although we should protect against infinite loops.
1954 if (ActiveMacros.size() == 20)
1955 return TokError("macros cannot be nested more than 20 levels deep");
1957 MCAsmMacroArguments A;
1958 if (ParseMacroArguments(M, A))
1961 // Remove any trailing empty arguments. Do this after-the-fact as we have
1962 // to keep empty arguments in the middle of the list or positionality
1963 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1964 while (!A.empty() && A.back().empty())
1967 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1968 // to hold the macro body with substitutions.
1969 SmallString<256> Buf;
1970 StringRef Body = M->Body;
1971 raw_svector_ostream OS(Buf);
1973 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1976 // We include the .endmacro in the buffer as our cue to exit the macro
1978 OS << ".endmacro\n";
1980 MemoryBuffer *Instantiation =
1981 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1983 // Create the macro instantiation object and add to the current macro
1984 // instantiation stack.
1985 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1989 ActiveMacros.push_back(MI);
1991 // Jump to the macro instantiation and prime the lexer.
1992 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1993 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1999 void AsmParser::HandleMacroExit() {
2000 // Jump to the EndOfStatement we should return to, and consume it.
2001 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2004 // Pop the instantiation entry.
2005 delete ActiveMacros.back();
2006 ActiveMacros.pop_back();
2009 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2010 switch (Value->getKind()) {
2011 case MCExpr::Binary: {
2012 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
2013 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
2015 case MCExpr::Target:
2016 case MCExpr::Constant:
2018 case MCExpr::SymbolRef: {
2019 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
2021 return IsUsedIn(Sym, S.getVariableValue());
2025 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
2028 llvm_unreachable("Unknown expr kind!");
2031 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
2033 // FIXME: Use better location, we should use proper tokens.
2034 SMLoc EqualLoc = Lexer.getLoc();
2036 const MCExpr *Value;
2037 if (parseExpression(Value))
2040 // Note: we don't count b as used in "a = b". This is to allow
2044 if (Lexer.isNot(AsmToken::EndOfStatement))
2045 return TokError("unexpected token in assignment");
2047 // Error on assignment to '.'.
2049 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2050 "(use '.space' or '.org').)"));
2053 // Eat the end of statement marker.
2056 // Validate that the LHS is allowed to be a variable (either it has not been
2057 // used as a symbol, or it is an absolute symbol).
2058 MCSymbol *Sym = getContext().LookupSymbol(Name);
2060 // Diagnose assignment to a label.
2062 // FIXME: Diagnostics. Note the location of the definition as a label.
2063 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2064 if (IsUsedIn(Sym, Value))
2065 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2066 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2067 ; // Allow redefinitions of undefined symbols only used in directives.
2068 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2069 ; // Allow redefinitions of variables that haven't yet been used.
2070 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2071 return Error(EqualLoc, "redefinition of '" + Name + "'");
2072 else if (!Sym->isVariable())
2073 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2074 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2075 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2078 // Don't count these checks as uses.
2079 Sym->setUsed(false);
2081 Sym = getContext().GetOrCreateSymbol(Name);
2083 // FIXME: Handle '.'.
2085 // Do the assignment.
2086 Out.EmitAssignment(Sym, Value);
2088 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2094 /// parseIdentifier:
2097 bool AsmParser::parseIdentifier(StringRef &Res) {
2098 // The assembler has relaxed rules for accepting identifiers, in particular we
2099 // allow things like '.globl $foo', which would normally be separate
2100 // tokens. At this level, we have already lexed so we cannot (currently)
2101 // handle this as a context dependent token, instead we detect adjacent tokens
2102 // and return the combined identifier.
2103 if (Lexer.is(AsmToken::Dollar)) {
2104 SMLoc DollarLoc = getLexer().getLoc();
2106 // Consume the dollar sign, and check for a following identifier.
2108 if (Lexer.isNot(AsmToken::Identifier))
2111 // We have a '$' followed by an identifier, make sure they are adjacent.
2112 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2115 // Construct the joined identifier and consume the token.
2116 Res = StringRef(DollarLoc.getPointer(),
2117 getTok().getIdentifier().size() + 1);
2122 if (Lexer.isNot(AsmToken::Identifier) &&
2123 Lexer.isNot(AsmToken::String))
2126 Res = getTok().getIdentifier();
2128 Lex(); // Consume the identifier token.
2133 /// ParseDirectiveSet:
2134 /// ::= .equ identifier ',' expression
2135 /// ::= .equiv identifier ',' expression
2136 /// ::= .set identifier ',' expression
2137 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
2140 if (parseIdentifier(Name))
2141 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2143 if (getLexer().isNot(AsmToken::Comma))
2144 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2147 return ParseAssignment(Name, allow_redef, true);
2150 bool AsmParser::parseEscapedString(std::string &Data) {
2151 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2154 StringRef Str = getTok().getStringContents();
2155 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2156 if (Str[i] != '\\') {
2161 // Recognize escaped characters. Note that this escape semantics currently
2162 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2165 return TokError("unexpected backslash at end of string");
2167 // Recognize octal sequences.
2168 if ((unsigned) (Str[i] - '0') <= 7) {
2169 // Consume up to three octal characters.
2170 unsigned Value = Str[i] - '0';
2172 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2174 Value = Value * 8 + (Str[i] - '0');
2176 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2178 Value = Value * 8 + (Str[i] - '0');
2183 return TokError("invalid octal escape sequence (out of range)");
2185 Data += (unsigned char) Value;
2189 // Otherwise recognize individual escapes.
2192 // Just reject invalid escape sequences for now.
2193 return TokError("invalid escape sequence (unrecognized character)");
2195 case 'b': Data += '\b'; break;
2196 case 'f': Data += '\f'; break;
2197 case 'n': Data += '\n'; break;
2198 case 'r': Data += '\r'; break;
2199 case 't': Data += '\t'; break;
2200 case '"': Data += '"'; break;
2201 case '\\': Data += '\\'; break;
2208 /// ParseDirectiveAscii:
2209 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2210 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2211 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2212 checkForValidSection();
2215 if (getLexer().isNot(AsmToken::String))
2216 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2219 if (parseEscapedString(Data))
2222 getStreamer().EmitBytes(Data);
2224 getStreamer().EmitBytes(StringRef("\0", 1));
2228 if (getLexer().is(AsmToken::EndOfStatement))
2231 if (getLexer().isNot(AsmToken::Comma))
2232 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2241 /// ParseDirectiveValue
2242 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2243 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2244 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2245 checkForValidSection();
2248 const MCExpr *Value;
2249 SMLoc ExprLoc = getLexer().getLoc();
2250 if (parseExpression(Value))
2253 // Special case constant expressions to match code generator.
2254 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2255 assert(Size <= 8 && "Invalid size");
2256 uint64_t IntValue = MCE->getValue();
2257 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2258 return Error(ExprLoc, "literal value out of range for directive");
2259 getStreamer().EmitIntValue(IntValue, Size);
2261 getStreamer().EmitValue(Value, Size);
2263 if (getLexer().is(AsmToken::EndOfStatement))
2266 // FIXME: Improve diagnostic.
2267 if (getLexer().isNot(AsmToken::Comma))
2268 return TokError("unexpected token in directive");
2277 /// ParseDirectiveRealValue
2278 /// ::= (.single | .double) [ expression (, expression)* ]
2279 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2280 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2281 checkForValidSection();
2284 // We don't truly support arithmetic on floating point expressions, so we
2285 // have to manually parse unary prefixes.
2287 if (getLexer().is(AsmToken::Minus)) {
2290 } else if (getLexer().is(AsmToken::Plus))
2293 if (getLexer().isNot(AsmToken::Integer) &&
2294 getLexer().isNot(AsmToken::Real) &&
2295 getLexer().isNot(AsmToken::Identifier))
2296 return TokError("unexpected token in directive");
2298 // Convert to an APFloat.
2299 APFloat Value(Semantics);
2300 StringRef IDVal = getTok().getString();
2301 if (getLexer().is(AsmToken::Identifier)) {
2302 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2303 Value = APFloat::getInf(Semantics);
2304 else if (!IDVal.compare_lower("nan"))
2305 Value = APFloat::getNaN(Semantics, false, ~0);
2307 return TokError("invalid floating point literal");
2308 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2309 APFloat::opInvalidOp)
2310 return TokError("invalid floating point literal");
2314 // Consume the numeric token.
2317 // Emit the value as an integer.
2318 APInt AsInt = Value.bitcastToAPInt();
2319 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2320 AsInt.getBitWidth() / 8);
2322 if (getLexer().is(AsmToken::EndOfStatement))
2325 if (getLexer().isNot(AsmToken::Comma))
2326 return TokError("unexpected token in directive");
2335 /// ParseDirectiveZero
2336 /// ::= .zero expression
2337 bool AsmParser::ParseDirectiveZero() {
2338 checkForValidSection();
2341 if (parseAbsoluteExpression(NumBytes))
2345 if (getLexer().is(AsmToken::Comma)) {
2347 if (parseAbsoluteExpression(Val))
2351 if (getLexer().isNot(AsmToken::EndOfStatement))
2352 return TokError("unexpected token in '.zero' directive");
2356 getStreamer().EmitFill(NumBytes, Val);
2361 /// ParseDirectiveFill
2362 /// ::= .fill expression , expression , expression
2363 bool AsmParser::ParseDirectiveFill() {
2364 checkForValidSection();
2367 if (parseAbsoluteExpression(NumValues))
2370 if (getLexer().isNot(AsmToken::Comma))
2371 return TokError("unexpected token in '.fill' directive");
2375 if (parseAbsoluteExpression(FillSize))
2378 if (getLexer().isNot(AsmToken::Comma))
2379 return TokError("unexpected token in '.fill' directive");
2383 if (parseAbsoluteExpression(FillExpr))
2386 if (getLexer().isNot(AsmToken::EndOfStatement))
2387 return TokError("unexpected token in '.fill' directive");
2391 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2392 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2394 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2395 getStreamer().EmitIntValue(FillExpr, FillSize);
2400 /// ParseDirectiveOrg
2401 /// ::= .org expression [ , expression ]
2402 bool AsmParser::ParseDirectiveOrg() {
2403 checkForValidSection();
2405 const MCExpr *Offset;
2406 SMLoc Loc = getTok().getLoc();
2407 if (parseExpression(Offset))
2410 // Parse optional fill expression.
2411 int64_t FillExpr = 0;
2412 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2413 if (getLexer().isNot(AsmToken::Comma))
2414 return TokError("unexpected token in '.org' directive");
2417 if (parseAbsoluteExpression(FillExpr))
2420 if (getLexer().isNot(AsmToken::EndOfStatement))
2421 return TokError("unexpected token in '.org' directive");
2426 // Only limited forms of relocatable expressions are accepted here, it
2427 // has to be relative to the current section. The streamer will return
2428 // 'true' if the expression wasn't evaluatable.
2429 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2430 return Error(Loc, "expected assembly-time absolute expression");
2435 /// ParseDirectiveAlign
2436 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2437 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2438 checkForValidSection();
2440 SMLoc AlignmentLoc = getLexer().getLoc();
2442 if (parseAbsoluteExpression(Alignment))
2446 bool HasFillExpr = false;
2447 int64_t FillExpr = 0;
2448 int64_t MaxBytesToFill = 0;
2449 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2450 if (getLexer().isNot(AsmToken::Comma))
2451 return TokError("unexpected token in directive");
2454 // The fill expression can be omitted while specifying a maximum number of
2455 // alignment bytes, e.g:
2457 if (getLexer().isNot(AsmToken::Comma)) {
2459 if (parseAbsoluteExpression(FillExpr))
2463 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2464 if (getLexer().isNot(AsmToken::Comma))
2465 return TokError("unexpected token in directive");
2468 MaxBytesLoc = getLexer().getLoc();
2469 if (parseAbsoluteExpression(MaxBytesToFill))
2472 if (getLexer().isNot(AsmToken::EndOfStatement))
2473 return TokError("unexpected token in directive");
2482 // Compute alignment in bytes.
2484 // FIXME: Diagnose overflow.
2485 if (Alignment >= 32) {
2486 Error(AlignmentLoc, "invalid alignment value");
2490 Alignment = 1ULL << Alignment;
2492 // Reject alignments that aren't a power of two, for gas compatibility.
2493 if (!isPowerOf2_64(Alignment))
2494 Error(AlignmentLoc, "alignment must be a power of 2");
2497 // Diagnose non-sensical max bytes to align.
2498 if (MaxBytesLoc.isValid()) {
2499 if (MaxBytesToFill < 1) {
2500 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2501 "many bytes, ignoring maximum bytes expression");
2505 if (MaxBytesToFill >= Alignment) {
2506 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2512 // Check whether we should use optimal code alignment for this .align
2514 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2515 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2516 ValueSize == 1 && UseCodeAlign) {
2517 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2519 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2520 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2527 /// ParseDirectiveFile
2528 /// ::= .file [number] filename
2529 /// ::= .file number directory filename
2530 bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2531 // FIXME: I'm not sure what this is.
2532 int64_t FileNumber = -1;
2533 SMLoc FileNumberLoc = getLexer().getLoc();
2534 if (getLexer().is(AsmToken::Integer)) {
2535 FileNumber = getTok().getIntVal();
2539 return TokError("file number less than one");
2542 if (getLexer().isNot(AsmToken::String))
2543 return TokError("unexpected token in '.file' directive");
2545 // Usually the directory and filename together, otherwise just the directory.
2546 StringRef Path = getTok().getString();
2547 Path = Path.substr(1, Path.size()-2);
2550 StringRef Directory;
2552 if (getLexer().is(AsmToken::String)) {
2553 if (FileNumber == -1)
2554 return TokError("explicit path specified, but no file number");
2555 Filename = getTok().getString();
2556 Filename = Filename.substr(1, Filename.size()-2);
2563 if (getLexer().isNot(AsmToken::EndOfStatement))
2564 return TokError("unexpected token in '.file' directive");
2566 if (FileNumber == -1)
2567 getStreamer().EmitFileDirective(Filename);
2569 if (getContext().getGenDwarfForAssembly() == true)
2570 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2571 "used to generate dwarf debug info for assembly code");
2573 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2574 Error(FileNumberLoc, "file number already allocated");
2580 /// ParseDirectiveLine
2581 /// ::= .line [number]
2582 bool AsmParser::ParseDirectiveLine() {
2583 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2584 if (getLexer().isNot(AsmToken::Integer))
2585 return TokError("unexpected token in '.line' directive");
2587 int64_t LineNumber = getTok().getIntVal();
2591 // FIXME: Do something with the .line.
2594 if (getLexer().isNot(AsmToken::EndOfStatement))
2595 return TokError("unexpected token in '.line' directive");
2600 /// ParseDirectiveLoc
2601 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2602 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2603 /// The first number is a file number, must have been previously assigned with
2604 /// a .file directive, the second number is the line number and optionally the
2605 /// third number is a column position (zero if not specified). The remaining
2606 /// optional items are .loc sub-directives.
2607 bool AsmParser::ParseDirectiveLoc() {
2608 if (getLexer().isNot(AsmToken::Integer))
2609 return TokError("unexpected token in '.loc' directive");
2610 int64_t FileNumber = getTok().getIntVal();
2612 return TokError("file number less than one in '.loc' directive");
2613 if (!getContext().isValidDwarfFileNumber(FileNumber))
2614 return TokError("unassigned file number in '.loc' directive");
2617 int64_t LineNumber = 0;
2618 if (getLexer().is(AsmToken::Integer)) {
2619 LineNumber = getTok().getIntVal();
2621 return TokError("line number less than one in '.loc' directive");
2625 int64_t ColumnPos = 0;
2626 if (getLexer().is(AsmToken::Integer)) {
2627 ColumnPos = getTok().getIntVal();
2629 return TokError("column position less than zero in '.loc' directive");
2633 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2635 int64_t Discriminator = 0;
2636 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2638 if (getLexer().is(AsmToken::EndOfStatement))
2642 SMLoc Loc = getTok().getLoc();
2643 if (parseIdentifier(Name))
2644 return TokError("unexpected token in '.loc' directive");
2646 if (Name == "basic_block")
2647 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2648 else if (Name == "prologue_end")
2649 Flags |= DWARF2_FLAG_PROLOGUE_END;
2650 else if (Name == "epilogue_begin")
2651 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2652 else if (Name == "is_stmt") {
2653 Loc = getTok().getLoc();
2654 const MCExpr *Value;
2655 if (parseExpression(Value))
2657 // The expression must be the constant 0 or 1.
2658 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2659 int Value = MCE->getValue();
2661 Flags &= ~DWARF2_FLAG_IS_STMT;
2662 else if (Value == 1)
2663 Flags |= DWARF2_FLAG_IS_STMT;
2665 return Error(Loc, "is_stmt value not 0 or 1");
2667 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2669 } else if (Name == "isa") {
2670 Loc = getTok().getLoc();
2671 const MCExpr *Value;
2672 if (parseExpression(Value))
2674 // The expression must be a constant greater or equal to 0.
2675 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2676 int Value = MCE->getValue();
2678 return Error(Loc, "isa number less than zero");
2681 return Error(Loc, "isa number not a constant value");
2683 } else if (Name == "discriminator") {
2684 if (parseAbsoluteExpression(Discriminator))
2687 return Error(Loc, "unknown sub-directive in '.loc' directive");
2690 if (getLexer().is(AsmToken::EndOfStatement))
2695 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2696 Isa, Discriminator, StringRef());
2701 /// ParseDirectiveStabs
2702 /// ::= .stabs string, number, number, number
2703 bool AsmParser::ParseDirectiveStabs() {
2704 return TokError("unsupported directive '.stabs'");
2707 /// ParseDirectiveCFISections
2708 /// ::= .cfi_sections section [, section]
2709 bool AsmParser::ParseDirectiveCFISections() {
2714 if (parseIdentifier(Name))
2715 return TokError("Expected an identifier");
2717 if (Name == ".eh_frame")
2719 else if (Name == ".debug_frame")
2722 if (getLexer().is(AsmToken::Comma)) {
2725 if (parseIdentifier(Name))
2726 return TokError("Expected an identifier");
2728 if (Name == ".eh_frame")
2730 else if (Name == ".debug_frame")
2734 getStreamer().EmitCFISections(EH, Debug);
2738 /// ParseDirectiveCFIStartProc
2739 /// ::= .cfi_startproc
2740 bool AsmParser::ParseDirectiveCFIStartProc() {
2741 getStreamer().EmitCFIStartProc();
2745 /// ParseDirectiveCFIEndProc
2746 /// ::= .cfi_endproc
2747 bool AsmParser::ParseDirectiveCFIEndProc() {
2748 getStreamer().EmitCFIEndProc();
2752 /// ParseRegisterOrRegisterNumber - parse register name or number.
2753 bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2754 SMLoc DirectiveLoc) {
2757 if (getLexer().isNot(AsmToken::Integer)) {
2758 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2760 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2762 return parseAbsoluteExpression(Register);
2767 /// ParseDirectiveCFIDefCfa
2768 /// ::= .cfi_def_cfa register, offset
2769 bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2770 int64_t Register = 0;
2771 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2774 if (getLexer().isNot(AsmToken::Comma))
2775 return TokError("unexpected token in directive");
2779 if (parseAbsoluteExpression(Offset))
2782 getStreamer().EmitCFIDefCfa(Register, Offset);
2786 /// ParseDirectiveCFIDefCfaOffset
2787 /// ::= .cfi_def_cfa_offset offset
2788 bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2790 if (parseAbsoluteExpression(Offset))
2793 getStreamer().EmitCFIDefCfaOffset(Offset);
2797 /// ParseDirectiveCFIRegister
2798 /// ::= .cfi_register register, register
2799 bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2800 int64_t Register1 = 0;
2801 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2804 if (getLexer().isNot(AsmToken::Comma))
2805 return TokError("unexpected token in directive");
2808 int64_t Register2 = 0;
2809 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2812 getStreamer().EmitCFIRegister(Register1, Register2);
2816 /// ParseDirectiveCFIAdjustCfaOffset
2817 /// ::= .cfi_adjust_cfa_offset adjustment
2818 bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2819 int64_t Adjustment = 0;
2820 if (parseAbsoluteExpression(Adjustment))
2823 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2827 /// ParseDirectiveCFIDefCfaRegister
2828 /// ::= .cfi_def_cfa_register register
2829 bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2830 int64_t Register = 0;
2831 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2834 getStreamer().EmitCFIDefCfaRegister(Register);
2838 /// ParseDirectiveCFIOffset
2839 /// ::= .cfi_offset register, offset
2840 bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2841 int64_t Register = 0;
2844 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2847 if (getLexer().isNot(AsmToken::Comma))
2848 return TokError("unexpected token in directive");
2851 if (parseAbsoluteExpression(Offset))
2854 getStreamer().EmitCFIOffset(Register, Offset);
2858 /// ParseDirectiveCFIRelOffset
2859 /// ::= .cfi_rel_offset register, offset
2860 bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2861 int64_t Register = 0;
2863 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2866 if (getLexer().isNot(AsmToken::Comma))
2867 return TokError("unexpected token in directive");
2871 if (parseAbsoluteExpression(Offset))
2874 getStreamer().EmitCFIRelOffset(Register, Offset);
2878 static bool isValidEncoding(int64_t Encoding) {
2879 if (Encoding & ~0xff)
2882 if (Encoding == dwarf::DW_EH_PE_omit)
2885 const unsigned Format = Encoding & 0xf;
2886 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2887 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2888 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2889 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2892 const unsigned Application = Encoding & 0x70;
2893 if (Application != dwarf::DW_EH_PE_absptr &&
2894 Application != dwarf::DW_EH_PE_pcrel)
2900 /// ParseDirectiveCFIPersonalityOrLsda
2901 /// IsPersonality true for cfi_personality, false for cfi_lsda
2902 /// ::= .cfi_personality encoding, [symbol_name]
2903 /// ::= .cfi_lsda encoding, [symbol_name]
2904 bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2905 int64_t Encoding = 0;
2906 if (parseAbsoluteExpression(Encoding))
2908 if (Encoding == dwarf::DW_EH_PE_omit)
2911 if (!isValidEncoding(Encoding))
2912 return TokError("unsupported encoding.");
2914 if (getLexer().isNot(AsmToken::Comma))
2915 return TokError("unexpected token in directive");
2919 if (parseIdentifier(Name))
2920 return TokError("expected identifier in directive");
2922 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2925 getStreamer().EmitCFIPersonality(Sym, Encoding);
2927 getStreamer().EmitCFILsda(Sym, Encoding);
2931 /// ParseDirectiveCFIRememberState
2932 /// ::= .cfi_remember_state
2933 bool AsmParser::ParseDirectiveCFIRememberState() {
2934 getStreamer().EmitCFIRememberState();
2938 /// ParseDirectiveCFIRestoreState
2939 /// ::= .cfi_remember_state
2940 bool AsmParser::ParseDirectiveCFIRestoreState() {
2941 getStreamer().EmitCFIRestoreState();
2945 /// ParseDirectiveCFISameValue
2946 /// ::= .cfi_same_value register
2947 bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2948 int64_t Register = 0;
2950 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2953 getStreamer().EmitCFISameValue(Register);
2957 /// ParseDirectiveCFIRestore
2958 /// ::= .cfi_restore register
2959 bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2960 int64_t Register = 0;
2961 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2964 getStreamer().EmitCFIRestore(Register);
2968 /// ParseDirectiveCFIEscape
2969 /// ::= .cfi_escape expression[,...]
2970 bool AsmParser::ParseDirectiveCFIEscape() {
2973 if (parseAbsoluteExpression(CurrValue))
2976 Values.push_back((uint8_t)CurrValue);
2978 while (getLexer().is(AsmToken::Comma)) {
2981 if (parseAbsoluteExpression(CurrValue))
2984 Values.push_back((uint8_t)CurrValue);
2987 getStreamer().EmitCFIEscape(Values);
2991 /// ParseDirectiveCFISignalFrame
2992 /// ::= .cfi_signal_frame
2993 bool AsmParser::ParseDirectiveCFISignalFrame() {
2994 if (getLexer().isNot(AsmToken::EndOfStatement))
2995 return Error(getLexer().getLoc(),
2996 "unexpected token in '.cfi_signal_frame'");
2998 getStreamer().EmitCFISignalFrame();
3002 /// ParseDirectiveCFIUndefined
3003 /// ::= .cfi_undefined register
3004 bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3005 int64_t Register = 0;
3007 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3010 getStreamer().EmitCFIUndefined(Register);
3014 /// ParseDirectiveMacrosOnOff
3017 bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
3018 if (getLexer().isNot(AsmToken::EndOfStatement))
3019 return Error(getLexer().getLoc(),
3020 "unexpected token in '" + Directive + "' directive");
3022 SetMacrosEnabled(Directive == ".macros_on");
3026 /// ParseDirectiveMacro
3027 /// ::= .macro name [parameters]
3028 bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
3030 if (parseIdentifier(Name))
3031 return TokError("expected identifier in '.macro' directive");
3033 MCAsmMacroParameters Parameters;
3034 // Argument delimiter is initially unknown. It will be set by
3035 // ParseMacroArgument()
3036 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3037 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3039 MCAsmMacroParameter Parameter;
3040 if (parseIdentifier(Parameter.first))
3041 return TokError("expected identifier in '.macro' directive");
3043 if (getLexer().is(AsmToken::Equal)) {
3045 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3049 Parameters.push_back(Parameter);
3051 if (getLexer().is(AsmToken::Comma))
3053 else if (getLexer().is(AsmToken::EndOfStatement))
3058 // Eat the end of statement.
3061 AsmToken EndToken, StartToken = getTok();
3063 // Lex the macro definition.
3065 // Check whether we have reached the end of the file.
3066 if (getLexer().is(AsmToken::Eof))
3067 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3069 // Otherwise, check whether we have reach the .endmacro.
3070 if (getLexer().is(AsmToken::Identifier) &&
3071 (getTok().getIdentifier() == ".endm" ||
3072 getTok().getIdentifier() == ".endmacro")) {
3073 EndToken = getTok();
3075 if (getLexer().isNot(AsmToken::EndOfStatement))
3076 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3081 // Otherwise, scan til the end of the statement.
3082 eatToEndOfStatement();
3085 if (LookupMacro(Name)) {
3086 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3089 const char *BodyStart = StartToken.getLoc().getPointer();
3090 const char *BodyEnd = EndToken.getLoc().getPointer();
3091 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3092 CheckForBadMacro(DirectiveLoc, Name, Body, Parameters);
3093 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3097 /// CheckForBadMacro
3099 /// With the support added for named parameters there may be code out there that
3100 /// is transitioning from positional parameters. In versions of gas that did
3101 /// not support named parameters they would be ignored on the macro defintion.
3102 /// But to support both styles of parameters this is not possible so if a macro
3103 /// defintion has named parameters but does not use them and has what appears
3104 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3105 /// warning that the positional parameter found in body which have no effect.
3106 /// Hoping the developer will either remove the named parameters from the macro
3107 /// definiton so the positional parameters get used if that was what was
3108 /// intended or change the macro to use the named parameters. It is possible
3109 /// this warning will trigger when the none of the named parameters are used
3110 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3111 void AsmParser::CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3113 MCAsmMacroParameters Parameters) {
3114 // If this macro is not defined with named parameters the warning we are
3115 // checking for here doesn't apply.
3116 unsigned NParameters = Parameters.size();
3117 if (NParameters == 0)
3120 bool NamedParametersFound = false;
3121 bool PositionalParametersFound = false;
3123 // Look at the body of the macro for use of both the named parameters and what
3124 // are likely to be positional parameters. This is what expandMacro() is
3125 // doing when it finds the parameters in the body.
3126 while (!Body.empty()) {
3127 // Scan for the next possible parameter.
3128 std::size_t End = Body.size(), Pos = 0;
3129 for (; Pos != End; ++Pos) {
3130 // Check for a substitution or escape.
3131 // This macro is defined with parameters, look for \foo, \bar, etc.
3132 if (Body[Pos] == '\\' && Pos + 1 != End)
3135 // This macro should have parameters, but look for $0, $1, ..., $n too.
3136 if (Body[Pos] != '$' || Pos + 1 == End)
3138 char Next = Body[Pos + 1];
3139 if (Next == '$' || Next == 'n' ||
3140 isdigit(static_cast<unsigned char>(Next)))
3144 // Check if we reached the end.
3148 if (Body[Pos] == '$') {
3149 switch (Body[Pos+1]) {
3154 // $n => number of arguments
3156 PositionalParametersFound = true;
3159 // $[0-9] => argument
3161 PositionalParametersFound = true;
3167 unsigned I = Pos + 1;
3168 while (isIdentifierChar(Body[I]) && I + 1 != End)
3171 const char *Begin = Body.data() + Pos +1;
3172 StringRef Argument(Begin, I - (Pos +1));
3174 for (; Index < NParameters; ++Index)
3175 if (Parameters[Index].first == Argument)
3178 if (Index == NParameters) {
3179 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
3185 NamedParametersFound = true;
3186 Pos += 1 + Argument.size();
3189 // Update the scan point.
3190 Body = Body.substr(Pos);
3193 if (!NamedParametersFound && PositionalParametersFound)
3194 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3195 "used in macro body, possible positional parameter "
3196 "found in body which will have no effect");
3199 /// ParseDirectiveEndMacro
3202 bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3203 if (getLexer().isNot(AsmToken::EndOfStatement))
3204 return TokError("unexpected token in '" + Directive + "' directive");
3206 // If we are inside a macro instantiation, terminate the current
3208 if (InsideMacroInstantiation()) {
3213 // Otherwise, this .endmacro is a stray entry in the file; well formed
3214 // .endmacro directives are handled during the macro definition parsing.
3215 return TokError("unexpected '" + Directive + "' in file, "
3216 "no current macro definition");
3219 /// ParseDirectivePurgeMacro
3221 bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3223 if (parseIdentifier(Name))
3224 return TokError("expected identifier in '.purgem' directive");
3226 if (getLexer().isNot(AsmToken::EndOfStatement))
3227 return TokError("unexpected token in '.purgem' directive");
3229 if (!LookupMacro(Name))
3230 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3232 UndefineMacro(Name);
3236 /// ParseDirectiveBundleAlignMode
3237 /// ::= {.bundle_align_mode} expression
3238 bool AsmParser::ParseDirectiveBundleAlignMode() {
3239 checkForValidSection();
3241 // Expect a single argument: an expression that evaluates to a constant
3242 // in the inclusive range 0-30.
3243 SMLoc ExprLoc = getLexer().getLoc();
3244 int64_t AlignSizePow2;
3245 if (parseAbsoluteExpression(AlignSizePow2))
3247 else if (getLexer().isNot(AsmToken::EndOfStatement))
3248 return TokError("unexpected token after expression in"
3249 " '.bundle_align_mode' directive");
3250 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3251 return Error(ExprLoc,
3252 "invalid bundle alignment size (expected between 0 and 30)");
3256 // Because of AlignSizePow2's verified range we can safely truncate it to
3258 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3262 /// ParseDirectiveBundleLock
3263 /// ::= {.bundle_lock} [align_to_end]
3264 bool AsmParser::ParseDirectiveBundleLock() {
3265 checkForValidSection();
3266 bool AlignToEnd = false;
3268 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3270 SMLoc Loc = getTok().getLoc();
3271 const char *kInvalidOptionError =
3272 "invalid option for '.bundle_lock' directive";
3274 if (parseIdentifier(Option))
3275 return Error(Loc, kInvalidOptionError);
3277 if (Option != "align_to_end")
3278 return Error(Loc, kInvalidOptionError);
3279 else if (getLexer().isNot(AsmToken::EndOfStatement))
3281 "unexpected token after '.bundle_lock' directive option");
3287 getStreamer().EmitBundleLock(AlignToEnd);
3291 /// ParseDirectiveBundleLock
3292 /// ::= {.bundle_lock}
3293 bool AsmParser::ParseDirectiveBundleUnlock() {
3294 checkForValidSection();
3296 if (getLexer().isNot(AsmToken::EndOfStatement))
3297 return TokError("unexpected token in '.bundle_unlock' directive");
3300 getStreamer().EmitBundleUnlock();
3304 /// ParseDirectiveSpace
3305 /// ::= (.skip | .space) expression [ , expression ]
3306 bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
3307 checkForValidSection();
3310 if (parseAbsoluteExpression(NumBytes))
3313 int64_t FillExpr = 0;
3314 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3315 if (getLexer().isNot(AsmToken::Comma))
3316 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3319 if (parseAbsoluteExpression(FillExpr))
3322 if (getLexer().isNot(AsmToken::EndOfStatement))
3323 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3329 return TokError("invalid number of bytes in '" +
3330 Twine(IDVal) + "' directive");
3332 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3333 getStreamer().EmitFill(NumBytes, FillExpr);
3338 /// ParseDirectiveLEB128
3339 /// ::= (.sleb128 | .uleb128) expression
3340 bool AsmParser::ParseDirectiveLEB128(bool Signed) {
3341 checkForValidSection();
3342 const MCExpr *Value;
3344 if (parseExpression(Value))
3347 if (getLexer().isNot(AsmToken::EndOfStatement))
3348 return TokError("unexpected token in directive");
3351 getStreamer().EmitSLEB128Value(Value);
3353 getStreamer().EmitULEB128Value(Value);
3358 /// ParseDirectiveSymbolAttribute
3359 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3360 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3361 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3364 SMLoc Loc = getTok().getLoc();
3366 if (parseIdentifier(Name))
3367 return Error(Loc, "expected identifier in directive");
3369 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3371 // Assembler local symbols don't make any sense here. Complain loudly.
3372 if (Sym->isTemporary())
3373 return Error(Loc, "non-local symbol required in directive");
3375 getStreamer().EmitSymbolAttribute(Sym, Attr);
3377 if (getLexer().is(AsmToken::EndOfStatement))
3380 if (getLexer().isNot(AsmToken::Comma))
3381 return TokError("unexpected token in directive");
3390 /// ParseDirectiveComm
3391 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3392 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
3393 checkForValidSection();
3395 SMLoc IDLoc = getLexer().getLoc();
3397 if (parseIdentifier(Name))
3398 return TokError("expected identifier in directive");
3400 // Handle the identifier as the key symbol.
3401 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3403 if (getLexer().isNot(AsmToken::Comma))
3404 return TokError("unexpected token in directive");
3408 SMLoc SizeLoc = getLexer().getLoc();
3409 if (parseAbsoluteExpression(Size))
3412 int64_t Pow2Alignment = 0;
3413 SMLoc Pow2AlignmentLoc;
3414 if (getLexer().is(AsmToken::Comma)) {
3416 Pow2AlignmentLoc = getLexer().getLoc();
3417 if (parseAbsoluteExpression(Pow2Alignment))
3420 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3421 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3422 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3424 // If this target takes alignments in bytes (not log) validate and convert.
3425 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3426 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3427 if (!isPowerOf2_64(Pow2Alignment))
3428 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3429 Pow2Alignment = Log2_64(Pow2Alignment);
3433 if (getLexer().isNot(AsmToken::EndOfStatement))
3434 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3438 // NOTE: a size of zero for a .comm should create a undefined symbol
3439 // but a size of .lcomm creates a bss symbol of size zero.
3441 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3442 "be less than zero");
3444 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3445 // may internally end up wanting an alignment in bytes.
3446 // FIXME: Diagnose overflow.
3447 if (Pow2Alignment < 0)
3448 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3449 "alignment, can't be less than zero");
3451 if (!Sym->isUndefined())
3452 return Error(IDLoc, "invalid symbol redefinition");
3454 // Create the Symbol as a common or local common with Size and Pow2Alignment
3456 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3460 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3464 /// ParseDirectiveAbort
3465 /// ::= .abort [... message ...]
3466 bool AsmParser::ParseDirectiveAbort() {
3467 // FIXME: Use loc from directive.
3468 SMLoc Loc = getLexer().getLoc();
3470 StringRef Str = parseStringToEndOfStatement();
3471 if (getLexer().isNot(AsmToken::EndOfStatement))
3472 return TokError("unexpected token in '.abort' directive");
3477 Error(Loc, ".abort detected. Assembly stopping.");
3479 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3480 // FIXME: Actually abort assembly here.
3485 /// ParseDirectiveInclude
3486 /// ::= .include "filename"
3487 bool AsmParser::ParseDirectiveInclude() {
3488 if (getLexer().isNot(AsmToken::String))
3489 return TokError("expected string in '.include' directive");
3491 std::string Filename = getTok().getString();
3492 SMLoc IncludeLoc = getLexer().getLoc();
3495 if (getLexer().isNot(AsmToken::EndOfStatement))
3496 return TokError("unexpected token in '.include' directive");
3498 // Strip the quotes.
3499 Filename = Filename.substr(1, Filename.size()-2);
3501 // Attempt to switch the lexer to the included file before consuming the end
3502 // of statement to avoid losing it when we switch.
3503 if (EnterIncludeFile(Filename)) {
3504 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3511 /// ParseDirectiveIncbin
3512 /// ::= .incbin "filename"
3513 bool AsmParser::ParseDirectiveIncbin() {
3514 if (getLexer().isNot(AsmToken::String))
3515 return TokError("expected string in '.incbin' directive");
3517 std::string Filename = getTok().getString();
3518 SMLoc IncbinLoc = getLexer().getLoc();
3521 if (getLexer().isNot(AsmToken::EndOfStatement))
3522 return TokError("unexpected token in '.incbin' directive");
3524 // Strip the quotes.
3525 Filename = Filename.substr(1, Filename.size()-2);
3527 // Attempt to process the included file.
3528 if (ProcessIncbinFile(Filename)) {
3529 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3536 /// ParseDirectiveIf
3537 /// ::= .if expression
3538 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
3539 TheCondStack.push_back(TheCondState);
3540 TheCondState.TheCond = AsmCond::IfCond;
3541 if (TheCondState.Ignore) {
3542 eatToEndOfStatement();
3545 if (parseAbsoluteExpression(ExprValue))
3548 if (getLexer().isNot(AsmToken::EndOfStatement))
3549 return TokError("unexpected token in '.if' directive");
3553 TheCondState.CondMet = ExprValue;
3554 TheCondState.Ignore = !TheCondState.CondMet;
3560 /// ParseDirectiveIfb
3562 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3563 TheCondStack.push_back(TheCondState);
3564 TheCondState.TheCond = AsmCond::IfCond;
3566 if (TheCondState.Ignore) {
3567 eatToEndOfStatement();
3569 StringRef Str = parseStringToEndOfStatement();
3571 if (getLexer().isNot(AsmToken::EndOfStatement))
3572 return TokError("unexpected token in '.ifb' directive");
3576 TheCondState.CondMet = ExpectBlank == Str.empty();
3577 TheCondState.Ignore = !TheCondState.CondMet;
3583 /// ParseDirectiveIfc
3584 /// ::= .ifc string1, string2
3585 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3586 TheCondStack.push_back(TheCondState);
3587 TheCondState.TheCond = AsmCond::IfCond;
3589 if (TheCondState.Ignore) {
3590 eatToEndOfStatement();
3592 StringRef Str1 = ParseStringToComma();
3594 if (getLexer().isNot(AsmToken::Comma))
3595 return TokError("unexpected token in '.ifc' directive");
3599 StringRef Str2 = parseStringToEndOfStatement();
3601 if (getLexer().isNot(AsmToken::EndOfStatement))
3602 return TokError("unexpected token in '.ifc' directive");
3606 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3607 TheCondState.Ignore = !TheCondState.CondMet;
3613 /// ParseDirectiveIfdef
3614 /// ::= .ifdef symbol
3615 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3617 TheCondStack.push_back(TheCondState);
3618 TheCondState.TheCond = AsmCond::IfCond;
3620 if (TheCondState.Ignore) {
3621 eatToEndOfStatement();
3623 if (parseIdentifier(Name))
3624 return TokError("expected identifier after '.ifdef'");
3628 MCSymbol *Sym = getContext().LookupSymbol(Name);
3631 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3633 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3634 TheCondState.Ignore = !TheCondState.CondMet;
3640 /// ParseDirectiveElseIf
3641 /// ::= .elseif expression
3642 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3643 if (TheCondState.TheCond != AsmCond::IfCond &&
3644 TheCondState.TheCond != AsmCond::ElseIfCond)
3645 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3647 TheCondState.TheCond = AsmCond::ElseIfCond;
3649 bool LastIgnoreState = false;
3650 if (!TheCondStack.empty())
3651 LastIgnoreState = TheCondStack.back().Ignore;
3652 if (LastIgnoreState || TheCondState.CondMet) {
3653 TheCondState.Ignore = true;
3654 eatToEndOfStatement();
3657 if (parseAbsoluteExpression(ExprValue))
3660 if (getLexer().isNot(AsmToken::EndOfStatement))
3661 return TokError("unexpected token in '.elseif' directive");
3664 TheCondState.CondMet = ExprValue;
3665 TheCondState.Ignore = !TheCondState.CondMet;
3671 /// ParseDirectiveElse
3673 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
3674 if (getLexer().isNot(AsmToken::EndOfStatement))
3675 return TokError("unexpected token in '.else' directive");
3679 if (TheCondState.TheCond != AsmCond::IfCond &&
3680 TheCondState.TheCond != AsmCond::ElseIfCond)
3681 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3683 TheCondState.TheCond = AsmCond::ElseCond;
3684 bool LastIgnoreState = false;
3685 if (!TheCondStack.empty())
3686 LastIgnoreState = TheCondStack.back().Ignore;
3687 if (LastIgnoreState || TheCondState.CondMet)
3688 TheCondState.Ignore = true;
3690 TheCondState.Ignore = false;
3695 /// ParseDirectiveEndIf
3697 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
3698 if (getLexer().isNot(AsmToken::EndOfStatement))
3699 return TokError("unexpected token in '.endif' directive");
3703 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3704 TheCondStack.empty())
3705 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3707 if (!TheCondStack.empty()) {
3708 TheCondState = TheCondStack.back();
3709 TheCondStack.pop_back();
3715 void AsmParser::initializeDirectiveKindMap() {
3716 DirectiveKindMap[".set"] = DK_SET;
3717 DirectiveKindMap[".equ"] = DK_EQU;
3718 DirectiveKindMap[".equiv"] = DK_EQUIV;
3719 DirectiveKindMap[".ascii"] = DK_ASCII;
3720 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3721 DirectiveKindMap[".string"] = DK_STRING;
3722 DirectiveKindMap[".byte"] = DK_BYTE;
3723 DirectiveKindMap[".short"] = DK_SHORT;
3724 DirectiveKindMap[".value"] = DK_VALUE;
3725 DirectiveKindMap[".2byte"] = DK_2BYTE;
3726 DirectiveKindMap[".long"] = DK_LONG;
3727 DirectiveKindMap[".int"] = DK_INT;
3728 DirectiveKindMap[".4byte"] = DK_4BYTE;
3729 DirectiveKindMap[".quad"] = DK_QUAD;
3730 DirectiveKindMap[".8byte"] = DK_8BYTE;
3731 DirectiveKindMap[".single"] = DK_SINGLE;
3732 DirectiveKindMap[".float"] = DK_FLOAT;
3733 DirectiveKindMap[".double"] = DK_DOUBLE;
3734 DirectiveKindMap[".align"] = DK_ALIGN;
3735 DirectiveKindMap[".align32"] = DK_ALIGN32;
3736 DirectiveKindMap[".balign"] = DK_BALIGN;
3737 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3738 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3739 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3740 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3741 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3742 DirectiveKindMap[".org"] = DK_ORG;
3743 DirectiveKindMap[".fill"] = DK_FILL;
3744 DirectiveKindMap[".zero"] = DK_ZERO;
3745 DirectiveKindMap[".extern"] = DK_EXTERN;
3746 DirectiveKindMap[".globl"] = DK_GLOBL;
3747 DirectiveKindMap[".global"] = DK_GLOBAL;
3748 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3749 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3750 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3751 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3752 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3753 DirectiveKindMap[".reference"] = DK_REFERENCE;
3754 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3755 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3756 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3757 DirectiveKindMap[".comm"] = DK_COMM;
3758 DirectiveKindMap[".common"] = DK_COMMON;
3759 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3760 DirectiveKindMap[".abort"] = DK_ABORT;
3761 DirectiveKindMap[".include"] = DK_INCLUDE;
3762 DirectiveKindMap[".incbin"] = DK_INCBIN;
3763 DirectiveKindMap[".code16"] = DK_CODE16;
3764 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3765 DirectiveKindMap[".rept"] = DK_REPT;
3766 DirectiveKindMap[".irp"] = DK_IRP;
3767 DirectiveKindMap[".irpc"] = DK_IRPC;
3768 DirectiveKindMap[".endr"] = DK_ENDR;
3769 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3770 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3771 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3772 DirectiveKindMap[".if"] = DK_IF;
3773 DirectiveKindMap[".ifb"] = DK_IFB;
3774 DirectiveKindMap[".ifnb"] = DK_IFNB;
3775 DirectiveKindMap[".ifc"] = DK_IFC;
3776 DirectiveKindMap[".ifnc"] = DK_IFNC;
3777 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3778 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3779 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3780 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3781 DirectiveKindMap[".else"] = DK_ELSE;
3782 DirectiveKindMap[".endif"] = DK_ENDIF;
3783 DirectiveKindMap[".skip"] = DK_SKIP;
3784 DirectiveKindMap[".space"] = DK_SPACE;
3785 DirectiveKindMap[".file"] = DK_FILE;
3786 DirectiveKindMap[".line"] = DK_LINE;
3787 DirectiveKindMap[".loc"] = DK_LOC;
3788 DirectiveKindMap[".stabs"] = DK_STABS;
3789 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3790 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3791 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3792 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3793 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3794 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3795 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3796 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3797 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3798 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3799 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3800 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3801 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3802 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3803 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3804 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3805 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3806 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3807 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3808 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3809 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3810 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3811 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3812 DirectiveKindMap[".macro"] = DK_MACRO;
3813 DirectiveKindMap[".endm"] = DK_ENDM;
3814 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3815 DirectiveKindMap[".purgem"] = DK_PURGEM;
3819 MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3820 AsmToken EndToken, StartToken = getTok();
3822 unsigned NestLevel = 0;
3824 // Check whether we have reached the end of the file.
3825 if (getLexer().is(AsmToken::Eof)) {
3826 Error(DirectiveLoc, "no matching '.endr' in definition");
3830 if (Lexer.is(AsmToken::Identifier) &&
3831 (getTok().getIdentifier() == ".rept")) {
3835 // Otherwise, check whether we have reached the .endr.
3836 if (Lexer.is(AsmToken::Identifier) &&
3837 getTok().getIdentifier() == ".endr") {
3838 if (NestLevel == 0) {
3839 EndToken = getTok();
3841 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3842 TokError("unexpected token in '.endr' directive");
3850 // Otherwise, scan till the end of the statement.
3851 eatToEndOfStatement();
3854 const char *BodyStart = StartToken.getLoc().getPointer();
3855 const char *BodyEnd = EndToken.getLoc().getPointer();
3856 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3858 // We Are Anonymous.
3860 MCAsmMacroParameters Parameters;
3861 return new MCAsmMacro(Name, Body, Parameters);
3864 void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
3865 raw_svector_ostream &OS) {
3868 MemoryBuffer *Instantiation =
3869 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3871 // Create the macro instantiation object and add to the current macro
3872 // instantiation stack.
3873 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3877 ActiveMacros.push_back(MI);
3879 // Jump to the macro instantiation and prime the lexer.
3880 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3881 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3885 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3887 if (parseAbsoluteExpression(Count))
3888 return TokError("unexpected token in '.rept' directive");
3891 return TokError("Count is negative");
3893 if (Lexer.isNot(AsmToken::EndOfStatement))
3894 return TokError("unexpected token in '.rept' directive");
3896 // Eat the end of statement.
3899 // Lex the rept definition.
3900 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3904 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3905 // to hold the macro body with substitutions.
3906 SmallString<256> Buf;
3907 MCAsmMacroParameters Parameters;
3908 MCAsmMacroArguments A;
3909 raw_svector_ostream OS(Buf);
3911 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3914 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3919 /// ParseDirectiveIrp
3920 /// ::= .irp symbol,values
3921 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3922 MCAsmMacroParameters Parameters;
3923 MCAsmMacroParameter Parameter;
3925 if (parseIdentifier(Parameter.first))
3926 return TokError("expected identifier in '.irp' directive");
3928 Parameters.push_back(Parameter);
3930 if (Lexer.isNot(AsmToken::Comma))
3931 return TokError("expected comma in '.irp' directive");
3935 MCAsmMacroArguments A;
3936 if (ParseMacroArguments(0, A))
3939 // Eat the end of statement.
3942 // Lex the irp definition.
3943 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3947 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3948 // to hold the macro body with substitutions.
3949 SmallString<256> Buf;
3950 raw_svector_ostream OS(Buf);
3952 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3953 MCAsmMacroArguments Args;
3956 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3960 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3965 /// ParseDirectiveIrpc
3966 /// ::= .irpc symbol,values
3967 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3968 MCAsmMacroParameters Parameters;
3969 MCAsmMacroParameter Parameter;
3971 if (parseIdentifier(Parameter.first))
3972 return TokError("expected identifier in '.irpc' directive");
3974 Parameters.push_back(Parameter);
3976 if (Lexer.isNot(AsmToken::Comma))
3977 return TokError("expected comma in '.irpc' directive");
3981 MCAsmMacroArguments A;
3982 if (ParseMacroArguments(0, A))
3985 if (A.size() != 1 || A.front().size() != 1)
3986 return TokError("unexpected token in '.irpc' directive");
3988 // Eat the end of statement.
3991 // Lex the irpc definition.
3992 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3996 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3997 // to hold the macro body with substitutions.
3998 SmallString<256> Buf;
3999 raw_svector_ostream OS(Buf);
4001 StringRef Values = A.front().front().getString();
4002 std::size_t I, End = Values.size();
4003 for (I = 0; I < End; ++I) {
4004 MCAsmMacroArgument Arg;
4005 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
4007 MCAsmMacroArguments Args;
4008 Args.push_back(Arg);
4010 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4014 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
4019 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
4020 if (ActiveMacros.empty())
4021 return TokError("unmatched '.endr' directive");
4023 // The only .repl that should get here are the ones created by
4024 // InstantiateMacroLikeBody.
4025 assert(getLexer().is(AsmToken::EndOfStatement));
4031 bool AsmParser::ParseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4033 const MCExpr *Value;
4034 SMLoc ExprLoc = getLexer().getLoc();
4035 if (parseExpression(Value))
4037 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4039 return Error(ExprLoc, "unexpected expression in _emit");
4040 uint64_t IntValue = MCE->getValue();
4041 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4042 return Error(ExprLoc, "literal value out of range for directive");
4044 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4048 bool AsmParser::ParseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4049 const MCExpr *Value;
4050 SMLoc ExprLoc = getLexer().getLoc();
4051 if (parseExpression(Value))
4053 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4055 return Error(ExprLoc, "unexpected expression in align");
4056 uint64_t IntValue = MCE->getValue();
4057 if (!isPowerOf2_64(IntValue))
4058 return Error(ExprLoc, "literal value not a power of two greater then zero");
4060 Info.AsmRewrites->push_back(AsmRewrite(AOK_Align, IDLoc, 5,
4061 Log2_64(IntValue)));
4065 // We are comparing pointers, but the pointers are relative to a single string.
4066 // Thus, this should always be deterministic.
4067 static int RewritesSort(const void *A, const void *B) {
4068 const AsmRewrite *AsmRewriteA = static_cast<const AsmRewrite *>(A);
4069 const AsmRewrite *AsmRewriteB = static_cast<const AsmRewrite *>(B);
4070 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4072 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4075 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4076 // rewrite to the same location. Make sure the SizeDirective rewrite is
4077 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4078 // ensures the sort algorithm is stable.
4079 if (AsmRewritePrecedence [AsmRewriteA->Kind] >
4080 AsmRewritePrecedence [AsmRewriteB->Kind])
4083 if (AsmRewritePrecedence [AsmRewriteA->Kind] <
4084 AsmRewritePrecedence [AsmRewriteB->Kind])
4086 llvm_unreachable ("Unstable rewrite sort.");
4090 AsmParser::parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
4091 unsigned &NumOutputs, unsigned &NumInputs,
4092 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4093 SmallVectorImpl<std::string> &Constraints,
4094 SmallVectorImpl<std::string> &Clobbers,
4095 const MCInstrInfo *MII,
4096 const MCInstPrinter *IP,
4097 MCAsmParserSemaCallback &SI) {
4098 SmallVector<void *, 4> InputDecls;
4099 SmallVector<void *, 4> OutputDecls;
4100 SmallVector<bool, 4> InputDeclsAddressOf;
4101 SmallVector<bool, 4> OutputDeclsAddressOf;
4102 SmallVector<std::string, 4> InputConstraints;
4103 SmallVector<std::string, 4> OutputConstraints;
4104 SmallVector<unsigned, 4> ClobberRegs;
4106 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4111 // While we have input, parse each statement.
4112 unsigned InputIdx = 0;
4113 unsigned OutputIdx = 0;
4114 while (getLexer().isNot(AsmToken::Eof)) {
4115 ParseStatementInfo Info(&AsmStrRewrites);
4116 if (ParseStatement(Info))
4119 if (Info.ParseError)
4122 if (Info.Opcode == ~0U)
4125 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4127 // Build the list of clobbers, outputs and inputs.
4128 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4129 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4132 if (Operand->isImm())
4135 // Register operand.
4136 if (Operand->isReg() && !Operand->needAddressOf()) {
4137 unsigned NumDefs = Desc.getNumDefs();
4139 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4140 ClobberRegs.push_back(Operand->getReg());
4144 // Expr/Input or Output.
4145 StringRef SymName = Operand->getSymName();
4146 if (SymName.empty())
4149 void *OpDecl = Operand->getOpDecl();
4153 bool isOutput = (i == 1) && Desc.mayStore();
4154 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4157 OutputDecls.push_back(OpDecl);
4158 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4159 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4160 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4162 InputDecls.push_back(OpDecl);
4163 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4164 InputConstraints.push_back(Operand->getConstraint().str());
4165 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4170 // Set the number of Outputs and Inputs.
4171 NumOutputs = OutputDecls.size();
4172 NumInputs = InputDecls.size();
4174 // Set the unique clobbers.
4175 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4176 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4178 Clobbers.assign(ClobberRegs.size(), std::string());
4179 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4180 raw_string_ostream OS(Clobbers[I]);
4181 IP->printRegName(OS, ClobberRegs[I]);
4184 // Merge the various outputs and inputs. Output are expected first.
4185 if (NumOutputs || NumInputs) {
4186 unsigned NumExprs = NumOutputs + NumInputs;
4187 OpDecls.resize(NumExprs);
4188 Constraints.resize(NumExprs);
4189 for (unsigned i = 0; i < NumOutputs; ++i) {
4190 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4191 Constraints[i] = OutputConstraints[i];
4193 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4194 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4195 Constraints[j] = InputConstraints[i];
4199 // Build the IR assembly string.
4200 std::string AsmStringIR;
4201 raw_string_ostream OS(AsmStringIR);
4202 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4203 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4204 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), RewritesSort);
4205 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4206 E = AsmStrRewrites.end();
4208 AsmRewriteKind Kind = (*I).Kind;
4209 if (Kind == AOK_Delete)
4212 const char *Loc = (*I).Loc.getPointer();
4213 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4215 // Emit everything up to the immediate/expression.
4216 unsigned Len = Loc - AsmStart;
4218 OS << StringRef(AsmStart, Len);
4220 // Skip the original expression.
4221 if (Kind == AOK_Skip) {
4222 AsmStart = Loc + (*I).Len;
4226 unsigned AdditionalSkip = 0;
4227 // Rewrite expressions in $N notation.
4231 OS << "$$" << (*I).Val;
4237 OS << '$' << InputIdx++;
4240 OS << '$' << OutputIdx++;
4242 case AOK_SizeDirective:
4245 case 8: OS << "byte ptr "; break;
4246 case 16: OS << "word ptr "; break;
4247 case 32: OS << "dword ptr "; break;
4248 case 64: OS << "qword ptr "; break;
4249 case 80: OS << "xword ptr "; break;
4250 case 128: OS << "xmmword ptr "; break;
4251 case 256: OS << "ymmword ptr "; break;
4258 unsigned Val = (*I).Val;
4259 OS << ".align " << Val;
4261 // Skip the original immediate.
4262 assert(Val < 10 && "Expected alignment less then 2^10.");
4263 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4266 case AOK_DotOperator:
4271 // Skip the original expression.
4272 AsmStart = Loc + (*I).Len + AdditionalSkip;
4275 // Emit the remainder of the asm string.
4276 if (AsmStart != AsmEnd)
4277 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4279 AsmString = OS.str();
4283 /// \brief Create an MCAsmParser instance.
4284 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
4285 MCContext &C, MCStreamer &Out,
4286 const MCAsmInfo &MAI) {
4287 return new AsmParser(SM, C, Out, MAI);