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/MCObjectFileInfo.h"
26 #include "llvm/MC/MCParser/AsmCond.h"
27 #include "llvm/MC/MCParser/AsmLexer.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCTargetAsmParser.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/raw_ostream.h"
48 FatalAssemblerWarnings("fatal-assembler-warnings",
49 cl::desc("Consider warnings as error"));
51 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
55 /// \brief Helper types for tracking macro definitions.
56 typedef std::vector<AsmToken> MCAsmMacroArgument;
57 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
58 typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
59 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
64 MCAsmMacroParameters Parameters;
67 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
68 Name(N), Body(B), Parameters(P) {}
70 MCAsmMacro(const MCAsmMacro& Other)
71 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
74 /// \brief Helper class for storing information about an active macro
76 struct MacroInstantiation {
77 /// The macro being instantiated.
78 const MCAsmMacro *TheMacro;
80 /// The macro instantiation with substitutions.
81 MemoryBuffer *Instantiation;
83 /// The location of the instantiation.
84 SMLoc InstantiationLoc;
86 /// The buffer where parsing should resume upon instantiation completion.
89 /// The location where parsing should resume upon instantiation completion.
93 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
97 struct ParseStatementInfo {
98 /// \brief The parsed operands from the last parsed statement.
99 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
101 /// \brief The opcode from the last parsed instruction.
104 /// \brief Was there an error parsing the inline assembly?
107 SmallVectorImpl<AsmRewrite> *AsmRewrites;
109 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
110 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
111 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
113 ~ParseStatementInfo() {
114 // Free any parsed operands.
115 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
116 delete ParsedOperands[i];
117 ParsedOperands.clear();
121 /// \brief The concrete assembly parser instance.
122 class AsmParser : public MCAsmParser {
123 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
124 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
129 const MCAsmInfo &MAI;
131 SourceMgr::DiagHandlerTy SavedDiagHandler;
132 void *SavedDiagContext;
133 MCAsmParserExtension *PlatformParser;
135 /// This is the current buffer index we're lexing from as managed by the
136 /// SourceMgr object.
139 AsmCond TheCondState;
140 std::vector<AsmCond> TheCondStack;
142 /// \brief maps directive names to handler methods in parser
143 /// extensions. Extensions register themselves in this map by calling
144 /// addDirectiveHandler.
145 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
147 /// \brief Map of currently defined macros.
148 StringMap<MCAsmMacro*> MacroMap;
150 /// \brief Stack of active macro instantiations.
151 std::vector<MacroInstantiation*> ActiveMacros;
153 /// \brief List of bodies of anonymous macros.
154 std::deque<MCAsmMacro> MacroLikeBodies;
156 /// Boolean tracking whether macro substitution is enabled.
157 unsigned MacrosEnabledFlag : 1;
159 /// Flag tracking whether any errors have been encountered.
160 unsigned HadError : 1;
162 /// The values from the last parsed cpp hash file line comment if any.
163 StringRef CppHashFilename;
164 int64_t CppHashLineNumber;
167 /// When generating dwarf for assembly source files we need to calculate the
168 /// logical line number based on the last parsed cpp hash file line comment
169 /// and current line. Since this is slow and messes up the SourceMgr's
170 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
171 SMLoc LastQueryIDLoc;
173 unsigned LastQueryLine;
175 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
176 unsigned AssemblerDialect;
178 /// \brief is Darwin compatibility enabled?
181 /// \brief Are we parsing ms-style inline assembly?
182 bool ParsingInlineAsm;
185 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
186 const MCAsmInfo &MAI);
187 virtual ~AsmParser();
189 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
191 virtual void addDirectiveHandler(StringRef Directive,
192 ExtensionDirectiveHandler Handler) {
193 ExtensionDirectiveMap[Directive] = Handler;
197 /// @name MCAsmParser Interface
200 virtual SourceMgr &getSourceManager() { return SrcMgr; }
201 virtual MCAsmLexer &getLexer() { return Lexer; }
202 virtual MCContext &getContext() { return Ctx; }
203 virtual MCStreamer &getStreamer() { return Out; }
204 virtual unsigned getAssemblerDialect() {
205 if (AssemblerDialect == ~0U)
206 return MAI.getAssemblerDialect();
208 return AssemblerDialect;
210 virtual void setAssemblerDialect(unsigned i) {
211 AssemblerDialect = i;
214 virtual bool Warning(SMLoc L, const Twine &Msg,
215 ArrayRef<SMRange> Ranges = None);
216 virtual bool Error(SMLoc L, const Twine &Msg,
217 ArrayRef<SMRange> Ranges = None);
219 virtual const AsmToken &Lex();
221 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
222 bool isParsingInlineAsm() { return ParsingInlineAsm; }
224 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
225 unsigned &NumOutputs, unsigned &NumInputs,
226 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
227 SmallVectorImpl<std::string> &Constraints,
228 SmallVectorImpl<std::string> &Clobbers,
229 const MCInstrInfo *MII,
230 const MCInstPrinter *IP,
231 MCAsmParserSemaCallback &SI);
233 bool parseExpression(const MCExpr *&Res);
234 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
235 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
236 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
237 virtual bool parseAbsoluteExpression(int64_t &Res);
239 /// \brief Parse an identifier or string (as a quoted identifier)
240 /// and set \p Res to the identifier contents.
241 virtual bool parseIdentifier(StringRef &Res);
242 virtual void eatToEndOfStatement();
244 virtual void checkForValidSection();
249 bool parseStatement(ParseStatementInfo &Info);
250 void eatToEndOfLine();
251 bool parseCppHashLineFilenameComment(const SMLoc &L);
253 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
254 MCAsmMacroParameters Parameters);
255 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
256 const MCAsmMacroParameters &Parameters,
257 const MCAsmMacroArguments &A,
260 /// \brief Are macros enabled in the parser?
261 bool areMacrosEnabled() {return MacrosEnabledFlag;}
263 /// \brief Control a flag in the parser that enables or disables macros.
264 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
266 /// \brief Lookup a previously defined macro.
267 /// \param Name Macro name.
268 /// \returns Pointer to macro. NULL if no such macro was defined.
269 const MCAsmMacro* lookupMacro(StringRef Name);
271 /// \brief Define a new macro with the given name and information.
272 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
274 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
275 void undefineMacro(StringRef Name);
277 /// \brief Are we inside a macro instantiation?
278 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
280 /// \brief Handle entry to macro instantiation.
282 /// \param M The macro.
283 /// \param NameLoc Instantiation location.
284 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
286 /// \brief Handle exit from macro instantiation.
287 void handleMacroExit();
289 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
290 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
291 /// correct delimiter by the method.
292 bool parseMacroArgument(MCAsmMacroArgument &MA,
293 AsmToken::TokenKind &ArgumentDelimiter);
295 /// \brief Parse all macro arguments for a given macro.
296 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
298 void printMacroInstantiations();
299 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
300 ArrayRef<SMRange> Ranges = None) const {
301 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
303 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
305 /// \brief Enter the specified file. This returns true on failure.
306 bool enterIncludeFile(const std::string &Filename);
308 /// \brief Process the specified file for the .incbin directive.
309 /// This returns true on failure.
310 bool processIncbinFile(const std::string &Filename);
312 /// \brief Reset the current lexer position to that given by \p Loc. The
313 /// current token is not set; clients should ensure Lex() is called
316 /// \param InBuffer If not -1, should be the known buffer id that contains the
318 void jumpToLoc(SMLoc Loc, int InBuffer=-1);
320 /// \brief Parse up to the end of statement and a return the contents from the
321 /// current token until the end of the statement; the current token on exit
322 /// will be either the EndOfStatement or EOF.
323 virtual StringRef parseStringToEndOfStatement();
325 /// \brief Parse until the end of a statement or a comma is encountered,
326 /// return the contents from the current token up to the end or comma.
327 StringRef parseStringToComma();
329 bool parseAssignment(StringRef Name, bool allow_redef,
330 bool NoDeadStrip = false);
332 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
333 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
334 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
336 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
338 // Generic (target and platform independent) directive parsing.
340 DK_NO_DIRECTIVE, // Placeholder
341 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
342 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
343 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
344 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
345 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
346 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
347 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
348 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
349 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
350 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
351 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
352 DK_ELSEIF, DK_ELSE, DK_ENDIF,
353 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
354 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
355 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
356 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
357 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
358 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
359 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
360 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
361 DK_SLEB128, DK_ULEB128,
365 /// \brief Maps directive name --> DirectiveKind enum, for
366 /// directives parsed by this class.
367 StringMap<DirectiveKind> DirectiveKindMap;
369 // ".ascii", ".asciz", ".string"
370 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
371 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
372 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
373 bool parseDirectiveFill(); // ".fill"
374 bool parseDirectiveZero(); // ".zero"
375 // ".set", ".equ", ".equiv"
376 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
377 bool parseDirectiveOrg(); // ".org"
378 // ".align{,32}", ".p2align{,w,l}"
379 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
381 // ".file", ".line", ".loc", ".stabs"
382 bool parseDirectiveFile(SMLoc DirectiveLoc);
383 bool parseDirectiveLine();
384 bool parseDirectiveLoc();
385 bool parseDirectiveStabs();
388 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
389 bool parseDirectiveCFIWindowSave();
390 bool parseDirectiveCFISections();
391 bool parseDirectiveCFIStartProc();
392 bool parseDirectiveCFIEndProc();
393 bool parseDirectiveCFIDefCfaOffset();
394 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
395 bool parseDirectiveCFIAdjustCfaOffset();
396 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
397 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
398 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
399 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
400 bool parseDirectiveCFIRememberState();
401 bool parseDirectiveCFIRestoreState();
402 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
403 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
404 bool parseDirectiveCFIEscape();
405 bool parseDirectiveCFISignalFrame();
406 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
409 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
410 bool parseDirectiveEndMacro(StringRef Directive);
411 bool parseDirectiveMacro(SMLoc DirectiveLoc);
412 bool parseDirectiveMacrosOnOff(StringRef Directive);
414 // ".bundle_align_mode"
415 bool parseDirectiveBundleAlignMode();
417 bool parseDirectiveBundleLock();
419 bool parseDirectiveBundleUnlock();
422 bool parseDirectiveSpace(StringRef IDVal);
424 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
425 bool parseDirectiveLEB128(bool Signed);
427 /// \brief Parse a directive like ".globl" which
428 /// accepts a single symbol (which should be a label or an external).
429 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
431 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
433 bool parseDirectiveAbort(); // ".abort"
434 bool parseDirectiveInclude(); // ".include"
435 bool parseDirectiveIncbin(); // ".incbin"
437 bool parseDirectiveIf(SMLoc DirectiveLoc); // ".if"
438 // ".ifb" or ".ifnb", depending on ExpectBlank.
439 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
440 // ".ifc" or ".ifnc", depending on ExpectEqual.
441 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
442 // ".ifdef" or ".ifndef", depending on expect_defined
443 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
444 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
445 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
446 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
447 virtual bool parseEscapedString(std::string &Data);
449 const MCExpr *applyModifierToExpr(const MCExpr *E,
450 MCSymbolRefExpr::VariantKind Variant);
452 // Macro-like directives
453 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
454 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
455 raw_svector_ostream &OS);
456 bool parseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
457 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
458 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
459 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
461 // "_emit" or "__emit"
462 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
466 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
469 bool parseDirectiveEnd(SMLoc DirectiveLoc);
471 void initializeDirectiveKindMap();
477 extern MCAsmParserExtension *createDarwinAsmParser();
478 extern MCAsmParserExtension *createELFAsmParser();
479 extern MCAsmParserExtension *createCOFFAsmParser();
483 enum { DEFAULT_ADDRSPACE = 0 };
485 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
486 const MCAsmInfo &_MAI)
487 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
488 PlatformParser(0), CurBuffer(0), MacrosEnabledFlag(true),
489 CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false),
490 ParsingInlineAsm(false) {
491 // Save the old handler.
492 SavedDiagHandler = SrcMgr.getDiagHandler();
493 SavedDiagContext = SrcMgr.getDiagContext();
494 // Set our own handler which calls the saved handler.
495 SrcMgr.setDiagHandler(DiagHandler, this);
496 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
498 // Initialize the platform / file format parser.
499 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
500 case MCObjectFileInfo::IsCOFF:
501 PlatformParser = createCOFFAsmParser();
502 PlatformParser->Initialize(*this);
504 case MCObjectFileInfo::IsMachO:
505 PlatformParser = createDarwinAsmParser();
506 PlatformParser->Initialize(*this);
509 case MCObjectFileInfo::IsELF:
510 PlatformParser = createELFAsmParser();
511 PlatformParser->Initialize(*this);
515 initializeDirectiveKindMap();
518 AsmParser::~AsmParser() {
519 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
521 // Destroy any macros.
522 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
525 delete it->getValue();
527 delete PlatformParser;
530 void AsmParser::printMacroInstantiations() {
531 // Print the active macro instantiation stack.
532 for (std::vector<MacroInstantiation *>::const_reverse_iterator
533 it = ActiveMacros.rbegin(),
534 ie = ActiveMacros.rend();
536 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
537 "while in macro instantiation");
540 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
541 if (FatalAssemblerWarnings)
542 return Error(L, Msg, Ranges);
543 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
544 printMacroInstantiations();
548 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
550 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
551 printMacroInstantiations();
555 bool AsmParser::enterIncludeFile(const std::string &Filename) {
556 std::string IncludedFile;
557 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
563 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
568 /// Process the specified .incbin file by searching for it in the include paths
569 /// then just emitting the byte contents of the file to the streamer. This
570 /// returns true on failure.
571 bool AsmParser::processIncbinFile(const std::string &Filename) {
572 std::string IncludedFile;
573 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
577 // Pick up the bytes from the file and emit them.
578 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
582 void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
583 if (InBuffer != -1) {
584 CurBuffer = InBuffer;
586 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
588 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
591 const AsmToken &AsmParser::Lex() {
592 const AsmToken *tok = &Lexer.Lex();
594 if (tok->is(AsmToken::Eof)) {
595 // If this is the end of an included file, pop the parent file off the
597 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
598 if (ParentIncludeLoc != SMLoc()) {
599 jumpToLoc(ParentIncludeLoc);
604 if (tok->is(AsmToken::Error))
605 Error(Lexer.getErrLoc(), Lexer.getErr());
610 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
611 // Create the initial section, if requested.
612 if (!NoInitialTextSection)
619 AsmCond StartingCondState = TheCondState;
621 // If we are generating dwarf for assembly source files save the initial text
622 // section and generate a .file directive.
623 if (getContext().getGenDwarfForAssembly()) {
624 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
625 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
626 getStreamer().EmitLabel(SectionStartSym);
627 getContext().setGenDwarfSectionStartSym(SectionStartSym);
628 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
630 getContext().getMainFileName());
633 // While we have input, parse each statement.
634 while (Lexer.isNot(AsmToken::Eof)) {
635 ParseStatementInfo Info;
636 if (!parseStatement(Info))
639 // We had an error, validate that one was emitted and recover by skipping to
641 assert(HadError && "Parse statement returned an error, but none emitted!");
642 eatToEndOfStatement();
645 if (TheCondState.TheCond != StartingCondState.TheCond ||
646 TheCondState.Ignore != StartingCondState.Ignore)
647 return TokError("unmatched .ifs or .elses");
649 // Check to see there are no empty DwarfFile slots.
650 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
651 getContext().getMCDwarfFiles();
652 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
653 if (!MCDwarfFiles[i])
654 TokError("unassigned file number: " + Twine(i) + " for .file directives");
657 // Check to see that all assembler local symbols were actually defined.
658 // Targets that don't do subsections via symbols may not want this, though,
659 // so conservatively exclude them. Only do this if we're finalizing, though,
660 // as otherwise we won't necessarilly have seen everything yet.
661 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
662 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
663 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
666 MCSymbol *Sym = i->getValue();
667 // Variable symbols may not be marked as defined, so check those
668 // explicitly. If we know it's a variable, we have a definition for
669 // the purposes of this check.
670 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
671 // FIXME: We would really like to refer back to where the symbol was
672 // first referenced for a source location. We need to add something
673 // to track that. Currently, we just point to the end of the file.
675 getLexer().getLoc(), SourceMgr::DK_Error,
676 "assembler local symbol '" + Sym->getName() + "' not defined");
680 // Callback to the target parser in case it needs to do anything.
682 getTargetParser().finishParse();
684 // Finalize the output stream if there are no errors and if the client wants
686 if (!HadError && !NoFinalize)
692 void AsmParser::checkForValidSection() {
693 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
694 TokError("expected section directive before assembly directive");
695 Out.InitToTextSection();
699 /// \brief Throw away the rest of the line for testing purposes.
700 void AsmParser::eatToEndOfStatement() {
701 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
705 if (Lexer.is(AsmToken::EndOfStatement))
709 StringRef AsmParser::parseStringToEndOfStatement() {
710 const char *Start = getTok().getLoc().getPointer();
712 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
715 const char *End = getTok().getLoc().getPointer();
716 return StringRef(Start, End - Start);
719 StringRef AsmParser::parseStringToComma() {
720 const char *Start = getTok().getLoc().getPointer();
722 while (Lexer.isNot(AsmToken::EndOfStatement) &&
723 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
726 const char *End = getTok().getLoc().getPointer();
727 return StringRef(Start, End - Start);
730 /// \brief Parse a paren expression and return it.
731 /// NOTE: This assumes the leading '(' has already been consumed.
733 /// parenexpr ::= expr)
735 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
736 if (parseExpression(Res))
738 if (Lexer.isNot(AsmToken::RParen))
739 return TokError("expected ')' in parentheses expression");
740 EndLoc = Lexer.getTok().getEndLoc();
745 /// \brief Parse a bracket expression and return it.
746 /// NOTE: This assumes the leading '[' has already been consumed.
748 /// bracketexpr ::= expr]
750 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
751 if (parseExpression(Res))
753 if (Lexer.isNot(AsmToken::RBrac))
754 return TokError("expected ']' in brackets expression");
755 EndLoc = Lexer.getTok().getEndLoc();
760 /// \brief Parse a primary expression and return it.
761 /// primaryexpr ::= (parenexpr
762 /// primaryexpr ::= symbol
763 /// primaryexpr ::= number
764 /// primaryexpr ::= '.'
765 /// primaryexpr ::= ~,+,- primaryexpr
766 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
767 SMLoc FirstTokenLoc = getLexer().getLoc();
768 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
769 switch (FirstTokenKind) {
771 return TokError("unknown token in expression");
772 // If we have an error assume that we've already handled it.
773 case AsmToken::Error:
775 case AsmToken::Exclaim:
776 Lex(); // Eat the operator.
777 if (parsePrimaryExpr(Res, EndLoc))
779 Res = MCUnaryExpr::CreateLNot(Res, getContext());
781 case AsmToken::Dollar:
783 case AsmToken::String:
784 case AsmToken::Identifier: {
785 StringRef Identifier;
786 if (parseIdentifier(Identifier)) {
787 if (FirstTokenKind == AsmToken::Dollar) {
788 if (Lexer.getMAI().getDollarIsPC()) {
789 // This is a '$' reference, which references the current PC. Emit a
790 // temporary label to the streamer and refer to it.
791 MCSymbol *Sym = Ctx.CreateTempSymbol();
793 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
795 EndLoc = FirstTokenLoc;
798 return Error(FirstTokenLoc, "invalid token in expression");
802 // Parse symbol variant
803 std::pair<StringRef, StringRef> Split;
804 if (!MAI.useParensForSymbolVariant()) {
805 Split = Identifier.split('@');
806 } else if (Lexer.is(AsmToken::LParen)) {
807 Lexer.Lex(); // eat (
809 parseIdentifier(VName);
810 if (Lexer.isNot(AsmToken::RParen)) {
811 return Error(Lexer.getTok().getLoc(),
812 "unexpected token in variant, expected ')'");
814 Lexer.Lex(); // eat )
815 Split = std::make_pair(Identifier, VName);
818 EndLoc = SMLoc::getFromPointer(Identifier.end());
820 // This is a symbol reference.
821 StringRef SymbolName = Identifier;
822 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
824 // Lookup the symbol variant if used.
825 if (Split.second.size()) {
826 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
827 if (Variant != MCSymbolRefExpr::VK_Invalid) {
828 SymbolName = Split.first;
829 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
830 Variant = MCSymbolRefExpr::VK_None;
832 Variant = MCSymbolRefExpr::VK_None;
833 return TokError("invalid variant '" + Split.second + "'");
837 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
839 // If this is an absolute variable reference, substitute it now to preserve
840 // semantics in the face of reassignment.
841 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
843 return Error(EndLoc, "unexpected modifier on variable reference");
845 Res = Sym->getVariableValue();
849 // Otherwise create a symbol ref.
850 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
853 case AsmToken::Integer: {
854 SMLoc Loc = getTok().getLoc();
855 int64_t IntVal = getTok().getIntVal();
856 Res = MCConstantExpr::Create(IntVal, getContext());
857 EndLoc = Lexer.getTok().getEndLoc();
859 // Look for 'b' or 'f' following an Integer as a directional label
860 if (Lexer.getKind() == AsmToken::Identifier) {
861 StringRef IDVal = getTok().getString();
862 // Lookup the symbol variant if used.
863 std::pair<StringRef, StringRef> Split = IDVal.split('@');
864 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
865 if (Split.first.size() != IDVal.size()) {
866 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
867 if (Variant == MCSymbolRefExpr::VK_Invalid) {
868 Variant = MCSymbolRefExpr::VK_None;
869 return TokError("invalid variant '" + Split.second + "'");
873 if (IDVal == "f" || IDVal == "b") {
875 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "f" ? 1 : 0);
876 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
877 if (IDVal == "b" && Sym->isUndefined())
878 return Error(Loc, "invalid reference to undefined symbol");
879 EndLoc = Lexer.getTok().getEndLoc();
880 Lex(); // Eat identifier.
885 case AsmToken::Real: {
886 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
887 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
888 Res = MCConstantExpr::Create(IntVal, getContext());
889 EndLoc = Lexer.getTok().getEndLoc();
893 case AsmToken::Dot: {
894 // This is a '.' reference, which references the current PC. Emit a
895 // temporary label to the streamer and refer to it.
896 MCSymbol *Sym = Ctx.CreateTempSymbol();
898 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
899 EndLoc = Lexer.getTok().getEndLoc();
900 Lex(); // Eat identifier.
903 case AsmToken::LParen:
904 Lex(); // Eat the '('.
905 return parseParenExpr(Res, EndLoc);
906 case AsmToken::LBrac:
907 if (!PlatformParser->HasBracketExpressions())
908 return TokError("brackets expression not supported on this target");
909 Lex(); // Eat the '['.
910 return parseBracketExpr(Res, EndLoc);
911 case AsmToken::Minus:
912 Lex(); // Eat the operator.
913 if (parsePrimaryExpr(Res, EndLoc))
915 Res = MCUnaryExpr::CreateMinus(Res, getContext());
918 Lex(); // Eat the operator.
919 if (parsePrimaryExpr(Res, EndLoc))
921 Res = MCUnaryExpr::CreatePlus(Res, getContext());
923 case AsmToken::Tilde:
924 Lex(); // Eat the operator.
925 if (parsePrimaryExpr(Res, EndLoc))
927 Res = MCUnaryExpr::CreateNot(Res, getContext());
932 bool AsmParser::parseExpression(const MCExpr *&Res) {
934 return parseExpression(Res, EndLoc);
938 AsmParser::applyModifierToExpr(const MCExpr *E,
939 MCSymbolRefExpr::VariantKind Variant) {
940 // Ask the target implementation about this expression first.
941 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
944 // Recurse over the given expression, rebuilding it to apply the given variant
945 // if there is exactly one symbol.
946 switch (E->getKind()) {
948 case MCExpr::Constant:
951 case MCExpr::SymbolRef: {
952 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
954 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
955 TokError("invalid variant on expression '" + getTok().getIdentifier() +
956 "' (already modified)");
960 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
963 case MCExpr::Unary: {
964 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
965 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
968 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
971 case MCExpr::Binary: {
972 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
973 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
974 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
984 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
988 llvm_unreachable("Invalid expression kind!");
991 /// \brief Parse an expression and return it.
993 /// expr ::= expr &&,|| expr -> lowest.
994 /// expr ::= expr |,^,&,! expr
995 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
996 /// expr ::= expr <<,>> expr
997 /// expr ::= expr +,- expr
998 /// expr ::= expr *,/,% expr -> highest.
999 /// expr ::= primaryexpr
1001 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1002 // Parse the expression.
1004 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1007 // As a special case, we support 'a op b @ modifier' by rewriting the
1008 // expression to include the modifier. This is inefficient, but in general we
1009 // expect users to use 'a@modifier op b'.
1010 if (Lexer.getKind() == AsmToken::At) {
1013 if (Lexer.isNot(AsmToken::Identifier))
1014 return TokError("unexpected symbol modifier following '@'");
1016 MCSymbolRefExpr::VariantKind Variant =
1017 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1018 if (Variant == MCSymbolRefExpr::VK_Invalid)
1019 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1021 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1023 return TokError("invalid modifier '" + getTok().getIdentifier() +
1024 "' (no symbols present)");
1031 // Try to constant fold it up front, if possible.
1033 if (Res->EvaluateAsAbsolute(Value))
1034 Res = MCConstantExpr::Create(Value, getContext());
1039 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1041 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1044 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1047 SMLoc StartLoc = Lexer.getLoc();
1048 if (parseExpression(Expr))
1051 if (!Expr->EvaluateAsAbsolute(Res))
1052 return Error(StartLoc, "expected absolute expression");
1057 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1058 MCBinaryExpr::Opcode &Kind) {
1061 return 0; // not a binop.
1063 // Lowest Precedence: &&, ||
1064 case AsmToken::AmpAmp:
1065 Kind = MCBinaryExpr::LAnd;
1067 case AsmToken::PipePipe:
1068 Kind = MCBinaryExpr::LOr;
1071 // Low Precedence: |, &, ^
1073 // FIXME: gas seems to support '!' as an infix operator?
1074 case AsmToken::Pipe:
1075 Kind = MCBinaryExpr::Or;
1077 case AsmToken::Caret:
1078 Kind = MCBinaryExpr::Xor;
1081 Kind = MCBinaryExpr::And;
1084 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1085 case AsmToken::EqualEqual:
1086 Kind = MCBinaryExpr::EQ;
1088 case AsmToken::ExclaimEqual:
1089 case AsmToken::LessGreater:
1090 Kind = MCBinaryExpr::NE;
1092 case AsmToken::Less:
1093 Kind = MCBinaryExpr::LT;
1095 case AsmToken::LessEqual:
1096 Kind = MCBinaryExpr::LTE;
1098 case AsmToken::Greater:
1099 Kind = MCBinaryExpr::GT;
1101 case AsmToken::GreaterEqual:
1102 Kind = MCBinaryExpr::GTE;
1105 // Intermediate Precedence: <<, >>
1106 case AsmToken::LessLess:
1107 Kind = MCBinaryExpr::Shl;
1109 case AsmToken::GreaterGreater:
1110 Kind = MCBinaryExpr::Shr;
1113 // High Intermediate Precedence: +, -
1114 case AsmToken::Plus:
1115 Kind = MCBinaryExpr::Add;
1117 case AsmToken::Minus:
1118 Kind = MCBinaryExpr::Sub;
1121 // Highest Precedence: *, /, %
1122 case AsmToken::Star:
1123 Kind = MCBinaryExpr::Mul;
1125 case AsmToken::Slash:
1126 Kind = MCBinaryExpr::Div;
1128 case AsmToken::Percent:
1129 Kind = MCBinaryExpr::Mod;
1134 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1135 /// Res contains the LHS of the expression on input.
1136 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1139 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1140 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1142 // If the next token is lower precedence than we are allowed to eat, return
1143 // successfully with what we ate already.
1144 if (TokPrec < Precedence)
1149 // Eat the next primary expression.
1151 if (parsePrimaryExpr(RHS, EndLoc))
1154 // If BinOp binds less tightly with RHS than the operator after RHS, let
1155 // the pending operator take RHS as its LHS.
1156 MCBinaryExpr::Opcode Dummy;
1157 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1158 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1161 // Merge LHS and RHS according to operator.
1162 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1167 /// ::= EndOfStatement
1168 /// ::= Label* Directive ...Operands... EndOfStatement
1169 /// ::= Label* Identifier OperandList* EndOfStatement
1170 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1171 if (Lexer.is(AsmToken::EndOfStatement)) {
1177 // Statements always start with an identifier or are a full line comment.
1178 AsmToken ID = getTok();
1179 SMLoc IDLoc = ID.getLoc();
1181 int64_t LocalLabelVal = -1;
1182 // A full line comment is a '#' as the first token.
1183 if (Lexer.is(AsmToken::Hash))
1184 return parseCppHashLineFilenameComment(IDLoc);
1186 // Allow an integer followed by a ':' as a directional local label.
1187 if (Lexer.is(AsmToken::Integer)) {
1188 LocalLabelVal = getTok().getIntVal();
1189 if (LocalLabelVal < 0) {
1190 if (!TheCondState.Ignore)
1191 return TokError("unexpected token at start of statement");
1194 IDVal = getTok().getString();
1195 Lex(); // Consume the integer token to be used as an identifier token.
1196 if (Lexer.getKind() != AsmToken::Colon) {
1197 if (!TheCondState.Ignore)
1198 return TokError("unexpected token at start of statement");
1201 } else if (Lexer.is(AsmToken::Dot)) {
1202 // Treat '.' as a valid identifier in this context.
1205 } else if (parseIdentifier(IDVal)) {
1206 if (!TheCondState.Ignore)
1207 return TokError("unexpected token at start of statement");
1211 // Handle conditional assembly here before checking for skipping. We
1212 // have to do this so that .endif isn't skipped in a ".if 0" block for
1214 StringMap<DirectiveKind>::const_iterator DirKindIt =
1215 DirectiveKindMap.find(IDVal);
1216 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1218 : DirKindIt->getValue();
1223 return parseDirectiveIf(IDLoc);
1225 return parseDirectiveIfb(IDLoc, true);
1227 return parseDirectiveIfb(IDLoc, false);
1229 return parseDirectiveIfc(IDLoc, true);
1231 return parseDirectiveIfc(IDLoc, false);
1233 return parseDirectiveIfdef(IDLoc, true);
1236 return parseDirectiveIfdef(IDLoc, false);
1238 return parseDirectiveElseIf(IDLoc);
1240 return parseDirectiveElse(IDLoc);
1242 return parseDirectiveEndIf(IDLoc);
1245 // Ignore the statement if in the middle of inactive conditional
1247 if (TheCondState.Ignore) {
1248 eatToEndOfStatement();
1252 // FIXME: Recurse on local labels?
1254 // See what kind of statement we have.
1255 switch (Lexer.getKind()) {
1256 case AsmToken::Colon: {
1257 checkForValidSection();
1259 // identifier ':' -> Label.
1262 // Diagnose attempt to use '.' as a label.
1264 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1266 // Diagnose attempt to use a variable as a label.
1268 // FIXME: Diagnostics. Note the location of the definition as a label.
1269 // FIXME: This doesn't diagnose assignment to a symbol which has been
1270 // implicitly marked as external.
1272 if (LocalLabelVal == -1)
1273 Sym = getContext().GetOrCreateSymbol(IDVal);
1275 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1276 if (!Sym->isUndefined() || Sym->isVariable())
1277 return Error(IDLoc, "invalid symbol redefinition");
1280 if (!ParsingInlineAsm)
1283 // If we are generating dwarf for assembly source files then gather the
1284 // info to make a dwarf label entry for this label if needed.
1285 if (getContext().getGenDwarfForAssembly())
1286 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1289 getTargetParser().onLabelParsed(Sym);
1291 // Consume any end of statement token, if present, to avoid spurious
1292 // AddBlankLine calls().
1293 if (Lexer.is(AsmToken::EndOfStatement)) {
1295 if (Lexer.is(AsmToken::Eof))
1302 case AsmToken::Equal:
1303 // identifier '=' ... -> assignment statement
1306 return parseAssignment(IDVal, true);
1308 default: // Normal instruction or directive.
1312 // If macros are enabled, check to see if this is a macro instantiation.
1313 if (areMacrosEnabled())
1314 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1315 return handleMacroEntry(M, IDLoc);
1318 // Otherwise, we have a normal instruction or directive.
1320 // Directives start with "."
1321 if (IDVal[0] == '.' && IDVal != ".") {
1322 // There are several entities interested in parsing directives:
1324 // 1. The target-specific assembly parser. Some directives are target
1325 // specific or may potentially behave differently on certain targets.
1326 // 2. Asm parser extensions. For example, platform-specific parsers
1327 // (like the ELF parser) register themselves as extensions.
1328 // 3. The generic directive parser implemented by this class. These are
1329 // all the directives that behave in a target and platform independent
1330 // manner, or at least have a default behavior that's shared between
1331 // all targets and platforms.
1333 // First query the target-specific parser. It will return 'true' if it
1334 // isn't interested in this directive.
1335 if (!getTargetParser().ParseDirective(ID))
1338 // Next, check the extention directive map to see if any extension has
1339 // registered itself to parse this directive.
1340 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1341 ExtensionDirectiveMap.lookup(IDVal);
1343 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1345 // Finally, if no one else is interested in this directive, it must be
1346 // generic and familiar to this class.
1352 return parseDirectiveSet(IDVal, true);
1354 return parseDirectiveSet(IDVal, false);
1356 return parseDirectiveAscii(IDVal, false);
1359 return parseDirectiveAscii(IDVal, true);
1361 return parseDirectiveValue(1);
1365 return parseDirectiveValue(2);
1369 return parseDirectiveValue(4);
1372 return parseDirectiveValue(8);
1375 return parseDirectiveRealValue(APFloat::IEEEsingle);
1377 return parseDirectiveRealValue(APFloat::IEEEdouble);
1379 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1380 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1383 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1384 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1387 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1389 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1391 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1393 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1395 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1397 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1399 return parseDirectiveOrg();
1401 return parseDirectiveFill();
1403 return parseDirectiveZero();
1405 eatToEndOfStatement(); // .extern is the default, ignore it.
1409 return parseDirectiveSymbolAttribute(MCSA_Global);
1410 case DK_LAZY_REFERENCE:
1411 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1412 case DK_NO_DEAD_STRIP:
1413 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1414 case DK_SYMBOL_RESOLVER:
1415 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1416 case DK_PRIVATE_EXTERN:
1417 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1419 return parseDirectiveSymbolAttribute(MCSA_Reference);
1420 case DK_WEAK_DEFINITION:
1421 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1422 case DK_WEAK_REFERENCE:
1423 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1424 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1425 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1428 return parseDirectiveComm(/*IsLocal=*/false);
1430 return parseDirectiveComm(/*IsLocal=*/true);
1432 return parseDirectiveAbort();
1434 return parseDirectiveInclude();
1436 return parseDirectiveIncbin();
1439 return TokError(Twine(IDVal) + " not supported yet");
1441 return parseDirectiveRept(IDLoc);
1443 return parseDirectiveIrp(IDLoc);
1445 return parseDirectiveIrpc(IDLoc);
1447 return parseDirectiveEndr(IDLoc);
1448 case DK_BUNDLE_ALIGN_MODE:
1449 return parseDirectiveBundleAlignMode();
1450 case DK_BUNDLE_LOCK:
1451 return parseDirectiveBundleLock();
1452 case DK_BUNDLE_UNLOCK:
1453 return parseDirectiveBundleUnlock();
1455 return parseDirectiveLEB128(true);
1457 return parseDirectiveLEB128(false);
1460 return parseDirectiveSpace(IDVal);
1462 return parseDirectiveFile(IDLoc);
1464 return parseDirectiveLine();
1466 return parseDirectiveLoc();
1468 return parseDirectiveStabs();
1469 case DK_CFI_SECTIONS:
1470 return parseDirectiveCFISections();
1471 case DK_CFI_STARTPROC:
1472 return parseDirectiveCFIStartProc();
1473 case DK_CFI_ENDPROC:
1474 return parseDirectiveCFIEndProc();
1475 case DK_CFI_DEF_CFA:
1476 return parseDirectiveCFIDefCfa(IDLoc);
1477 case DK_CFI_DEF_CFA_OFFSET:
1478 return parseDirectiveCFIDefCfaOffset();
1479 case DK_CFI_ADJUST_CFA_OFFSET:
1480 return parseDirectiveCFIAdjustCfaOffset();
1481 case DK_CFI_DEF_CFA_REGISTER:
1482 return parseDirectiveCFIDefCfaRegister(IDLoc);
1484 return parseDirectiveCFIOffset(IDLoc);
1485 case DK_CFI_REL_OFFSET:
1486 return parseDirectiveCFIRelOffset(IDLoc);
1487 case DK_CFI_PERSONALITY:
1488 return parseDirectiveCFIPersonalityOrLsda(true);
1490 return parseDirectiveCFIPersonalityOrLsda(false);
1491 case DK_CFI_REMEMBER_STATE:
1492 return parseDirectiveCFIRememberState();
1493 case DK_CFI_RESTORE_STATE:
1494 return parseDirectiveCFIRestoreState();
1495 case DK_CFI_SAME_VALUE:
1496 return parseDirectiveCFISameValue(IDLoc);
1497 case DK_CFI_RESTORE:
1498 return parseDirectiveCFIRestore(IDLoc);
1500 return parseDirectiveCFIEscape();
1501 case DK_CFI_SIGNAL_FRAME:
1502 return parseDirectiveCFISignalFrame();
1503 case DK_CFI_UNDEFINED:
1504 return parseDirectiveCFIUndefined(IDLoc);
1505 case DK_CFI_REGISTER:
1506 return parseDirectiveCFIRegister(IDLoc);
1507 case DK_CFI_WINDOW_SAVE:
1508 return parseDirectiveCFIWindowSave();
1511 return parseDirectiveMacrosOnOff(IDVal);
1513 return parseDirectiveMacro(IDLoc);
1516 return parseDirectiveEndMacro(IDVal);
1518 return parseDirectivePurgeMacro(IDLoc);
1520 return parseDirectiveEnd(IDLoc);
1523 return Error(IDLoc, "unknown directive");
1526 // __asm _emit or __asm __emit
1527 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1528 IDVal == "_EMIT" || IDVal == "__EMIT"))
1529 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1532 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1533 return parseDirectiveMSAlign(IDLoc, Info);
1535 checkForValidSection();
1537 // Canonicalize the opcode to lower case.
1538 std::string OpcodeStr = IDVal.lower();
1539 ParseInstructionInfo IInfo(Info.AsmRewrites);
1540 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1541 Info.ParsedOperands);
1542 Info.ParseError = HadError;
1544 // Dump the parsed representation, if requested.
1545 if (getShowParsedOperands()) {
1546 SmallString<256> Str;
1547 raw_svector_ostream OS(Str);
1548 OS << "parsed instruction: [";
1549 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1552 Info.ParsedOperands[i]->print(OS);
1556 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1559 // If we are generating dwarf for assembly source files and the current
1560 // section is the initial text section then generate a .loc directive for
1562 if (!HadError && getContext().getGenDwarfForAssembly() &&
1563 getContext().getGenDwarfSection() ==
1564 getStreamer().getCurrentSection().first) {
1566 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1568 // If we previously parsed a cpp hash file line comment then make sure the
1569 // current Dwarf File is for the CppHashFilename if not then emit the
1570 // Dwarf File table for it and adjust the line number for the .loc.
1571 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
1572 getContext().getMCDwarfFiles();
1573 if (CppHashFilename.size() != 0) {
1574 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1576 getStreamer().EmitDwarfFileDirective(
1577 getContext().nextGenDwarfFileNumber(), StringRef(),
1580 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1581 // cache with the different Loc from the call above we save the last
1582 // info we queried here with SrcMgr.FindLineNumber().
1583 unsigned CppHashLocLineNo;
1584 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1585 CppHashLocLineNo = LastQueryLine;
1587 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1588 LastQueryLine = CppHashLocLineNo;
1589 LastQueryIDLoc = CppHashLoc;
1590 LastQueryBuffer = CppHashBuf;
1592 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1595 getStreamer().EmitDwarfLocDirective(
1596 getContext().getGenDwarfFileNumber(), Line, 0,
1597 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1601 // If parsing succeeded, match the instruction.
1604 HadError = getTargetParser().MatchAndEmitInstruction(
1605 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
1609 // Don't skip the rest of the line, the instruction parser is responsible for
1614 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1615 /// since they may not be able to be tokenized to get to the end of line token.
1616 void AsmParser::eatToEndOfLine() {
1617 if (!Lexer.is(AsmToken::EndOfStatement))
1618 Lexer.LexUntilEndOfLine();
1623 /// parseCppHashLineFilenameComment as this:
1624 /// ::= # number "filename"
1625 /// or just as a full line comment if it doesn't have a number and a string.
1626 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1627 Lex(); // Eat the hash token.
1629 if (getLexer().isNot(AsmToken::Integer)) {
1630 // Consume the line since in cases it is not a well-formed line directive,
1631 // as if were simply a full line comment.
1636 int64_t LineNumber = getTok().getIntVal();
1639 if (getLexer().isNot(AsmToken::String)) {
1644 StringRef Filename = getTok().getString();
1645 // Get rid of the enclosing quotes.
1646 Filename = Filename.substr(1, Filename.size() - 2);
1648 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1650 CppHashFilename = Filename;
1651 CppHashLineNumber = LineNumber;
1652 CppHashBuf = CurBuffer;
1654 // Ignore any trailing characters, they're just comment.
1659 /// \brief will use the last parsed cpp hash line filename comment
1660 /// for the Filename and LineNo if any in the diagnostic.
1661 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1662 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1663 raw_ostream &OS = errs();
1665 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1666 const SMLoc &DiagLoc = Diag.getLoc();
1667 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1668 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1670 // Like SourceMgr::printMessage() we need to print the include stack if any
1671 // before printing the message.
1672 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1673 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1674 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1675 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1678 // If we have not parsed a cpp hash line filename comment or the source
1679 // manager changed or buffer changed (like in a nested include) then just
1680 // print the normal diagnostic using its Filename and LineNo.
1681 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1682 DiagBuf != CppHashBuf) {
1683 if (Parser->SavedDiagHandler)
1684 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1690 // Use the CppHashFilename and calculate a line number based on the
1691 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1693 const std::string &Filename = Parser->CppHashFilename;
1695 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1696 int CppHashLocLineNo =
1697 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1699 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1701 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1702 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1703 Diag.getLineContents(), Diag.getRanges());
1705 if (Parser->SavedDiagHandler)
1706 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1708 NewDiag.print(0, OS);
1711 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1712 // difference being that that function accepts '@' as part of identifiers and
1713 // we can't do that. AsmLexer.cpp should probably be changed to handle
1714 // '@' as a special case when needed.
1715 static bool isIdentifierChar(char c) {
1716 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1720 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1721 const MCAsmMacroParameters &Parameters,
1722 const MCAsmMacroArguments &A, const SMLoc &L) {
1723 unsigned NParameters = Parameters.size();
1724 if (NParameters != 0 && NParameters != A.size())
1725 return Error(L, "Wrong number of arguments");
1727 // A macro without parameters is handled differently on Darwin:
1728 // gas accepts no arguments and does no substitutions
1729 while (!Body.empty()) {
1730 // Scan for the next substitution.
1731 std::size_t End = Body.size(), Pos = 0;
1732 for (; Pos != End; ++Pos) {
1733 // Check for a substitution or escape.
1735 // This macro has no parameters, look for $0, $1, etc.
1736 if (Body[Pos] != '$' || Pos + 1 == End)
1739 char Next = Body[Pos + 1];
1740 if (Next == '$' || Next == 'n' ||
1741 isdigit(static_cast<unsigned char>(Next)))
1744 // This macro has parameters, look for \foo, \bar, etc.
1745 if (Body[Pos] == '\\' && Pos + 1 != End)
1751 OS << Body.slice(0, Pos);
1753 // Check if we reached the end.
1758 switch (Body[Pos + 1]) {
1764 // $n => number of arguments
1769 // $[0-9] => argument
1771 // Missing arguments are ignored.
1772 unsigned Index = Body[Pos + 1] - '0';
1773 if (Index >= A.size())
1776 // Otherwise substitute with the token values, with spaces eliminated.
1777 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1778 ie = A[Index].end();
1780 OS << it->getString();
1786 unsigned I = Pos + 1;
1787 while (isIdentifierChar(Body[I]) && I + 1 != End)
1790 const char *Begin = Body.data() + Pos + 1;
1791 StringRef Argument(Begin, I - (Pos + 1));
1793 for (; Index < NParameters; ++Index)
1794 if (Parameters[Index].first == Argument)
1797 if (Index == NParameters) {
1798 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1801 OS << '\\' << Argument;
1805 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1806 ie = A[Index].end();
1808 if (it->getKind() == AsmToken::String)
1809 OS << it->getStringContents();
1811 OS << it->getString();
1813 Pos += 1 + Argument.size();
1816 // Update the scan point.
1817 Body = Body.substr(Pos);
1823 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1824 SMLoc EL, MemoryBuffer *I)
1825 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1828 static bool isOperator(AsmToken::TokenKind kind) {
1832 case AsmToken::Plus:
1833 case AsmToken::Minus:
1834 case AsmToken::Tilde:
1835 case AsmToken::Slash:
1836 case AsmToken::Star:
1838 case AsmToken::Equal:
1839 case AsmToken::EqualEqual:
1840 case AsmToken::Pipe:
1841 case AsmToken::PipePipe:
1842 case AsmToken::Caret:
1844 case AsmToken::AmpAmp:
1845 case AsmToken::Exclaim:
1846 case AsmToken::ExclaimEqual:
1847 case AsmToken::Percent:
1848 case AsmToken::Less:
1849 case AsmToken::LessEqual:
1850 case AsmToken::LessLess:
1851 case AsmToken::LessGreater:
1852 case AsmToken::Greater:
1853 case AsmToken::GreaterEqual:
1854 case AsmToken::GreaterGreater:
1859 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA,
1860 AsmToken::TokenKind &ArgumentDelimiter) {
1861 unsigned ParenLevel = 0;
1862 unsigned AddTokens = 0;
1864 // gas accepts arguments separated by whitespace, except on Darwin
1866 Lexer.setSkipSpace(false);
1869 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1870 Lexer.setSkipSpace(true);
1871 return TokError("unexpected token in macro instantiation");
1874 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1875 // Spaces and commas cannot be mixed to delimit parameters
1876 if (ArgumentDelimiter == AsmToken::Eof)
1877 ArgumentDelimiter = AsmToken::Comma;
1878 else if (ArgumentDelimiter != AsmToken::Comma) {
1879 Lexer.setSkipSpace(true);
1880 return TokError("expected ' ' for macro argument separator");
1885 if (Lexer.is(AsmToken::Space)) {
1886 Lex(); // Eat spaces
1888 // Spaces can delimit parameters, but could also be part an expression.
1889 // If the token after a space is an operator, add the token and the next
1890 // one into this argument
1891 if (ArgumentDelimiter == AsmToken::Space ||
1892 ArgumentDelimiter == AsmToken::Eof) {
1893 if (isOperator(Lexer.getKind())) {
1894 // Check to see whether the token is used as an operator,
1895 // or part of an identifier
1896 const char *NextChar = getTok().getEndLoc().getPointer();
1897 if (*NextChar == ' ')
1901 if (!AddTokens && ParenLevel == 0) {
1902 if (ArgumentDelimiter == AsmToken::Eof &&
1903 !isOperator(Lexer.getKind()))
1904 ArgumentDelimiter = AsmToken::Space;
1910 // handleMacroEntry relies on not advancing the lexer here
1911 // to be able to fill in the remaining default parameter values
1912 if (Lexer.is(AsmToken::EndOfStatement))
1915 // Adjust the current parentheses level.
1916 if (Lexer.is(AsmToken::LParen))
1918 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1921 // Append the token to the current argument list.
1922 MA.push_back(getTok());
1928 Lexer.setSkipSpace(true);
1929 if (ParenLevel != 0)
1930 return TokError("unbalanced parentheses in macro argument");
1934 // Parse the macro instantiation arguments.
1935 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1936 MCAsmMacroArguments &A) {
1937 const unsigned NParameters = M ? M->Parameters.size() : 0;
1938 // Argument delimiter is initially unknown. It will be set by
1939 // parseMacroArgument()
1940 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1942 // Parse two kinds of macro invocations:
1943 // - macros defined without any parameters accept an arbitrary number of them
1944 // - macros defined with parameters accept at most that many of them
1945 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1947 MCAsmMacroArgument MA;
1949 if (parseMacroArgument(MA, ArgumentDelimiter))
1952 if (!MA.empty() || !NParameters)
1954 else if (NParameters) {
1955 if (!M->Parameters[Parameter].second.empty())
1956 A.push_back(M->Parameters[Parameter].second);
1959 // At the end of the statement, fill in remaining arguments that have
1960 // default values. If there aren't any, then the next argument is
1961 // required but missing
1962 if (Lexer.is(AsmToken::EndOfStatement)) {
1963 if (NParameters && Parameter < NParameters - 1) {
1964 if (M->Parameters[Parameter + 1].second.empty())
1965 return TokError("macro argument '" +
1966 Twine(M->Parameters[Parameter + 1].first) +
1974 if (Lexer.is(AsmToken::Comma))
1977 return TokError("Too many arguments");
1980 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
1981 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
1982 return (I == MacroMap.end()) ? NULL : I->getValue();
1985 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
1986 MacroMap[Name] = new MCAsmMacro(Macro);
1989 void AsmParser::undefineMacro(StringRef Name) {
1990 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
1991 if (I != MacroMap.end()) {
1992 delete I->getValue();
1997 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
1998 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1999 // this, although we should protect against infinite loops.
2000 if (ActiveMacros.size() == 20)
2001 return TokError("macros cannot be nested more than 20 levels deep");
2003 MCAsmMacroArguments A;
2004 if (parseMacroArguments(M, A))
2007 // Remove any trailing empty arguments. Do this after-the-fact as we have
2008 // to keep empty arguments in the middle of the list or positionality
2009 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
2010 while (!A.empty() && A.back().empty())
2013 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2014 // to hold the macro body with substitutions.
2015 SmallString<256> Buf;
2016 StringRef Body = M->Body;
2017 raw_svector_ostream OS(Buf);
2019 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2022 // We include the .endmacro in the buffer as our cue to exit the macro
2024 OS << ".endmacro\n";
2026 MemoryBuffer *Instantiation =
2027 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2029 // Create the macro instantiation object and add to the current macro
2030 // instantiation stack.
2031 MacroInstantiation *MI = new MacroInstantiation(
2032 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
2033 ActiveMacros.push_back(MI);
2035 // Jump to the macro instantiation and prime the lexer.
2036 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2037 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2043 void AsmParser::handleMacroExit() {
2044 // Jump to the EndOfStatement we should return to, and consume it.
2045 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2048 // Pop the instantiation entry.
2049 delete ActiveMacros.back();
2050 ActiveMacros.pop_back();
2053 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2054 switch (Value->getKind()) {
2055 case MCExpr::Binary: {
2056 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2057 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2059 case MCExpr::Target:
2060 case MCExpr::Constant:
2062 case MCExpr::SymbolRef: {
2064 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2066 return isUsedIn(Sym, S.getVariableValue());
2070 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2073 llvm_unreachable("Unknown expr kind!");
2076 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2078 // FIXME: Use better location, we should use proper tokens.
2079 SMLoc EqualLoc = Lexer.getLoc();
2081 const MCExpr *Value;
2082 if (parseExpression(Value))
2085 // Note: we don't count b as used in "a = b". This is to allow
2089 if (Lexer.isNot(AsmToken::EndOfStatement))
2090 return TokError("unexpected token in assignment");
2092 // Error on assignment to '.'.
2094 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2095 "(use '.space' or '.org').)"));
2098 // Eat the end of statement marker.
2101 // Validate that the LHS is allowed to be a variable (either it has not been
2102 // used as a symbol, or it is an absolute symbol).
2103 MCSymbol *Sym = getContext().LookupSymbol(Name);
2105 // Diagnose assignment to a label.
2107 // FIXME: Diagnostics. Note the location of the definition as a label.
2108 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2109 if (isUsedIn(Sym, Value))
2110 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2111 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2112 ; // Allow redefinitions of undefined symbols only used in directives.
2113 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2114 ; // Allow redefinitions of variables that haven't yet been used.
2115 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2116 return Error(EqualLoc, "redefinition of '" + Name + "'");
2117 else if (!Sym->isVariable())
2118 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2119 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2120 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2123 // Don't count these checks as uses.
2124 Sym->setUsed(false);
2126 Sym = getContext().GetOrCreateSymbol(Name);
2128 // FIXME: Handle '.'.
2130 // Do the assignment.
2131 Out.EmitAssignment(Sym, Value);
2133 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2138 /// parseIdentifier:
2141 bool AsmParser::parseIdentifier(StringRef &Res) {
2142 // The assembler has relaxed rules for accepting identifiers, in particular we
2143 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2144 // separate tokens. At this level, we have already lexed so we cannot (currently)
2145 // handle this as a context dependent token, instead we detect adjacent tokens
2146 // and return the combined identifier.
2147 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2148 SMLoc PrefixLoc = getLexer().getLoc();
2150 // Consume the prefix character, and check for a following identifier.
2152 if (Lexer.isNot(AsmToken::Identifier))
2155 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2156 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2159 // Construct the joined identifier and consume the token.
2161 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2166 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2169 Res = getTok().getIdentifier();
2171 Lex(); // Consume the identifier token.
2176 /// parseDirectiveSet:
2177 /// ::= .equ identifier ',' expression
2178 /// ::= .equiv identifier ',' expression
2179 /// ::= .set identifier ',' expression
2180 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2183 if (parseIdentifier(Name))
2184 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2186 if (getLexer().isNot(AsmToken::Comma))
2187 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2190 return parseAssignment(Name, allow_redef, true);
2193 bool AsmParser::parseEscapedString(std::string &Data) {
2194 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2197 StringRef Str = getTok().getStringContents();
2198 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2199 if (Str[i] != '\\') {
2204 // Recognize escaped characters. Note that this escape semantics currently
2205 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2208 return TokError("unexpected backslash at end of string");
2210 // Recognize octal sequences.
2211 if ((unsigned)(Str[i] - '0') <= 7) {
2212 // Consume up to three octal characters.
2213 unsigned Value = Str[i] - '0';
2215 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2217 Value = Value * 8 + (Str[i] - '0');
2219 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2221 Value = Value * 8 + (Str[i] - '0');
2226 return TokError("invalid octal escape sequence (out of range)");
2228 Data += (unsigned char)Value;
2232 // Otherwise recognize individual escapes.
2235 // Just reject invalid escape sequences for now.
2236 return TokError("invalid escape sequence (unrecognized character)");
2238 case 'b': Data += '\b'; break;
2239 case 'f': Data += '\f'; break;
2240 case 'n': Data += '\n'; break;
2241 case 'r': Data += '\r'; break;
2242 case 't': Data += '\t'; break;
2243 case '"': Data += '"'; break;
2244 case '\\': Data += '\\'; break;
2251 /// parseDirectiveAscii:
2252 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2253 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2254 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2255 checkForValidSection();
2258 if (getLexer().isNot(AsmToken::String))
2259 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2262 if (parseEscapedString(Data))
2265 getStreamer().EmitBytes(Data);
2267 getStreamer().EmitBytes(StringRef("\0", 1));
2271 if (getLexer().is(AsmToken::EndOfStatement))
2274 if (getLexer().isNot(AsmToken::Comma))
2275 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2284 /// parseDirectiveValue
2285 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2286 bool AsmParser::parseDirectiveValue(unsigned Size) {
2287 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2288 checkForValidSection();
2291 const MCExpr *Value;
2292 SMLoc ExprLoc = getLexer().getLoc();
2293 if (parseExpression(Value))
2296 // Special case constant expressions to match code generator.
2297 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2298 assert(Size <= 8 && "Invalid size");
2299 uint64_t IntValue = MCE->getValue();
2300 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2301 return Error(ExprLoc, "literal value out of range for directive");
2302 getStreamer().EmitIntValue(IntValue, Size);
2304 getStreamer().EmitValue(Value, Size);
2306 if (getLexer().is(AsmToken::EndOfStatement))
2309 // FIXME: Improve diagnostic.
2310 if (getLexer().isNot(AsmToken::Comma))
2311 return TokError("unexpected token in directive");
2320 /// parseDirectiveRealValue
2321 /// ::= (.single | .double) [ expression (, expression)* ]
2322 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2323 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2324 checkForValidSection();
2327 // We don't truly support arithmetic on floating point expressions, so we
2328 // have to manually parse unary prefixes.
2330 if (getLexer().is(AsmToken::Minus)) {
2333 } else if (getLexer().is(AsmToken::Plus))
2336 if (getLexer().isNot(AsmToken::Integer) &&
2337 getLexer().isNot(AsmToken::Real) &&
2338 getLexer().isNot(AsmToken::Identifier))
2339 return TokError("unexpected token in directive");
2341 // Convert to an APFloat.
2342 APFloat Value(Semantics);
2343 StringRef IDVal = getTok().getString();
2344 if (getLexer().is(AsmToken::Identifier)) {
2345 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2346 Value = APFloat::getInf(Semantics);
2347 else if (!IDVal.compare_lower("nan"))
2348 Value = APFloat::getNaN(Semantics, false, ~0);
2350 return TokError("invalid floating point literal");
2351 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2352 APFloat::opInvalidOp)
2353 return TokError("invalid floating point literal");
2357 // Consume the numeric token.
2360 // Emit the value as an integer.
2361 APInt AsInt = Value.bitcastToAPInt();
2362 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2363 AsInt.getBitWidth() / 8);
2365 if (getLexer().is(AsmToken::EndOfStatement))
2368 if (getLexer().isNot(AsmToken::Comma))
2369 return TokError("unexpected token in directive");
2378 /// parseDirectiveZero
2379 /// ::= .zero expression
2380 bool AsmParser::parseDirectiveZero() {
2381 checkForValidSection();
2384 if (parseAbsoluteExpression(NumBytes))
2388 if (getLexer().is(AsmToken::Comma)) {
2390 if (parseAbsoluteExpression(Val))
2394 if (getLexer().isNot(AsmToken::EndOfStatement))
2395 return TokError("unexpected token in '.zero' directive");
2399 getStreamer().EmitFill(NumBytes, Val);
2404 /// parseDirectiveFill
2405 /// ::= .fill expression [ , expression [ , expression ] ]
2406 bool AsmParser::parseDirectiveFill() {
2407 checkForValidSection();
2410 if (parseAbsoluteExpression(NumValues))
2413 int64_t FillSize = 1;
2414 int64_t FillExpr = 0;
2416 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2417 if (getLexer().isNot(AsmToken::Comma))
2418 return TokError("unexpected token in '.fill' directive");
2421 if (parseAbsoluteExpression(FillSize))
2424 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2425 if (getLexer().isNot(AsmToken::Comma))
2426 return TokError("unexpected token in '.fill' directive");
2429 if (parseAbsoluteExpression(FillExpr))
2432 if (getLexer().isNot(AsmToken::EndOfStatement))
2433 return TokError("unexpected token in '.fill' directive");
2439 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2440 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2442 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2443 getStreamer().EmitIntValue(FillExpr, FillSize);
2448 /// parseDirectiveOrg
2449 /// ::= .org expression [ , expression ]
2450 bool AsmParser::parseDirectiveOrg() {
2451 checkForValidSection();
2453 const MCExpr *Offset;
2454 SMLoc Loc = getTok().getLoc();
2455 if (parseExpression(Offset))
2458 // Parse optional fill expression.
2459 int64_t FillExpr = 0;
2460 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2461 if (getLexer().isNot(AsmToken::Comma))
2462 return TokError("unexpected token in '.org' directive");
2465 if (parseAbsoluteExpression(FillExpr))
2468 if (getLexer().isNot(AsmToken::EndOfStatement))
2469 return TokError("unexpected token in '.org' directive");
2474 // Only limited forms of relocatable expressions are accepted here, it
2475 // has to be relative to the current section. The streamer will return
2476 // 'true' if the expression wasn't evaluatable.
2477 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2478 return Error(Loc, "expected assembly-time absolute expression");
2483 /// parseDirectiveAlign
2484 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2485 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2486 checkForValidSection();
2488 SMLoc AlignmentLoc = getLexer().getLoc();
2490 if (parseAbsoluteExpression(Alignment))
2494 bool HasFillExpr = false;
2495 int64_t FillExpr = 0;
2496 int64_t MaxBytesToFill = 0;
2497 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2498 if (getLexer().isNot(AsmToken::Comma))
2499 return TokError("unexpected token in directive");
2502 // The fill expression can be omitted while specifying a maximum number of
2503 // alignment bytes, e.g:
2505 if (getLexer().isNot(AsmToken::Comma)) {
2507 if (parseAbsoluteExpression(FillExpr))
2511 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2512 if (getLexer().isNot(AsmToken::Comma))
2513 return TokError("unexpected token in directive");
2516 MaxBytesLoc = getLexer().getLoc();
2517 if (parseAbsoluteExpression(MaxBytesToFill))
2520 if (getLexer().isNot(AsmToken::EndOfStatement))
2521 return TokError("unexpected token in directive");
2530 // Compute alignment in bytes.
2532 // FIXME: Diagnose overflow.
2533 if (Alignment >= 32) {
2534 Error(AlignmentLoc, "invalid alignment value");
2538 Alignment = 1ULL << Alignment;
2540 // Reject alignments that aren't a power of two, for gas compatibility.
2541 if (!isPowerOf2_64(Alignment))
2542 Error(AlignmentLoc, "alignment must be a power of 2");
2545 // Diagnose non-sensical max bytes to align.
2546 if (MaxBytesLoc.isValid()) {
2547 if (MaxBytesToFill < 1) {
2548 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2549 "many bytes, ignoring maximum bytes expression");
2553 if (MaxBytesToFill >= Alignment) {
2554 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2560 // Check whether we should use optimal code alignment for this .align
2562 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2563 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2564 ValueSize == 1 && UseCodeAlign) {
2565 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2567 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2568 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2575 /// parseDirectiveFile
2576 /// ::= .file [number] filename
2577 /// ::= .file number directory filename
2578 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2579 // FIXME: I'm not sure what this is.
2580 int64_t FileNumber = -1;
2581 SMLoc FileNumberLoc = getLexer().getLoc();
2582 if (getLexer().is(AsmToken::Integer)) {
2583 FileNumber = getTok().getIntVal();
2587 return TokError("file number less than one");
2590 if (getLexer().isNot(AsmToken::String))
2591 return TokError("unexpected token in '.file' directive");
2593 // Usually the directory and filename together, otherwise just the directory.
2594 // Allow the strings to have escaped octal character sequence.
2595 std::string Path = getTok().getString();
2596 if (parseEscapedString(Path))
2600 StringRef Directory;
2602 std::string FilenameData;
2603 if (getLexer().is(AsmToken::String)) {
2604 if (FileNumber == -1)
2605 return TokError("explicit path specified, but no file number");
2606 if (parseEscapedString(FilenameData))
2608 Filename = FilenameData;
2615 if (getLexer().isNot(AsmToken::EndOfStatement))
2616 return TokError("unexpected token in '.file' directive");
2618 if (FileNumber == -1)
2619 getStreamer().EmitFileDirective(Filename);
2621 if (getContext().getGenDwarfForAssembly() == true)
2623 "input can't have .file dwarf directives when -g is "
2624 "used to generate dwarf debug info for assembly code");
2626 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2627 Error(FileNumberLoc, "file number already allocated");
2633 /// parseDirectiveLine
2634 /// ::= .line [number]
2635 bool AsmParser::parseDirectiveLine() {
2636 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2637 if (getLexer().isNot(AsmToken::Integer))
2638 return TokError("unexpected token in '.line' directive");
2640 int64_t LineNumber = getTok().getIntVal();
2644 // FIXME: Do something with the .line.
2647 if (getLexer().isNot(AsmToken::EndOfStatement))
2648 return TokError("unexpected token in '.line' directive");
2653 /// parseDirectiveLoc
2654 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2655 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2656 /// The first number is a file number, must have been previously assigned with
2657 /// a .file directive, the second number is the line number and optionally the
2658 /// third number is a column position (zero if not specified). The remaining
2659 /// optional items are .loc sub-directives.
2660 bool AsmParser::parseDirectiveLoc() {
2661 if (getLexer().isNot(AsmToken::Integer))
2662 return TokError("unexpected token in '.loc' directive");
2663 int64_t FileNumber = getTok().getIntVal();
2665 return TokError("file number less than one in '.loc' directive");
2666 if (!getContext().isValidDwarfFileNumber(FileNumber))
2667 return TokError("unassigned file number in '.loc' directive");
2670 int64_t LineNumber = 0;
2671 if (getLexer().is(AsmToken::Integer)) {
2672 LineNumber = getTok().getIntVal();
2674 return TokError("line number less than zero in '.loc' directive");
2678 int64_t ColumnPos = 0;
2679 if (getLexer().is(AsmToken::Integer)) {
2680 ColumnPos = getTok().getIntVal();
2682 return TokError("column position less than zero in '.loc' directive");
2686 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2688 int64_t Discriminator = 0;
2689 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2691 if (getLexer().is(AsmToken::EndOfStatement))
2695 SMLoc Loc = getTok().getLoc();
2696 if (parseIdentifier(Name))
2697 return TokError("unexpected token in '.loc' directive");
2699 if (Name == "basic_block")
2700 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2701 else if (Name == "prologue_end")
2702 Flags |= DWARF2_FLAG_PROLOGUE_END;
2703 else if (Name == "epilogue_begin")
2704 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2705 else if (Name == "is_stmt") {
2706 Loc = getTok().getLoc();
2707 const MCExpr *Value;
2708 if (parseExpression(Value))
2710 // The expression must be the constant 0 or 1.
2711 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2712 int Value = MCE->getValue();
2714 Flags &= ~DWARF2_FLAG_IS_STMT;
2715 else if (Value == 1)
2716 Flags |= DWARF2_FLAG_IS_STMT;
2718 return Error(Loc, "is_stmt value not 0 or 1");
2720 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2722 } else if (Name == "isa") {
2723 Loc = getTok().getLoc();
2724 const MCExpr *Value;
2725 if (parseExpression(Value))
2727 // The expression must be a constant greater or equal to 0.
2728 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2729 int Value = MCE->getValue();
2731 return Error(Loc, "isa number less than zero");
2734 return Error(Loc, "isa number not a constant value");
2736 } else if (Name == "discriminator") {
2737 if (parseAbsoluteExpression(Discriminator))
2740 return Error(Loc, "unknown sub-directive in '.loc' directive");
2743 if (getLexer().is(AsmToken::EndOfStatement))
2748 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2749 Isa, Discriminator, StringRef());
2754 /// parseDirectiveStabs
2755 /// ::= .stabs string, number, number, number
2756 bool AsmParser::parseDirectiveStabs() {
2757 return TokError("unsupported directive '.stabs'");
2760 /// parseDirectiveCFISections
2761 /// ::= .cfi_sections section [, section]
2762 bool AsmParser::parseDirectiveCFISections() {
2767 if (parseIdentifier(Name))
2768 return TokError("Expected an identifier");
2770 if (Name == ".eh_frame")
2772 else if (Name == ".debug_frame")
2775 if (getLexer().is(AsmToken::Comma)) {
2778 if (parseIdentifier(Name))
2779 return TokError("Expected an identifier");
2781 if (Name == ".eh_frame")
2783 else if (Name == ".debug_frame")
2787 getStreamer().EmitCFISections(EH, Debug);
2791 /// parseDirectiveCFIStartProc
2792 /// ::= .cfi_startproc
2793 bool AsmParser::parseDirectiveCFIStartProc() {
2794 getStreamer().EmitCFIStartProc();
2798 /// parseDirectiveCFIEndProc
2799 /// ::= .cfi_endproc
2800 bool AsmParser::parseDirectiveCFIEndProc() {
2801 getStreamer().EmitCFIEndProc();
2805 /// \brief parse register name or number.
2806 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2807 SMLoc DirectiveLoc) {
2810 if (getLexer().isNot(AsmToken::Integer)) {
2811 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2813 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2815 return parseAbsoluteExpression(Register);
2820 /// parseDirectiveCFIDefCfa
2821 /// ::= .cfi_def_cfa register, offset
2822 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2823 int64_t Register = 0;
2824 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2827 if (getLexer().isNot(AsmToken::Comma))
2828 return TokError("unexpected token in directive");
2832 if (parseAbsoluteExpression(Offset))
2835 getStreamer().EmitCFIDefCfa(Register, Offset);
2839 /// parseDirectiveCFIDefCfaOffset
2840 /// ::= .cfi_def_cfa_offset offset
2841 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2843 if (parseAbsoluteExpression(Offset))
2846 getStreamer().EmitCFIDefCfaOffset(Offset);
2850 /// parseDirectiveCFIRegister
2851 /// ::= .cfi_register register, register
2852 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2853 int64_t Register1 = 0;
2854 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2857 if (getLexer().isNot(AsmToken::Comma))
2858 return TokError("unexpected token in directive");
2861 int64_t Register2 = 0;
2862 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2865 getStreamer().EmitCFIRegister(Register1, Register2);
2869 /// parseDirectiveCFIWindowSave
2870 /// ::= .cfi_window_save
2871 bool AsmParser::parseDirectiveCFIWindowSave() {
2872 getStreamer().EmitCFIWindowSave();
2876 /// parseDirectiveCFIAdjustCfaOffset
2877 /// ::= .cfi_adjust_cfa_offset adjustment
2878 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
2879 int64_t Adjustment = 0;
2880 if (parseAbsoluteExpression(Adjustment))
2883 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2887 /// parseDirectiveCFIDefCfaRegister
2888 /// ::= .cfi_def_cfa_register register
2889 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2890 int64_t Register = 0;
2891 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2894 getStreamer().EmitCFIDefCfaRegister(Register);
2898 /// parseDirectiveCFIOffset
2899 /// ::= .cfi_offset register, offset
2900 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2901 int64_t Register = 0;
2904 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2907 if (getLexer().isNot(AsmToken::Comma))
2908 return TokError("unexpected token in directive");
2911 if (parseAbsoluteExpression(Offset))
2914 getStreamer().EmitCFIOffset(Register, Offset);
2918 /// parseDirectiveCFIRelOffset
2919 /// ::= .cfi_rel_offset register, offset
2920 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2921 int64_t Register = 0;
2923 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2926 if (getLexer().isNot(AsmToken::Comma))
2927 return TokError("unexpected token in directive");
2931 if (parseAbsoluteExpression(Offset))
2934 getStreamer().EmitCFIRelOffset(Register, Offset);
2938 static bool isValidEncoding(int64_t Encoding) {
2939 if (Encoding & ~0xff)
2942 if (Encoding == dwarf::DW_EH_PE_omit)
2945 const unsigned Format = Encoding & 0xf;
2946 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2947 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2948 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2949 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2952 const unsigned Application = Encoding & 0x70;
2953 if (Application != dwarf::DW_EH_PE_absptr &&
2954 Application != dwarf::DW_EH_PE_pcrel)
2960 /// parseDirectiveCFIPersonalityOrLsda
2961 /// IsPersonality true for cfi_personality, false for cfi_lsda
2962 /// ::= .cfi_personality encoding, [symbol_name]
2963 /// ::= .cfi_lsda encoding, [symbol_name]
2964 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2965 int64_t Encoding = 0;
2966 if (parseAbsoluteExpression(Encoding))
2968 if (Encoding == dwarf::DW_EH_PE_omit)
2971 if (!isValidEncoding(Encoding))
2972 return TokError("unsupported encoding.");
2974 if (getLexer().isNot(AsmToken::Comma))
2975 return TokError("unexpected token in directive");
2979 if (parseIdentifier(Name))
2980 return TokError("expected identifier in directive");
2982 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2985 getStreamer().EmitCFIPersonality(Sym, Encoding);
2987 getStreamer().EmitCFILsda(Sym, Encoding);
2991 /// parseDirectiveCFIRememberState
2992 /// ::= .cfi_remember_state
2993 bool AsmParser::parseDirectiveCFIRememberState() {
2994 getStreamer().EmitCFIRememberState();
2998 /// parseDirectiveCFIRestoreState
2999 /// ::= .cfi_remember_state
3000 bool AsmParser::parseDirectiveCFIRestoreState() {
3001 getStreamer().EmitCFIRestoreState();
3005 /// parseDirectiveCFISameValue
3006 /// ::= .cfi_same_value register
3007 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3008 int64_t Register = 0;
3010 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3013 getStreamer().EmitCFISameValue(Register);
3017 /// parseDirectiveCFIRestore
3018 /// ::= .cfi_restore register
3019 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3020 int64_t Register = 0;
3021 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3024 getStreamer().EmitCFIRestore(Register);
3028 /// parseDirectiveCFIEscape
3029 /// ::= .cfi_escape expression[,...]
3030 bool AsmParser::parseDirectiveCFIEscape() {
3033 if (parseAbsoluteExpression(CurrValue))
3036 Values.push_back((uint8_t)CurrValue);
3038 while (getLexer().is(AsmToken::Comma)) {
3041 if (parseAbsoluteExpression(CurrValue))
3044 Values.push_back((uint8_t)CurrValue);
3047 getStreamer().EmitCFIEscape(Values);
3051 /// parseDirectiveCFISignalFrame
3052 /// ::= .cfi_signal_frame
3053 bool AsmParser::parseDirectiveCFISignalFrame() {
3054 if (getLexer().isNot(AsmToken::EndOfStatement))
3055 return Error(getLexer().getLoc(),
3056 "unexpected token in '.cfi_signal_frame'");
3058 getStreamer().EmitCFISignalFrame();
3062 /// parseDirectiveCFIUndefined
3063 /// ::= .cfi_undefined register
3064 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3065 int64_t Register = 0;
3067 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3070 getStreamer().EmitCFIUndefined(Register);
3074 /// parseDirectiveMacrosOnOff
3077 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3078 if (getLexer().isNot(AsmToken::EndOfStatement))
3079 return Error(getLexer().getLoc(),
3080 "unexpected token in '" + Directive + "' directive");
3082 setMacrosEnabled(Directive == ".macros_on");
3086 /// parseDirectiveMacro
3087 /// ::= .macro name [parameters]
3088 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3090 if (parseIdentifier(Name))
3091 return TokError("expected identifier in '.macro' directive");
3093 MCAsmMacroParameters Parameters;
3094 // Argument delimiter is initially unknown. It will be set by
3095 // parseMacroArgument()
3096 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3097 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3099 MCAsmMacroParameter Parameter;
3100 if (parseIdentifier(Parameter.first))
3101 return TokError("expected identifier in '.macro' directive");
3103 if (getLexer().is(AsmToken::Equal)) {
3105 if (parseMacroArgument(Parameter.second, ArgumentDelimiter))
3109 Parameters.push_back(Parameter);
3111 if (getLexer().is(AsmToken::Comma))
3113 else if (getLexer().is(AsmToken::EndOfStatement))
3118 // Eat the end of statement.
3121 AsmToken EndToken, StartToken = getTok();
3123 // Lex the macro definition.
3125 // Check whether we have reached the end of the file.
3126 if (getLexer().is(AsmToken::Eof))
3127 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3129 // Otherwise, check whether we have reach the .endmacro.
3130 if (getLexer().is(AsmToken::Identifier) &&
3131 (getTok().getIdentifier() == ".endm" ||
3132 getTok().getIdentifier() == ".endmacro")) {
3133 EndToken = getTok();
3135 if (getLexer().isNot(AsmToken::EndOfStatement))
3136 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3141 // Otherwise, scan til the end of the statement.
3142 eatToEndOfStatement();
3145 if (lookupMacro(Name)) {
3146 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3149 const char *BodyStart = StartToken.getLoc().getPointer();
3150 const char *BodyEnd = EndToken.getLoc().getPointer();
3151 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3152 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3153 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3157 /// checkForBadMacro
3159 /// With the support added for named parameters there may be code out there that
3160 /// is transitioning from positional parameters. In versions of gas that did
3161 /// not support named parameters they would be ignored on the macro defintion.
3162 /// But to support both styles of parameters this is not possible so if a macro
3163 /// defintion has named parameters but does not use them and has what appears
3164 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3165 /// warning that the positional parameter found in body which have no effect.
3166 /// Hoping the developer will either remove the named parameters from the macro
3167 /// definiton so the positional parameters get used if that was what was
3168 /// intended or change the macro to use the named parameters. It is possible
3169 /// this warning will trigger when the none of the named parameters are used
3170 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3171 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3173 MCAsmMacroParameters Parameters) {
3174 // If this macro is not defined with named parameters the warning we are
3175 // checking for here doesn't apply.
3176 unsigned NParameters = Parameters.size();
3177 if (NParameters == 0)
3180 bool NamedParametersFound = false;
3181 bool PositionalParametersFound = false;
3183 // Look at the body of the macro for use of both the named parameters and what
3184 // are likely to be positional parameters. This is what expandMacro() is
3185 // doing when it finds the parameters in the body.
3186 while (!Body.empty()) {
3187 // Scan for the next possible parameter.
3188 std::size_t End = Body.size(), Pos = 0;
3189 for (; Pos != End; ++Pos) {
3190 // Check for a substitution or escape.
3191 // This macro is defined with parameters, look for \foo, \bar, etc.
3192 if (Body[Pos] == '\\' && Pos + 1 != End)
3195 // This macro should have parameters, but look for $0, $1, ..., $n too.
3196 if (Body[Pos] != '$' || Pos + 1 == End)
3198 char Next = Body[Pos + 1];
3199 if (Next == '$' || Next == 'n' ||
3200 isdigit(static_cast<unsigned char>(Next)))
3204 // Check if we reached the end.
3208 if (Body[Pos] == '$') {
3209 switch (Body[Pos + 1]) {
3214 // $n => number of arguments
3216 PositionalParametersFound = true;
3219 // $[0-9] => argument
3221 PositionalParametersFound = true;
3227 unsigned I = Pos + 1;
3228 while (isIdentifierChar(Body[I]) && I + 1 != End)
3231 const char *Begin = Body.data() + Pos + 1;
3232 StringRef Argument(Begin, I - (Pos + 1));
3234 for (; Index < NParameters; ++Index)
3235 if (Parameters[Index].first == Argument)
3238 if (Index == NParameters) {
3239 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3245 NamedParametersFound = true;
3246 Pos += 1 + Argument.size();
3249 // Update the scan point.
3250 Body = Body.substr(Pos);
3253 if (!NamedParametersFound && PositionalParametersFound)
3254 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3255 "used in macro body, possible positional parameter "
3256 "found in body which will have no effect");
3259 /// parseDirectiveEndMacro
3262 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3263 if (getLexer().isNot(AsmToken::EndOfStatement))
3264 return TokError("unexpected token in '" + Directive + "' directive");
3266 // If we are inside a macro instantiation, terminate the current
3268 if (isInsideMacroInstantiation()) {
3273 // Otherwise, this .endmacro is a stray entry in the file; well formed
3274 // .endmacro directives are handled during the macro definition parsing.
3275 return TokError("unexpected '" + Directive + "' in file, "
3276 "no current macro definition");
3279 /// parseDirectivePurgeMacro
3281 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3283 if (parseIdentifier(Name))
3284 return TokError("expected identifier in '.purgem' directive");
3286 if (getLexer().isNot(AsmToken::EndOfStatement))
3287 return TokError("unexpected token in '.purgem' directive");
3289 if (!lookupMacro(Name))
3290 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3292 undefineMacro(Name);
3296 /// parseDirectiveBundleAlignMode
3297 /// ::= {.bundle_align_mode} expression
3298 bool AsmParser::parseDirectiveBundleAlignMode() {
3299 checkForValidSection();
3301 // Expect a single argument: an expression that evaluates to a constant
3302 // in the inclusive range 0-30.
3303 SMLoc ExprLoc = getLexer().getLoc();
3304 int64_t AlignSizePow2;
3305 if (parseAbsoluteExpression(AlignSizePow2))
3307 else if (getLexer().isNot(AsmToken::EndOfStatement))
3308 return TokError("unexpected token after expression in"
3309 " '.bundle_align_mode' directive");
3310 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3311 return Error(ExprLoc,
3312 "invalid bundle alignment size (expected between 0 and 30)");
3316 // Because of AlignSizePow2's verified range we can safely truncate it to
3318 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3322 /// parseDirectiveBundleLock
3323 /// ::= {.bundle_lock} [align_to_end]
3324 bool AsmParser::parseDirectiveBundleLock() {
3325 checkForValidSection();
3326 bool AlignToEnd = false;
3328 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3330 SMLoc Loc = getTok().getLoc();
3331 const char *kInvalidOptionError =
3332 "invalid option for '.bundle_lock' directive";
3334 if (parseIdentifier(Option))
3335 return Error(Loc, kInvalidOptionError);
3337 if (Option != "align_to_end")
3338 return Error(Loc, kInvalidOptionError);
3339 else if (getLexer().isNot(AsmToken::EndOfStatement))
3341 "unexpected token after '.bundle_lock' directive option");
3347 getStreamer().EmitBundleLock(AlignToEnd);
3351 /// parseDirectiveBundleLock
3352 /// ::= {.bundle_lock}
3353 bool AsmParser::parseDirectiveBundleUnlock() {
3354 checkForValidSection();
3356 if (getLexer().isNot(AsmToken::EndOfStatement))
3357 return TokError("unexpected token in '.bundle_unlock' directive");
3360 getStreamer().EmitBundleUnlock();
3364 /// parseDirectiveSpace
3365 /// ::= (.skip | .space) expression [ , expression ]
3366 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3367 checkForValidSection();
3370 if (parseAbsoluteExpression(NumBytes))
3373 int64_t FillExpr = 0;
3374 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3375 if (getLexer().isNot(AsmToken::Comma))
3376 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3379 if (parseAbsoluteExpression(FillExpr))
3382 if (getLexer().isNot(AsmToken::EndOfStatement))
3383 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3389 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3392 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3393 getStreamer().EmitFill(NumBytes, FillExpr);
3398 /// parseDirectiveLEB128
3399 /// ::= (.sleb128 | .uleb128) expression
3400 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3401 checkForValidSection();
3402 const MCExpr *Value;
3404 if (parseExpression(Value))
3407 if (getLexer().isNot(AsmToken::EndOfStatement))
3408 return TokError("unexpected token in directive");
3411 getStreamer().EmitSLEB128Value(Value);
3413 getStreamer().EmitULEB128Value(Value);
3418 /// parseDirectiveSymbolAttribute
3419 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3420 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3421 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3424 SMLoc Loc = getTok().getLoc();
3426 if (parseIdentifier(Name))
3427 return Error(Loc, "expected identifier in directive");
3429 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3431 // Assembler local symbols don't make any sense here. Complain loudly.
3432 if (Sym->isTemporary())
3433 return Error(Loc, "non-local symbol required in directive");
3435 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3436 return Error(Loc, "unable to emit symbol attribute");
3438 if (getLexer().is(AsmToken::EndOfStatement))
3441 if (getLexer().isNot(AsmToken::Comma))
3442 return TokError("unexpected token in directive");
3451 /// parseDirectiveComm
3452 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3453 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3454 checkForValidSection();
3456 SMLoc IDLoc = getLexer().getLoc();
3458 if (parseIdentifier(Name))
3459 return TokError("expected identifier in directive");
3461 // Handle the identifier as the key symbol.
3462 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3464 if (getLexer().isNot(AsmToken::Comma))
3465 return TokError("unexpected token in directive");
3469 SMLoc SizeLoc = getLexer().getLoc();
3470 if (parseAbsoluteExpression(Size))
3473 int64_t Pow2Alignment = 0;
3474 SMLoc Pow2AlignmentLoc;
3475 if (getLexer().is(AsmToken::Comma)) {
3477 Pow2AlignmentLoc = getLexer().getLoc();
3478 if (parseAbsoluteExpression(Pow2Alignment))
3481 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3482 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3483 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3485 // If this target takes alignments in bytes (not log) validate and convert.
3486 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3487 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3488 if (!isPowerOf2_64(Pow2Alignment))
3489 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3490 Pow2Alignment = Log2_64(Pow2Alignment);
3494 if (getLexer().isNot(AsmToken::EndOfStatement))
3495 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3499 // NOTE: a size of zero for a .comm should create a undefined symbol
3500 // but a size of .lcomm creates a bss symbol of size zero.
3502 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3503 "be less than zero");
3505 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3506 // may internally end up wanting an alignment in bytes.
3507 // FIXME: Diagnose overflow.
3508 if (Pow2Alignment < 0)
3509 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3510 "alignment, can't be less than zero");
3512 if (!Sym->isUndefined())
3513 return Error(IDLoc, "invalid symbol redefinition");
3515 // Create the Symbol as a common or local common with Size and Pow2Alignment
3517 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3521 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3525 /// parseDirectiveAbort
3526 /// ::= .abort [... message ...]
3527 bool AsmParser::parseDirectiveAbort() {
3528 // FIXME: Use loc from directive.
3529 SMLoc Loc = getLexer().getLoc();
3531 StringRef Str = parseStringToEndOfStatement();
3532 if (getLexer().isNot(AsmToken::EndOfStatement))
3533 return TokError("unexpected token in '.abort' directive");
3538 Error(Loc, ".abort detected. Assembly stopping.");
3540 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3541 // FIXME: Actually abort assembly here.
3546 /// parseDirectiveInclude
3547 /// ::= .include "filename"
3548 bool AsmParser::parseDirectiveInclude() {
3549 if (getLexer().isNot(AsmToken::String))
3550 return TokError("expected string in '.include' directive");
3552 // Allow the strings to have escaped octal character sequence.
3553 std::string Filename;
3554 if (parseEscapedString(Filename))
3556 SMLoc IncludeLoc = getLexer().getLoc();
3559 if (getLexer().isNot(AsmToken::EndOfStatement))
3560 return TokError("unexpected token in '.include' directive");
3562 // Attempt to switch the lexer to the included file before consuming the end
3563 // of statement to avoid losing it when we switch.
3564 if (enterIncludeFile(Filename)) {
3565 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3572 /// parseDirectiveIncbin
3573 /// ::= .incbin "filename"
3574 bool AsmParser::parseDirectiveIncbin() {
3575 if (getLexer().isNot(AsmToken::String))
3576 return TokError("expected string in '.incbin' directive");
3578 // Allow the strings to have escaped octal character sequence.
3579 std::string Filename;
3580 if (parseEscapedString(Filename))
3582 SMLoc IncbinLoc = getLexer().getLoc();
3585 if (getLexer().isNot(AsmToken::EndOfStatement))
3586 return TokError("unexpected token in '.incbin' directive");
3588 // Attempt to process the included file.
3589 if (processIncbinFile(Filename)) {
3590 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3597 /// parseDirectiveIf
3598 /// ::= .if expression
3599 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3600 TheCondStack.push_back(TheCondState);
3601 TheCondState.TheCond = AsmCond::IfCond;
3602 if (TheCondState.Ignore) {
3603 eatToEndOfStatement();
3606 if (parseAbsoluteExpression(ExprValue))
3609 if (getLexer().isNot(AsmToken::EndOfStatement))
3610 return TokError("unexpected token in '.if' directive");
3614 TheCondState.CondMet = ExprValue;
3615 TheCondState.Ignore = !TheCondState.CondMet;
3621 /// parseDirectiveIfb
3623 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3624 TheCondStack.push_back(TheCondState);
3625 TheCondState.TheCond = AsmCond::IfCond;
3627 if (TheCondState.Ignore) {
3628 eatToEndOfStatement();
3630 StringRef Str = parseStringToEndOfStatement();
3632 if (getLexer().isNot(AsmToken::EndOfStatement))
3633 return TokError("unexpected token in '.ifb' directive");
3637 TheCondState.CondMet = ExpectBlank == Str.empty();
3638 TheCondState.Ignore = !TheCondState.CondMet;
3644 /// parseDirectiveIfc
3645 /// ::= .ifc string1, string2
3646 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3647 TheCondStack.push_back(TheCondState);
3648 TheCondState.TheCond = AsmCond::IfCond;
3650 if (TheCondState.Ignore) {
3651 eatToEndOfStatement();
3653 StringRef Str1 = parseStringToComma();
3655 if (getLexer().isNot(AsmToken::Comma))
3656 return TokError("unexpected token in '.ifc' directive");
3660 StringRef Str2 = parseStringToEndOfStatement();
3662 if (getLexer().isNot(AsmToken::EndOfStatement))
3663 return TokError("unexpected token in '.ifc' directive");
3667 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3668 TheCondState.Ignore = !TheCondState.CondMet;
3674 /// parseDirectiveIfdef
3675 /// ::= .ifdef symbol
3676 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3678 TheCondStack.push_back(TheCondState);
3679 TheCondState.TheCond = AsmCond::IfCond;
3681 if (TheCondState.Ignore) {
3682 eatToEndOfStatement();
3684 if (parseIdentifier(Name))
3685 return TokError("expected identifier after '.ifdef'");
3689 MCSymbol *Sym = getContext().LookupSymbol(Name);
3692 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3694 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3695 TheCondState.Ignore = !TheCondState.CondMet;
3701 /// parseDirectiveElseIf
3702 /// ::= .elseif expression
3703 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3704 if (TheCondState.TheCond != AsmCond::IfCond &&
3705 TheCondState.TheCond != AsmCond::ElseIfCond)
3706 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3708 TheCondState.TheCond = AsmCond::ElseIfCond;
3710 bool LastIgnoreState = false;
3711 if (!TheCondStack.empty())
3712 LastIgnoreState = TheCondStack.back().Ignore;
3713 if (LastIgnoreState || TheCondState.CondMet) {
3714 TheCondState.Ignore = true;
3715 eatToEndOfStatement();
3718 if (parseAbsoluteExpression(ExprValue))
3721 if (getLexer().isNot(AsmToken::EndOfStatement))
3722 return TokError("unexpected token in '.elseif' directive");
3725 TheCondState.CondMet = ExprValue;
3726 TheCondState.Ignore = !TheCondState.CondMet;
3732 /// parseDirectiveElse
3734 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3735 if (getLexer().isNot(AsmToken::EndOfStatement))
3736 return TokError("unexpected token in '.else' directive");
3740 if (TheCondState.TheCond != AsmCond::IfCond &&
3741 TheCondState.TheCond != AsmCond::ElseIfCond)
3742 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3744 TheCondState.TheCond = AsmCond::ElseCond;
3745 bool LastIgnoreState = false;
3746 if (!TheCondStack.empty())
3747 LastIgnoreState = TheCondStack.back().Ignore;
3748 if (LastIgnoreState || TheCondState.CondMet)
3749 TheCondState.Ignore = true;
3751 TheCondState.Ignore = false;
3756 /// parseDirectiveEnd
3758 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
3759 if (getLexer().isNot(AsmToken::EndOfStatement))
3760 return TokError("unexpected token in '.end' directive");
3764 while (Lexer.isNot(AsmToken::Eof))
3770 /// parseDirectiveEndIf
3772 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
3773 if (getLexer().isNot(AsmToken::EndOfStatement))
3774 return TokError("unexpected token in '.endif' directive");
3778 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
3779 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3781 if (!TheCondStack.empty()) {
3782 TheCondState = TheCondStack.back();
3783 TheCondStack.pop_back();
3789 void AsmParser::initializeDirectiveKindMap() {
3790 DirectiveKindMap[".set"] = DK_SET;
3791 DirectiveKindMap[".equ"] = DK_EQU;
3792 DirectiveKindMap[".equiv"] = DK_EQUIV;
3793 DirectiveKindMap[".ascii"] = DK_ASCII;
3794 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3795 DirectiveKindMap[".string"] = DK_STRING;
3796 DirectiveKindMap[".byte"] = DK_BYTE;
3797 DirectiveKindMap[".short"] = DK_SHORT;
3798 DirectiveKindMap[".value"] = DK_VALUE;
3799 DirectiveKindMap[".2byte"] = DK_2BYTE;
3800 DirectiveKindMap[".long"] = DK_LONG;
3801 DirectiveKindMap[".int"] = DK_INT;
3802 DirectiveKindMap[".4byte"] = DK_4BYTE;
3803 DirectiveKindMap[".quad"] = DK_QUAD;
3804 DirectiveKindMap[".8byte"] = DK_8BYTE;
3805 DirectiveKindMap[".single"] = DK_SINGLE;
3806 DirectiveKindMap[".float"] = DK_FLOAT;
3807 DirectiveKindMap[".double"] = DK_DOUBLE;
3808 DirectiveKindMap[".align"] = DK_ALIGN;
3809 DirectiveKindMap[".align32"] = DK_ALIGN32;
3810 DirectiveKindMap[".balign"] = DK_BALIGN;
3811 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3812 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3813 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3814 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3815 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3816 DirectiveKindMap[".org"] = DK_ORG;
3817 DirectiveKindMap[".fill"] = DK_FILL;
3818 DirectiveKindMap[".zero"] = DK_ZERO;
3819 DirectiveKindMap[".extern"] = DK_EXTERN;
3820 DirectiveKindMap[".globl"] = DK_GLOBL;
3821 DirectiveKindMap[".global"] = DK_GLOBAL;
3822 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3823 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3824 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3825 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3826 DirectiveKindMap[".reference"] = DK_REFERENCE;
3827 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3828 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3829 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3830 DirectiveKindMap[".comm"] = DK_COMM;
3831 DirectiveKindMap[".common"] = DK_COMMON;
3832 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3833 DirectiveKindMap[".abort"] = DK_ABORT;
3834 DirectiveKindMap[".include"] = DK_INCLUDE;
3835 DirectiveKindMap[".incbin"] = DK_INCBIN;
3836 DirectiveKindMap[".code16"] = DK_CODE16;
3837 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3838 DirectiveKindMap[".rept"] = DK_REPT;
3839 DirectiveKindMap[".irp"] = DK_IRP;
3840 DirectiveKindMap[".irpc"] = DK_IRPC;
3841 DirectiveKindMap[".endr"] = DK_ENDR;
3842 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3843 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3844 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3845 DirectiveKindMap[".if"] = DK_IF;
3846 DirectiveKindMap[".ifb"] = DK_IFB;
3847 DirectiveKindMap[".ifnb"] = DK_IFNB;
3848 DirectiveKindMap[".ifc"] = DK_IFC;
3849 DirectiveKindMap[".ifnc"] = DK_IFNC;
3850 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3851 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3852 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3853 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3854 DirectiveKindMap[".else"] = DK_ELSE;
3855 DirectiveKindMap[".end"] = DK_END;
3856 DirectiveKindMap[".endif"] = DK_ENDIF;
3857 DirectiveKindMap[".skip"] = DK_SKIP;
3858 DirectiveKindMap[".space"] = DK_SPACE;
3859 DirectiveKindMap[".file"] = DK_FILE;
3860 DirectiveKindMap[".line"] = DK_LINE;
3861 DirectiveKindMap[".loc"] = DK_LOC;
3862 DirectiveKindMap[".stabs"] = DK_STABS;
3863 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3864 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3865 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3866 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3867 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3868 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3869 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3870 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3871 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3872 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3873 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3874 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3875 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3876 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3877 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3878 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3879 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3880 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3881 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3882 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3883 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3884 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
3885 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3886 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3887 DirectiveKindMap[".macro"] = DK_MACRO;
3888 DirectiveKindMap[".endm"] = DK_ENDM;
3889 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3890 DirectiveKindMap[".purgem"] = DK_PURGEM;
3893 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
3894 AsmToken EndToken, StartToken = getTok();
3896 unsigned NestLevel = 0;
3898 // Check whether we have reached the end of the file.
3899 if (getLexer().is(AsmToken::Eof)) {
3900 Error(DirectiveLoc, "no matching '.endr' in definition");
3904 if (Lexer.is(AsmToken::Identifier) &&
3905 (getTok().getIdentifier() == ".rept")) {
3909 // Otherwise, check whether we have reached the .endr.
3910 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
3911 if (NestLevel == 0) {
3912 EndToken = getTok();
3914 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3915 TokError("unexpected token in '.endr' directive");
3923 // Otherwise, scan till the end of the statement.
3924 eatToEndOfStatement();
3927 const char *BodyStart = StartToken.getLoc().getPointer();
3928 const char *BodyEnd = EndToken.getLoc().getPointer();
3929 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3931 // We Are Anonymous.
3933 MCAsmMacroParameters Parameters;
3934 MacroLikeBodies.push_back(MCAsmMacro(Name, Body, Parameters));
3935 return &MacroLikeBodies.back();
3938 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
3939 raw_svector_ostream &OS) {
3942 MemoryBuffer *Instantiation =
3943 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3945 // Create the macro instantiation object and add to the current macro
3946 // instantiation stack.
3947 MacroInstantiation *MI = new MacroInstantiation(
3948 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
3949 ActiveMacros.push_back(MI);
3951 // Jump to the macro instantiation and prime the lexer.
3952 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3953 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3957 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc) {
3959 if (parseAbsoluteExpression(Count))
3960 return TokError("unexpected token in '.rept' directive");
3963 return TokError("Count is negative");
3965 if (Lexer.isNot(AsmToken::EndOfStatement))
3966 return TokError("unexpected token in '.rept' directive");
3968 // Eat the end of statement.
3971 // Lex the rept definition.
3972 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
3976 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3977 // to hold the macro body with substitutions.
3978 SmallString<256> Buf;
3979 MCAsmMacroParameters Parameters;
3980 MCAsmMacroArguments A;
3981 raw_svector_ostream OS(Buf);
3983 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3986 instantiateMacroLikeBody(M, DirectiveLoc, OS);
3991 /// parseDirectiveIrp
3992 /// ::= .irp symbol,values
3993 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
3994 MCAsmMacroParameters Parameters;
3995 MCAsmMacroParameter Parameter;
3997 if (parseIdentifier(Parameter.first))
3998 return TokError("expected identifier in '.irp' directive");
4000 Parameters.push_back(Parameter);
4002 if (Lexer.isNot(AsmToken::Comma))
4003 return TokError("expected comma in '.irp' directive");
4007 MCAsmMacroArguments A;
4008 if (parseMacroArguments(0, A))
4011 // Eat the end of statement.
4014 // Lex the irp definition.
4015 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4019 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4020 // to hold the macro body with substitutions.
4021 SmallString<256> Buf;
4022 raw_svector_ostream OS(Buf);
4024 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4025 MCAsmMacroArguments Args;
4028 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4032 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4037 /// parseDirectiveIrpc
4038 /// ::= .irpc symbol,values
4039 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4040 MCAsmMacroParameters Parameters;
4041 MCAsmMacroParameter Parameter;
4043 if (parseIdentifier(Parameter.first))
4044 return TokError("expected identifier in '.irpc' directive");
4046 Parameters.push_back(Parameter);
4048 if (Lexer.isNot(AsmToken::Comma))
4049 return TokError("expected comma in '.irpc' directive");
4053 MCAsmMacroArguments A;
4054 if (parseMacroArguments(0, A))
4057 if (A.size() != 1 || A.front().size() != 1)
4058 return TokError("unexpected token in '.irpc' directive");
4060 // Eat the end of statement.
4063 // Lex the irpc definition.
4064 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4068 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4069 // to hold the macro body with substitutions.
4070 SmallString<256> Buf;
4071 raw_svector_ostream OS(Buf);
4073 StringRef Values = A.front().front().getString();
4074 std::size_t I, End = Values.size();
4075 for (I = 0; I < End; ++I) {
4076 MCAsmMacroArgument Arg;
4077 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4079 MCAsmMacroArguments Args;
4080 Args.push_back(Arg);
4082 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4086 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4091 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4092 if (ActiveMacros.empty())
4093 return TokError("unmatched '.endr' directive");
4095 // The only .repl that should get here are the ones created by
4096 // instantiateMacroLikeBody.
4097 assert(getLexer().is(AsmToken::EndOfStatement));
4103 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4105 const MCExpr *Value;
4106 SMLoc ExprLoc = getLexer().getLoc();
4107 if (parseExpression(Value))
4109 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4111 return Error(ExprLoc, "unexpected expression in _emit");
4112 uint64_t IntValue = MCE->getValue();
4113 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4114 return Error(ExprLoc, "literal value out of range for directive");
4116 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4120 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4121 const MCExpr *Value;
4122 SMLoc ExprLoc = getLexer().getLoc();
4123 if (parseExpression(Value))
4125 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4127 return Error(ExprLoc, "unexpected expression in align");
4128 uint64_t IntValue = MCE->getValue();
4129 if (!isPowerOf2_64(IntValue))
4130 return Error(ExprLoc, "literal value not a power of two greater then zero");
4132 Info.AsmRewrites->push_back(
4133 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4137 // We are comparing pointers, but the pointers are relative to a single string.
4138 // Thus, this should always be deterministic.
4139 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4140 const AsmRewrite *AsmRewriteB) {
4141 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4143 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4146 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4147 // rewrite to the same location. Make sure the SizeDirective rewrite is
4148 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4149 // ensures the sort algorithm is stable.
4150 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4151 AsmRewritePrecedence[AsmRewriteB->Kind])
4154 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4155 AsmRewritePrecedence[AsmRewriteB->Kind])
4157 llvm_unreachable("Unstable rewrite sort.");
4160 bool AsmParser::parseMSInlineAsm(
4161 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4162 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4163 SmallVectorImpl<std::string> &Constraints,
4164 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4165 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4166 SmallVector<void *, 4> InputDecls;
4167 SmallVector<void *, 4> OutputDecls;
4168 SmallVector<bool, 4> InputDeclsAddressOf;
4169 SmallVector<bool, 4> OutputDeclsAddressOf;
4170 SmallVector<std::string, 4> InputConstraints;
4171 SmallVector<std::string, 4> OutputConstraints;
4172 SmallVector<unsigned, 4> ClobberRegs;
4174 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4179 // While we have input, parse each statement.
4180 unsigned InputIdx = 0;
4181 unsigned OutputIdx = 0;
4182 while (getLexer().isNot(AsmToken::Eof)) {
4183 ParseStatementInfo Info(&AsmStrRewrites);
4184 if (parseStatement(Info))
4187 if (Info.ParseError)
4190 if (Info.Opcode == ~0U)
4193 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4195 // Build the list of clobbers, outputs and inputs.
4196 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4197 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4200 if (Operand->isImm())
4203 // Register operand.
4204 if (Operand->isReg() && !Operand->needAddressOf()) {
4205 unsigned NumDefs = Desc.getNumDefs();
4207 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4208 ClobberRegs.push_back(Operand->getReg());
4212 // Expr/Input or Output.
4213 StringRef SymName = Operand->getSymName();
4214 if (SymName.empty())
4217 void *OpDecl = Operand->getOpDecl();
4221 bool isOutput = (i == 1) && Desc.mayStore();
4222 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4225 OutputDecls.push_back(OpDecl);
4226 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4227 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4228 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4230 InputDecls.push_back(OpDecl);
4231 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4232 InputConstraints.push_back(Operand->getConstraint().str());
4233 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4237 // Consider implicit defs to be clobbers. Think of cpuid and push.
4238 const uint16_t *ImpDefs = Desc.getImplicitDefs();
4239 for (unsigned I = 0, E = Desc.getNumImplicitDefs(); I != E; ++I)
4240 ClobberRegs.push_back(ImpDefs[I]);
4243 // Set the number of Outputs and Inputs.
4244 NumOutputs = OutputDecls.size();
4245 NumInputs = InputDecls.size();
4247 // Set the unique clobbers.
4248 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4249 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4251 Clobbers.assign(ClobberRegs.size(), std::string());
4252 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4253 raw_string_ostream OS(Clobbers[I]);
4254 IP->printRegName(OS, ClobberRegs[I]);
4257 // Merge the various outputs and inputs. Output are expected first.
4258 if (NumOutputs || NumInputs) {
4259 unsigned NumExprs = NumOutputs + NumInputs;
4260 OpDecls.resize(NumExprs);
4261 Constraints.resize(NumExprs);
4262 for (unsigned i = 0; i < NumOutputs; ++i) {
4263 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4264 Constraints[i] = OutputConstraints[i];
4266 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4267 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4268 Constraints[j] = InputConstraints[i];
4272 // Build the IR assembly string.
4273 std::string AsmStringIR;
4274 raw_string_ostream OS(AsmStringIR);
4275 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4276 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4277 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4278 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4279 E = AsmStrRewrites.end();
4281 AsmRewriteKind Kind = (*I).Kind;
4282 if (Kind == AOK_Delete)
4285 const char *Loc = (*I).Loc.getPointer();
4286 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4288 // Emit everything up to the immediate/expression.
4289 unsigned Len = Loc - AsmStart;
4291 OS << StringRef(AsmStart, Len);
4293 // Skip the original expression.
4294 if (Kind == AOK_Skip) {
4295 AsmStart = Loc + (*I).Len;
4299 unsigned AdditionalSkip = 0;
4300 // Rewrite expressions in $N notation.
4305 OS << "$$" << (*I).Val;
4311 OS << '$' << InputIdx++;
4314 OS << '$' << OutputIdx++;
4316 case AOK_SizeDirective:
4319 case 8: OS << "byte ptr "; break;
4320 case 16: OS << "word ptr "; break;
4321 case 32: OS << "dword ptr "; break;
4322 case 64: OS << "qword ptr "; break;
4323 case 80: OS << "xword ptr "; break;
4324 case 128: OS << "xmmword ptr "; break;
4325 case 256: OS << "ymmword ptr "; break;
4332 unsigned Val = (*I).Val;
4333 OS << ".align " << Val;
4335 // Skip the original immediate.
4336 assert(Val < 10 && "Expected alignment less then 2^10.");
4337 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4340 case AOK_DotOperator:
4345 // Skip the original expression.
4346 AsmStart = Loc + (*I).Len + AdditionalSkip;
4349 // Emit the remainder of the asm string.
4350 if (AsmStart != AsmEnd)
4351 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4353 AsmString = OS.str();
4357 /// \brief Create an MCAsmParser instance.
4358 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4359 MCStreamer &Out, const MCAsmInfo &MAI) {
4360 return new AsmParser(SM, C, Out, MAI);