1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCParser/AsmCond.h"
27 #include "llvm/MC/MCParser/AsmLexer.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCTargetAsmParser.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/raw_ostream.h"
48 FatalAssemblerWarnings("fatal-assembler-warnings",
49 cl::desc("Consider warnings as error"));
51 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
54 /// \brief Helper types for tracking macro definitions.
55 typedef std::vector<AsmToken> MCAsmMacroArgument;
56 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
58 struct MCAsmMacroParameter {
60 MCAsmMacroArgument Value;
63 MCAsmMacroParameter() : Required(false) { }
66 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
71 MCAsmMacroParameters Parameters;
74 MCAsmMacro(StringRef N, StringRef B, ArrayRef<MCAsmMacroParameter> P) :
75 Name(N), Body(B), Parameters(P) {}
78 /// \brief Helper class for storing information about an active macro
80 struct MacroInstantiation {
81 /// The macro being instantiated.
82 const MCAsmMacro *TheMacro;
84 /// The macro instantiation with substitutions.
85 MemoryBuffer *Instantiation;
87 /// The location of the instantiation.
88 SMLoc InstantiationLoc;
90 /// The buffer where parsing should resume upon instantiation completion.
93 /// The location where parsing should resume upon instantiation completion.
97 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
101 struct ParseStatementInfo {
102 /// \brief The parsed operands from the last parsed statement.
103 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
105 /// \brief The opcode from the last parsed instruction.
108 /// \brief Was there an error parsing the inline assembly?
111 SmallVectorImpl<AsmRewrite> *AsmRewrites;
113 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
114 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
115 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
117 ~ParseStatementInfo() {
118 // Free any parsed operands.
119 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
120 delete ParsedOperands[i];
121 ParsedOperands.clear();
125 /// \brief The concrete assembly parser instance.
126 class AsmParser : public MCAsmParser {
127 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
128 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
133 const MCAsmInfo &MAI;
135 SourceMgr::DiagHandlerTy SavedDiagHandler;
136 void *SavedDiagContext;
137 MCAsmParserExtension *PlatformParser;
139 /// This is the current buffer index we're lexing from as managed by the
140 /// SourceMgr object.
143 AsmCond TheCondState;
144 std::vector<AsmCond> TheCondStack;
146 /// \brief maps directive names to handler methods in parser
147 /// extensions. Extensions register themselves in this map by calling
148 /// addDirectiveHandler.
149 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
151 /// \brief Map of currently defined macros.
152 StringMap<MCAsmMacro*> MacroMap;
154 /// \brief Stack of active macro instantiations.
155 std::vector<MacroInstantiation*> ActiveMacros;
157 /// \brief List of bodies of anonymous macros.
158 std::deque<MCAsmMacro> MacroLikeBodies;
160 /// Boolean tracking whether macro substitution is enabled.
161 unsigned MacrosEnabledFlag : 1;
163 /// Flag tracking whether any errors have been encountered.
164 unsigned HadError : 1;
166 /// The values from the last parsed cpp hash file line comment if any.
167 StringRef CppHashFilename;
168 int64_t CppHashLineNumber;
171 /// When generating dwarf for assembly source files we need to calculate the
172 /// logical line number based on the last parsed cpp hash file line comment
173 /// and current line. Since this is slow and messes up the SourceMgr's
174 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
175 SMLoc LastQueryIDLoc;
177 unsigned LastQueryLine;
179 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
180 unsigned AssemblerDialect;
182 /// \brief is Darwin compatibility enabled?
185 /// \brief Are we parsing ms-style inline assembly?
186 bool ParsingInlineAsm;
189 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
190 const MCAsmInfo &MAI);
191 virtual ~AsmParser();
193 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
195 virtual void addDirectiveHandler(StringRef Directive,
196 ExtensionDirectiveHandler Handler) {
197 ExtensionDirectiveMap[Directive] = Handler;
201 /// @name MCAsmParser Interface
204 virtual SourceMgr &getSourceManager() { return SrcMgr; }
205 virtual MCAsmLexer &getLexer() { return Lexer; }
206 virtual MCContext &getContext() { return Ctx; }
207 virtual MCStreamer &getStreamer() { return Out; }
208 virtual unsigned getAssemblerDialect() {
209 if (AssemblerDialect == ~0U)
210 return MAI.getAssemblerDialect();
212 return AssemblerDialect;
214 virtual void setAssemblerDialect(unsigned i) {
215 AssemblerDialect = i;
218 virtual void Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges = None);
219 virtual bool Warning(SMLoc L, const Twine &Msg,
220 ArrayRef<SMRange> Ranges = None);
221 virtual bool Error(SMLoc L, const Twine &Msg,
222 ArrayRef<SMRange> Ranges = None);
224 virtual const AsmToken &Lex();
226 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
227 bool isParsingInlineAsm() { return ParsingInlineAsm; }
229 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
230 unsigned &NumOutputs, unsigned &NumInputs,
231 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
232 SmallVectorImpl<std::string> &Constraints,
233 SmallVectorImpl<std::string> &Clobbers,
234 const MCInstrInfo *MII,
235 const MCInstPrinter *IP,
236 MCAsmParserSemaCallback &SI);
238 bool parseExpression(const MCExpr *&Res);
239 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
240 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
241 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
242 virtual bool parseAbsoluteExpression(int64_t &Res);
244 /// \brief Parse an identifier or string (as a quoted identifier)
245 /// and set \p Res to the identifier contents.
246 virtual bool parseIdentifier(StringRef &Res);
247 virtual void eatToEndOfStatement();
249 virtual void checkForValidSection();
254 bool parseStatement(ParseStatementInfo &Info);
255 void eatToEndOfLine();
256 bool parseCppHashLineFilenameComment(const SMLoc &L);
258 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
259 ArrayRef<MCAsmMacroParameter> Parameters);
260 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
261 ArrayRef<MCAsmMacroParameter> Parameters,
262 ArrayRef<MCAsmMacroArgument> A,
265 /// \brief Are macros enabled in the parser?
266 bool areMacrosEnabled() {return MacrosEnabledFlag;}
268 /// \brief Control a flag in the parser that enables or disables macros.
269 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
271 /// \brief Lookup a previously defined macro.
272 /// \param Name Macro name.
273 /// \returns Pointer to macro. NULL if no such macro was defined.
274 const MCAsmMacro* lookupMacro(StringRef Name);
276 /// \brief Define a new macro with the given name and information.
277 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
279 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
280 void undefineMacro(StringRef Name);
282 /// \brief Are we inside a macro instantiation?
283 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
285 /// \brief Handle entry to macro instantiation.
287 /// \param M The macro.
288 /// \param NameLoc Instantiation location.
289 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
291 /// \brief Handle exit from macro instantiation.
292 void handleMacroExit();
294 /// \brief Extract AsmTokens for a macro argument.
295 bool parseMacroArgument(MCAsmMacroArgument &MA);
297 /// \brief Parse all macro arguments for a given macro.
298 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
300 void printMacroInstantiations();
301 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
302 ArrayRef<SMRange> Ranges = None) const {
303 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
305 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
307 /// \brief Enter the specified file. This returns true on failure.
308 bool enterIncludeFile(const std::string &Filename);
310 /// \brief Process the specified file for the .incbin directive.
311 /// This returns true on failure.
312 bool processIncbinFile(const std::string &Filename);
314 /// \brief Reset the current lexer position to that given by \p Loc. The
315 /// current token is not set; clients should ensure Lex() is called
318 /// \param InBuffer If not -1, should be the known buffer id that contains the
320 void jumpToLoc(SMLoc Loc, int InBuffer=-1);
322 /// \brief Parse up to the end of statement and a return the contents from the
323 /// current token until the end of the statement; the current token on exit
324 /// will be either the EndOfStatement or EOF.
325 virtual StringRef parseStringToEndOfStatement();
327 /// \brief Parse until the end of a statement or a comma is encountered,
328 /// return the contents from the current token up to the end or comma.
329 StringRef parseStringToComma();
331 bool parseAssignment(StringRef Name, bool allow_redef,
332 bool NoDeadStrip = false);
334 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
335 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
336 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
338 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
340 // Generic (target and platform independent) directive parsing.
342 DK_NO_DIRECTIVE, // Placeholder
343 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
344 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
345 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
346 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
347 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
348 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
349 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
350 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
351 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
352 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
353 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
354 DK_ELSEIF, DK_ELSE, DK_ENDIF,
355 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
356 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
357 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
358 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
359 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
360 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
361 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
362 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
363 DK_SLEB128, DK_ULEB128,
367 /// \brief Maps directive name --> DirectiveKind enum, for
368 /// directives parsed by this class.
369 StringMap<DirectiveKind> DirectiveKindMap;
371 // ".ascii", ".asciz", ".string"
372 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
373 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
374 bool parseDirectiveOctaValue(); // ".octa"
375 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
376 bool parseDirectiveFill(); // ".fill"
377 bool parseDirectiveZero(); // ".zero"
378 // ".set", ".equ", ".equiv"
379 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
380 bool parseDirectiveOrg(); // ".org"
381 // ".align{,32}", ".p2align{,w,l}"
382 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
384 // ".file", ".line", ".loc", ".stabs"
385 bool parseDirectiveFile(SMLoc DirectiveLoc);
386 bool parseDirectiveLine();
387 bool parseDirectiveLoc();
388 bool parseDirectiveStabs();
391 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
392 bool parseDirectiveCFIWindowSave();
393 bool parseDirectiveCFISections();
394 bool parseDirectiveCFIStartProc();
395 bool parseDirectiveCFIEndProc();
396 bool parseDirectiveCFIDefCfaOffset();
397 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
398 bool parseDirectiveCFIAdjustCfaOffset();
399 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
400 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
401 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
403 bool parseDirectiveCFIRememberState();
404 bool parseDirectiveCFIRestoreState();
405 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
406 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
407 bool parseDirectiveCFIEscape();
408 bool parseDirectiveCFISignalFrame();
409 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
412 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
413 bool parseDirectiveEndMacro(StringRef Directive);
414 bool parseDirectiveMacro(SMLoc DirectiveLoc);
415 bool parseDirectiveMacrosOnOff(StringRef Directive);
417 // ".bundle_align_mode"
418 bool parseDirectiveBundleAlignMode();
420 bool parseDirectiveBundleLock();
422 bool parseDirectiveBundleUnlock();
425 bool parseDirectiveSpace(StringRef IDVal);
427 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
428 bool parseDirectiveLEB128(bool Signed);
430 /// \brief Parse a directive like ".globl" which
431 /// accepts a single symbol (which should be a label or an external).
432 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
434 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
436 bool parseDirectiveAbort(); // ".abort"
437 bool parseDirectiveInclude(); // ".include"
438 bool parseDirectiveIncbin(); // ".incbin"
440 bool parseDirectiveIf(SMLoc DirectiveLoc); // ".if"
441 // ".ifb" or ".ifnb", depending on ExpectBlank.
442 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
443 // ".ifc" or ".ifnc", depending on ExpectEqual.
444 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
445 // ".ifdef" or ".ifndef", depending on expect_defined
446 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
447 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
448 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
449 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
450 virtual bool parseEscapedString(std::string &Data);
452 const MCExpr *applyModifierToExpr(const MCExpr *E,
453 MCSymbolRefExpr::VariantKind Variant);
455 // Macro-like directives
456 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
457 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
458 raw_svector_ostream &OS);
459 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
460 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
461 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
462 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
464 // "_emit" or "__emit"
465 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
469 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
472 bool parseDirectiveEnd(SMLoc DirectiveLoc);
474 void initializeDirectiveKindMap();
480 extern MCAsmParserExtension *createDarwinAsmParser();
481 extern MCAsmParserExtension *createELFAsmParser();
482 extern MCAsmParserExtension *createCOFFAsmParser();
486 enum { DEFAULT_ADDRSPACE = 0 };
488 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
489 const MCAsmInfo &_MAI)
490 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
491 PlatformParser(0), CurBuffer(0), MacrosEnabledFlag(true),
492 CppHashLineNumber(0), AssemblerDialect(~0U), IsDarwin(false),
493 ParsingInlineAsm(false) {
494 // Save the old handler.
495 SavedDiagHandler = SrcMgr.getDiagHandler();
496 SavedDiagContext = SrcMgr.getDiagContext();
497 // Set our own handler which calls the saved handler.
498 SrcMgr.setDiagHandler(DiagHandler, this);
499 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
501 // Initialize the platform / file format parser.
502 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
503 case MCObjectFileInfo::IsCOFF:
504 PlatformParser = createCOFFAsmParser();
505 PlatformParser->Initialize(*this);
507 case MCObjectFileInfo::IsMachO:
508 PlatformParser = createDarwinAsmParser();
509 PlatformParser->Initialize(*this);
512 case MCObjectFileInfo::IsELF:
513 PlatformParser = createELFAsmParser();
514 PlatformParser->Initialize(*this);
518 initializeDirectiveKindMap();
521 AsmParser::~AsmParser() {
522 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
524 // Destroy any macros.
525 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
528 delete it->getValue();
530 delete PlatformParser;
533 void AsmParser::printMacroInstantiations() {
534 // Print the active macro instantiation stack.
535 for (std::vector<MacroInstantiation *>::const_reverse_iterator
536 it = ActiveMacros.rbegin(),
537 ie = ActiveMacros.rend();
539 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
540 "while in macro instantiation");
543 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
544 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
545 printMacroInstantiations();
548 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
549 if (FatalAssemblerWarnings)
550 return Error(L, Msg, Ranges);
551 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
552 printMacroInstantiations();
556 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
558 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
559 printMacroInstantiations();
563 bool AsmParser::enterIncludeFile(const std::string &Filename) {
564 std::string IncludedFile;
565 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
571 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
576 /// Process the specified .incbin file by searching for it in the include paths
577 /// then just emitting the byte contents of the file to the streamer. This
578 /// returns true on failure.
579 bool AsmParser::processIncbinFile(const std::string &Filename) {
580 std::string IncludedFile;
581 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
585 // Pick up the bytes from the file and emit them.
586 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
590 void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
591 if (InBuffer != -1) {
592 CurBuffer = InBuffer;
594 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
596 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
599 const AsmToken &AsmParser::Lex() {
600 const AsmToken *tok = &Lexer.Lex();
602 if (tok->is(AsmToken::Eof)) {
603 // If this is the end of an included file, pop the parent file off the
605 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
606 if (ParentIncludeLoc != SMLoc()) {
607 jumpToLoc(ParentIncludeLoc);
612 if (tok->is(AsmToken::Error))
613 Error(Lexer.getErrLoc(), Lexer.getErr());
618 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
619 // Create the initial section, if requested.
620 if (!NoInitialTextSection)
627 AsmCond StartingCondState = TheCondState;
629 // If we are generating dwarf for assembly source files save the initial text
630 // section and generate a .file directive.
631 if (getContext().getGenDwarfForAssembly()) {
632 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
633 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
634 getStreamer().EmitLabel(SectionStartSym);
635 getContext().setGenDwarfSectionStartSym(SectionStartSym);
636 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
638 getContext().getMainFileName());
641 // While we have input, parse each statement.
642 while (Lexer.isNot(AsmToken::Eof)) {
643 ParseStatementInfo Info;
644 if (!parseStatement(Info))
647 // We had an error, validate that one was emitted and recover by skipping to
649 assert(HadError && "Parse statement returned an error, but none emitted!");
650 eatToEndOfStatement();
653 if (TheCondState.TheCond != StartingCondState.TheCond ||
654 TheCondState.Ignore != StartingCondState.Ignore)
655 return TokError("unmatched .ifs or .elses");
657 // Check to see there are no empty DwarfFile slots.
658 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
659 getContext().getMCDwarfFiles();
660 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
661 if (!MCDwarfFiles[i])
662 TokError("unassigned file number: " + Twine(i) + " for .file directives");
665 // Check to see that all assembler local symbols were actually defined.
666 // Targets that don't do subsections via symbols may not want this, though,
667 // so conservatively exclude them. Only do this if we're finalizing, though,
668 // as otherwise we won't necessarilly have seen everything yet.
669 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
670 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
671 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
674 MCSymbol *Sym = i->getValue();
675 // Variable symbols may not be marked as defined, so check those
676 // explicitly. If we know it's a variable, we have a definition for
677 // the purposes of this check.
678 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
679 // FIXME: We would really like to refer back to where the symbol was
680 // first referenced for a source location. We need to add something
681 // to track that. Currently, we just point to the end of the file.
683 getLexer().getLoc(), SourceMgr::DK_Error,
684 "assembler local symbol '" + Sym->getName() + "' not defined");
688 // Finalize the output stream if there are no errors and if the client wants
690 if (!HadError && !NoFinalize)
696 void AsmParser::checkForValidSection() {
697 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
698 TokError("expected section directive before assembly directive");
703 /// \brief Throw away the rest of the line for testing purposes.
704 void AsmParser::eatToEndOfStatement() {
705 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
709 if (Lexer.is(AsmToken::EndOfStatement))
713 StringRef AsmParser::parseStringToEndOfStatement() {
714 const char *Start = getTok().getLoc().getPointer();
716 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
719 const char *End = getTok().getLoc().getPointer();
720 return StringRef(Start, End - Start);
723 StringRef AsmParser::parseStringToComma() {
724 const char *Start = getTok().getLoc().getPointer();
726 while (Lexer.isNot(AsmToken::EndOfStatement) &&
727 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
730 const char *End = getTok().getLoc().getPointer();
731 return StringRef(Start, End - Start);
734 /// \brief Parse a paren expression and return it.
735 /// NOTE: This assumes the leading '(' has already been consumed.
737 /// parenexpr ::= expr)
739 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
740 if (parseExpression(Res))
742 if (Lexer.isNot(AsmToken::RParen))
743 return TokError("expected ')' in parentheses expression");
744 EndLoc = Lexer.getTok().getEndLoc();
749 /// \brief Parse a bracket expression and return it.
750 /// NOTE: This assumes the leading '[' has already been consumed.
752 /// bracketexpr ::= expr]
754 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
755 if (parseExpression(Res))
757 if (Lexer.isNot(AsmToken::RBrac))
758 return TokError("expected ']' in brackets expression");
759 EndLoc = Lexer.getTok().getEndLoc();
764 /// \brief Parse a primary expression and return it.
765 /// primaryexpr ::= (parenexpr
766 /// primaryexpr ::= symbol
767 /// primaryexpr ::= number
768 /// primaryexpr ::= '.'
769 /// primaryexpr ::= ~,+,- primaryexpr
770 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
771 SMLoc FirstTokenLoc = getLexer().getLoc();
772 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
773 switch (FirstTokenKind) {
775 return TokError("unknown token in expression");
776 // If we have an error assume that we've already handled it.
777 case AsmToken::Error:
779 case AsmToken::Exclaim:
780 Lex(); // Eat the operator.
781 if (parsePrimaryExpr(Res, EndLoc))
783 Res = MCUnaryExpr::CreateLNot(Res, getContext());
785 case AsmToken::Dollar:
787 case AsmToken::String:
788 case AsmToken::Identifier: {
789 StringRef Identifier;
790 if (parseIdentifier(Identifier)) {
791 if (FirstTokenKind == AsmToken::Dollar) {
792 if (Lexer.getMAI().getDollarIsPC()) {
793 // This is a '$' reference, which references the current PC. Emit a
794 // temporary label to the streamer and refer to it.
795 MCSymbol *Sym = Ctx.CreateTempSymbol();
797 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
799 EndLoc = FirstTokenLoc;
802 return Error(FirstTokenLoc, "invalid token in expression");
806 // Parse symbol variant
807 std::pair<StringRef, StringRef> Split;
808 if (!MAI.useParensForSymbolVariant()) {
809 Split = Identifier.split('@');
810 } else if (Lexer.is(AsmToken::LParen)) {
811 Lexer.Lex(); // eat (
813 parseIdentifier(VName);
814 if (Lexer.isNot(AsmToken::RParen)) {
815 return Error(Lexer.getTok().getLoc(),
816 "unexpected token in variant, expected ')'");
818 Lexer.Lex(); // eat )
819 Split = std::make_pair(Identifier, VName);
822 EndLoc = SMLoc::getFromPointer(Identifier.end());
824 // This is a symbol reference.
825 StringRef SymbolName = Identifier;
826 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
828 // Lookup the symbol variant if used.
829 if (Split.second.size()) {
830 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
831 if (Variant != MCSymbolRefExpr::VK_Invalid) {
832 SymbolName = Split.first;
833 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
834 Variant = MCSymbolRefExpr::VK_None;
836 Variant = MCSymbolRefExpr::VK_None;
837 return Error(SMLoc::getFromPointer(Split.second.begin()),
838 "invalid variant '" + Split.second + "'");
842 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
844 // If this is an absolute variable reference, substitute it now to preserve
845 // semantics in the face of reassignment.
846 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
848 return Error(EndLoc, "unexpected modifier on variable reference");
850 Res = Sym->getVariableValue();
854 // Otherwise create a symbol ref.
855 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
858 case AsmToken::BigNum:
859 return TokError("literal value out of range for directive");
860 case AsmToken::Integer: {
861 SMLoc Loc = getTok().getLoc();
862 int64_t IntVal = getTok().getIntVal();
863 Res = MCConstantExpr::Create(IntVal, getContext());
864 EndLoc = Lexer.getTok().getEndLoc();
866 // Look for 'b' or 'f' following an Integer as a directional label
867 if (Lexer.getKind() == AsmToken::Identifier) {
868 StringRef IDVal = getTok().getString();
869 // Lookup the symbol variant if used.
870 std::pair<StringRef, StringRef> Split = IDVal.split('@');
871 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
872 if (Split.first.size() != IDVal.size()) {
873 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
874 if (Variant == MCSymbolRefExpr::VK_Invalid) {
875 Variant = MCSymbolRefExpr::VK_None;
876 return TokError("invalid variant '" + Split.second + "'");
880 if (IDVal == "f" || IDVal == "b") {
882 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "f" ? 1 : 0);
883 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
884 if (IDVal == "b" && Sym->isUndefined())
885 return Error(Loc, "invalid reference to undefined symbol");
886 EndLoc = Lexer.getTok().getEndLoc();
887 Lex(); // Eat identifier.
892 case AsmToken::Real: {
893 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
894 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
895 Res = MCConstantExpr::Create(IntVal, getContext());
896 EndLoc = Lexer.getTok().getEndLoc();
900 case AsmToken::Dot: {
901 // This is a '.' reference, which references the current PC. Emit a
902 // temporary label to the streamer and refer to it.
903 MCSymbol *Sym = Ctx.CreateTempSymbol();
905 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
906 EndLoc = Lexer.getTok().getEndLoc();
907 Lex(); // Eat identifier.
910 case AsmToken::LParen:
911 Lex(); // Eat the '('.
912 return parseParenExpr(Res, EndLoc);
913 case AsmToken::LBrac:
914 if (!PlatformParser->HasBracketExpressions())
915 return TokError("brackets expression not supported on this target");
916 Lex(); // Eat the '['.
917 return parseBracketExpr(Res, EndLoc);
918 case AsmToken::Minus:
919 Lex(); // Eat the operator.
920 if (parsePrimaryExpr(Res, EndLoc))
922 Res = MCUnaryExpr::CreateMinus(Res, getContext());
925 Lex(); // Eat the operator.
926 if (parsePrimaryExpr(Res, EndLoc))
928 Res = MCUnaryExpr::CreatePlus(Res, getContext());
930 case AsmToken::Tilde:
931 Lex(); // Eat the operator.
932 if (parsePrimaryExpr(Res, EndLoc))
934 Res = MCUnaryExpr::CreateNot(Res, getContext());
939 bool AsmParser::parseExpression(const MCExpr *&Res) {
941 return parseExpression(Res, EndLoc);
945 AsmParser::applyModifierToExpr(const MCExpr *E,
946 MCSymbolRefExpr::VariantKind Variant) {
947 // Ask the target implementation about this expression first.
948 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
951 // Recurse over the given expression, rebuilding it to apply the given variant
952 // if there is exactly one symbol.
953 switch (E->getKind()) {
955 case MCExpr::Constant:
958 case MCExpr::SymbolRef: {
959 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
961 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
962 TokError("invalid variant on expression '" + getTok().getIdentifier() +
963 "' (already modified)");
967 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
970 case MCExpr::Unary: {
971 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
972 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
975 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
978 case MCExpr::Binary: {
979 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
980 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
981 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
991 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
995 llvm_unreachable("Invalid expression kind!");
998 /// \brief Parse an expression and return it.
1000 /// expr ::= expr &&,|| expr -> lowest.
1001 /// expr ::= expr |,^,&,! expr
1002 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1003 /// expr ::= expr <<,>> expr
1004 /// expr ::= expr +,- expr
1005 /// expr ::= expr *,/,% expr -> highest.
1006 /// expr ::= primaryexpr
1008 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1009 // Parse the expression.
1011 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1014 // As a special case, we support 'a op b @ modifier' by rewriting the
1015 // expression to include the modifier. This is inefficient, but in general we
1016 // expect users to use 'a@modifier op b'.
1017 if (Lexer.getKind() == AsmToken::At) {
1020 if (Lexer.isNot(AsmToken::Identifier))
1021 return TokError("unexpected symbol modifier following '@'");
1023 MCSymbolRefExpr::VariantKind Variant =
1024 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1025 if (Variant == MCSymbolRefExpr::VK_Invalid)
1026 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1028 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1030 return TokError("invalid modifier '" + getTok().getIdentifier() +
1031 "' (no symbols present)");
1038 // Try to constant fold it up front, if possible.
1040 if (Res->EvaluateAsAbsolute(Value))
1041 Res = MCConstantExpr::Create(Value, getContext());
1046 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1048 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1051 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1054 SMLoc StartLoc = Lexer.getLoc();
1055 if (parseExpression(Expr))
1058 if (!Expr->EvaluateAsAbsolute(Res))
1059 return Error(StartLoc, "expected absolute expression");
1064 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1065 MCBinaryExpr::Opcode &Kind) {
1068 return 0; // not a binop.
1070 // Lowest Precedence: &&, ||
1071 case AsmToken::AmpAmp:
1072 Kind = MCBinaryExpr::LAnd;
1074 case AsmToken::PipePipe:
1075 Kind = MCBinaryExpr::LOr;
1078 // Low Precedence: |, &, ^
1080 // FIXME: gas seems to support '!' as an infix operator?
1081 case AsmToken::Pipe:
1082 Kind = MCBinaryExpr::Or;
1084 case AsmToken::Caret:
1085 Kind = MCBinaryExpr::Xor;
1088 Kind = MCBinaryExpr::And;
1091 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1092 case AsmToken::EqualEqual:
1093 Kind = MCBinaryExpr::EQ;
1095 case AsmToken::ExclaimEqual:
1096 case AsmToken::LessGreater:
1097 Kind = MCBinaryExpr::NE;
1099 case AsmToken::Less:
1100 Kind = MCBinaryExpr::LT;
1102 case AsmToken::LessEqual:
1103 Kind = MCBinaryExpr::LTE;
1105 case AsmToken::Greater:
1106 Kind = MCBinaryExpr::GT;
1108 case AsmToken::GreaterEqual:
1109 Kind = MCBinaryExpr::GTE;
1112 // Intermediate Precedence: <<, >>
1113 case AsmToken::LessLess:
1114 Kind = MCBinaryExpr::Shl;
1116 case AsmToken::GreaterGreater:
1117 Kind = MCBinaryExpr::Shr;
1120 // High Intermediate Precedence: +, -
1121 case AsmToken::Plus:
1122 Kind = MCBinaryExpr::Add;
1124 case AsmToken::Minus:
1125 Kind = MCBinaryExpr::Sub;
1128 // Highest Precedence: *, /, %
1129 case AsmToken::Star:
1130 Kind = MCBinaryExpr::Mul;
1132 case AsmToken::Slash:
1133 Kind = MCBinaryExpr::Div;
1135 case AsmToken::Percent:
1136 Kind = MCBinaryExpr::Mod;
1141 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1142 /// Res contains the LHS of the expression on input.
1143 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1146 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1147 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1149 // If the next token is lower precedence than we are allowed to eat, return
1150 // successfully with what we ate already.
1151 if (TokPrec < Precedence)
1156 // Eat the next primary expression.
1158 if (parsePrimaryExpr(RHS, EndLoc))
1161 // If BinOp binds less tightly with RHS than the operator after RHS, let
1162 // the pending operator take RHS as its LHS.
1163 MCBinaryExpr::Opcode Dummy;
1164 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1165 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1168 // Merge LHS and RHS according to operator.
1169 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1174 /// ::= EndOfStatement
1175 /// ::= Label* Directive ...Operands... EndOfStatement
1176 /// ::= Label* Identifier OperandList* EndOfStatement
1177 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1178 if (Lexer.is(AsmToken::EndOfStatement)) {
1184 // Statements always start with an identifier or are a full line comment.
1185 AsmToken ID = getTok();
1186 SMLoc IDLoc = ID.getLoc();
1188 int64_t LocalLabelVal = -1;
1189 // A full line comment is a '#' as the first token.
1190 if (Lexer.is(AsmToken::Hash))
1191 return parseCppHashLineFilenameComment(IDLoc);
1193 // Allow an integer followed by a ':' as a directional local label.
1194 if (Lexer.is(AsmToken::Integer)) {
1195 LocalLabelVal = getTok().getIntVal();
1196 if (LocalLabelVal < 0) {
1197 if (!TheCondState.Ignore)
1198 return TokError("unexpected token at start of statement");
1201 IDVal = getTok().getString();
1202 Lex(); // Consume the integer token to be used as an identifier token.
1203 if (Lexer.getKind() != AsmToken::Colon) {
1204 if (!TheCondState.Ignore)
1205 return TokError("unexpected token at start of statement");
1208 } else if (Lexer.is(AsmToken::Dot)) {
1209 // Treat '.' as a valid identifier in this context.
1212 } else if (parseIdentifier(IDVal)) {
1213 if (!TheCondState.Ignore)
1214 return TokError("unexpected token at start of statement");
1218 // Handle conditional assembly here before checking for skipping. We
1219 // have to do this so that .endif isn't skipped in a ".if 0" block for
1221 StringMap<DirectiveKind>::const_iterator DirKindIt =
1222 DirectiveKindMap.find(IDVal);
1223 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1225 : DirKindIt->getValue();
1230 return parseDirectiveIf(IDLoc);
1232 return parseDirectiveIfb(IDLoc, true);
1234 return parseDirectiveIfb(IDLoc, false);
1236 return parseDirectiveIfc(IDLoc, true);
1238 return parseDirectiveIfc(IDLoc, false);
1240 return parseDirectiveIfdef(IDLoc, true);
1243 return parseDirectiveIfdef(IDLoc, false);
1245 return parseDirectiveElseIf(IDLoc);
1247 return parseDirectiveElse(IDLoc);
1249 return parseDirectiveEndIf(IDLoc);
1252 // Ignore the statement if in the middle of inactive conditional
1254 if (TheCondState.Ignore) {
1255 eatToEndOfStatement();
1259 // FIXME: Recurse on local labels?
1261 // See what kind of statement we have.
1262 switch (Lexer.getKind()) {
1263 case AsmToken::Colon: {
1264 checkForValidSection();
1266 // identifier ':' -> Label.
1269 // Diagnose attempt to use '.' as a label.
1271 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1273 // Diagnose attempt to use a variable as a label.
1275 // FIXME: Diagnostics. Note the location of the definition as a label.
1276 // FIXME: This doesn't diagnose assignment to a symbol which has been
1277 // implicitly marked as external.
1279 if (LocalLabelVal == -1)
1280 Sym = getContext().GetOrCreateSymbol(IDVal);
1282 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1283 if (!Sym->isUndefined() || Sym->isVariable())
1284 return Error(IDLoc, "invalid symbol redefinition");
1287 if (!ParsingInlineAsm)
1290 // If we are generating dwarf for assembly source files then gather the
1291 // info to make a dwarf label entry for this label if needed.
1292 if (getContext().getGenDwarfForAssembly())
1293 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1296 getTargetParser().onLabelParsed(Sym);
1298 // Consume any end of statement token, if present, to avoid spurious
1299 // AddBlankLine calls().
1300 if (Lexer.is(AsmToken::EndOfStatement)) {
1302 if (Lexer.is(AsmToken::Eof))
1309 case AsmToken::Equal:
1310 // identifier '=' ... -> assignment statement
1313 return parseAssignment(IDVal, true);
1315 default: // Normal instruction or directive.
1319 // If macros are enabled, check to see if this is a macro instantiation.
1320 if (areMacrosEnabled())
1321 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1322 return handleMacroEntry(M, IDLoc);
1325 // Otherwise, we have a normal instruction or directive.
1327 // Directives start with "."
1328 if (IDVal[0] == '.' && IDVal != ".") {
1329 // There are several entities interested in parsing directives:
1331 // 1. The target-specific assembly parser. Some directives are target
1332 // specific or may potentially behave differently on certain targets.
1333 // 2. Asm parser extensions. For example, platform-specific parsers
1334 // (like the ELF parser) register themselves as extensions.
1335 // 3. The generic directive parser implemented by this class. These are
1336 // all the directives that behave in a target and platform independent
1337 // manner, or at least have a default behavior that's shared between
1338 // all targets and platforms.
1340 // First query the target-specific parser. It will return 'true' if it
1341 // isn't interested in this directive.
1342 if (!getTargetParser().ParseDirective(ID))
1345 // Next, check the extension directive map to see if any extension has
1346 // registered itself to parse this directive.
1347 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1348 ExtensionDirectiveMap.lookup(IDVal);
1350 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1352 // Finally, if no one else is interested in this directive, it must be
1353 // generic and familiar to this class.
1359 return parseDirectiveSet(IDVal, true);
1361 return parseDirectiveSet(IDVal, false);
1363 return parseDirectiveAscii(IDVal, false);
1366 return parseDirectiveAscii(IDVal, true);
1368 return parseDirectiveValue(1);
1372 return parseDirectiveValue(2);
1376 return parseDirectiveValue(4);
1379 return parseDirectiveValue(8);
1381 return parseDirectiveOctaValue();
1384 return parseDirectiveRealValue(APFloat::IEEEsingle);
1386 return parseDirectiveRealValue(APFloat::IEEEdouble);
1388 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1389 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1392 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1393 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1396 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1398 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1400 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1402 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1404 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1406 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1408 return parseDirectiveOrg();
1410 return parseDirectiveFill();
1412 return parseDirectiveZero();
1414 eatToEndOfStatement(); // .extern is the default, ignore it.
1418 return parseDirectiveSymbolAttribute(MCSA_Global);
1419 case DK_LAZY_REFERENCE:
1420 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1421 case DK_NO_DEAD_STRIP:
1422 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1423 case DK_SYMBOL_RESOLVER:
1424 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1425 case DK_PRIVATE_EXTERN:
1426 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1428 return parseDirectiveSymbolAttribute(MCSA_Reference);
1429 case DK_WEAK_DEFINITION:
1430 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1431 case DK_WEAK_REFERENCE:
1432 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1433 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1434 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1437 return parseDirectiveComm(/*IsLocal=*/false);
1439 return parseDirectiveComm(/*IsLocal=*/true);
1441 return parseDirectiveAbort();
1443 return parseDirectiveInclude();
1445 return parseDirectiveIncbin();
1448 return TokError(Twine(IDVal) + " not supported yet");
1450 return parseDirectiveRept(IDLoc, IDVal);
1452 return parseDirectiveIrp(IDLoc);
1454 return parseDirectiveIrpc(IDLoc);
1456 return parseDirectiveEndr(IDLoc);
1457 case DK_BUNDLE_ALIGN_MODE:
1458 return parseDirectiveBundleAlignMode();
1459 case DK_BUNDLE_LOCK:
1460 return parseDirectiveBundleLock();
1461 case DK_BUNDLE_UNLOCK:
1462 return parseDirectiveBundleUnlock();
1464 return parseDirectiveLEB128(true);
1466 return parseDirectiveLEB128(false);
1469 return parseDirectiveSpace(IDVal);
1471 return parseDirectiveFile(IDLoc);
1473 return parseDirectiveLine();
1475 return parseDirectiveLoc();
1477 return parseDirectiveStabs();
1478 case DK_CFI_SECTIONS:
1479 return parseDirectiveCFISections();
1480 case DK_CFI_STARTPROC:
1481 return parseDirectiveCFIStartProc();
1482 case DK_CFI_ENDPROC:
1483 return parseDirectiveCFIEndProc();
1484 case DK_CFI_DEF_CFA:
1485 return parseDirectiveCFIDefCfa(IDLoc);
1486 case DK_CFI_DEF_CFA_OFFSET:
1487 return parseDirectiveCFIDefCfaOffset();
1488 case DK_CFI_ADJUST_CFA_OFFSET:
1489 return parseDirectiveCFIAdjustCfaOffset();
1490 case DK_CFI_DEF_CFA_REGISTER:
1491 return parseDirectiveCFIDefCfaRegister(IDLoc);
1493 return parseDirectiveCFIOffset(IDLoc);
1494 case DK_CFI_REL_OFFSET:
1495 return parseDirectiveCFIRelOffset(IDLoc);
1496 case DK_CFI_PERSONALITY:
1497 return parseDirectiveCFIPersonalityOrLsda(true);
1499 return parseDirectiveCFIPersonalityOrLsda(false);
1500 case DK_CFI_REMEMBER_STATE:
1501 return parseDirectiveCFIRememberState();
1502 case DK_CFI_RESTORE_STATE:
1503 return parseDirectiveCFIRestoreState();
1504 case DK_CFI_SAME_VALUE:
1505 return parseDirectiveCFISameValue(IDLoc);
1506 case DK_CFI_RESTORE:
1507 return parseDirectiveCFIRestore(IDLoc);
1509 return parseDirectiveCFIEscape();
1510 case DK_CFI_SIGNAL_FRAME:
1511 return parseDirectiveCFISignalFrame();
1512 case DK_CFI_UNDEFINED:
1513 return parseDirectiveCFIUndefined(IDLoc);
1514 case DK_CFI_REGISTER:
1515 return parseDirectiveCFIRegister(IDLoc);
1516 case DK_CFI_WINDOW_SAVE:
1517 return parseDirectiveCFIWindowSave();
1520 return parseDirectiveMacrosOnOff(IDVal);
1522 return parseDirectiveMacro(IDLoc);
1525 return parseDirectiveEndMacro(IDVal);
1527 return parseDirectivePurgeMacro(IDLoc);
1529 return parseDirectiveEnd(IDLoc);
1532 return Error(IDLoc, "unknown directive");
1535 // __asm _emit or __asm __emit
1536 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1537 IDVal == "_EMIT" || IDVal == "__EMIT"))
1538 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1541 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1542 return parseDirectiveMSAlign(IDLoc, Info);
1544 checkForValidSection();
1546 // Canonicalize the opcode to lower case.
1547 std::string OpcodeStr = IDVal.lower();
1548 ParseInstructionInfo IInfo(Info.AsmRewrites);
1549 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1550 Info.ParsedOperands);
1551 Info.ParseError = HadError;
1553 // Dump the parsed representation, if requested.
1554 if (getShowParsedOperands()) {
1555 SmallString<256> Str;
1556 raw_svector_ostream OS(Str);
1557 OS << "parsed instruction: [";
1558 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1561 Info.ParsedOperands[i]->print(OS);
1565 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1568 // If we are generating dwarf for assembly source files and the current
1569 // section is the initial text section then generate a .loc directive for
1571 if (!HadError && getContext().getGenDwarfForAssembly() &&
1572 getContext().getGenDwarfSection() ==
1573 getStreamer().getCurrentSection().first) {
1575 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1577 // If we previously parsed a cpp hash file line comment then make sure the
1578 // current Dwarf File is for the CppHashFilename if not then emit the
1579 // Dwarf File table for it and adjust the line number for the .loc.
1580 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
1581 getContext().getMCDwarfFiles();
1582 if (CppHashFilename.size() != 0) {
1583 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1585 getStreamer().EmitDwarfFileDirective(
1586 getContext().nextGenDwarfFileNumber(), StringRef(),
1589 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1590 // cache with the different Loc from the call above we save the last
1591 // info we queried here with SrcMgr.FindLineNumber().
1592 unsigned CppHashLocLineNo;
1593 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1594 CppHashLocLineNo = LastQueryLine;
1596 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1597 LastQueryLine = CppHashLocLineNo;
1598 LastQueryIDLoc = CppHashLoc;
1599 LastQueryBuffer = CppHashBuf;
1601 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1604 getStreamer().EmitDwarfLocDirective(
1605 getContext().getGenDwarfFileNumber(), Line, 0,
1606 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1610 // If parsing succeeded, match the instruction.
1613 HadError = getTargetParser().MatchAndEmitInstruction(
1614 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
1618 // Don't skip the rest of the line, the instruction parser is responsible for
1623 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1624 /// since they may not be able to be tokenized to get to the end of line token.
1625 void AsmParser::eatToEndOfLine() {
1626 if (!Lexer.is(AsmToken::EndOfStatement))
1627 Lexer.LexUntilEndOfLine();
1632 /// parseCppHashLineFilenameComment as this:
1633 /// ::= # number "filename"
1634 /// or just as a full line comment if it doesn't have a number and a string.
1635 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1636 Lex(); // Eat the hash token.
1638 if (getLexer().isNot(AsmToken::Integer)) {
1639 // Consume the line since in cases it is not a well-formed line directive,
1640 // as if were simply a full line comment.
1645 int64_t LineNumber = getTok().getIntVal();
1648 if (getLexer().isNot(AsmToken::String)) {
1653 StringRef Filename = getTok().getString();
1654 // Get rid of the enclosing quotes.
1655 Filename = Filename.substr(1, Filename.size() - 2);
1657 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1659 CppHashFilename = Filename;
1660 CppHashLineNumber = LineNumber;
1661 CppHashBuf = CurBuffer;
1663 // Ignore any trailing characters, they're just comment.
1668 /// \brief will use the last parsed cpp hash line filename comment
1669 /// for the Filename and LineNo if any in the diagnostic.
1670 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1671 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1672 raw_ostream &OS = errs();
1674 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1675 const SMLoc &DiagLoc = Diag.getLoc();
1676 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1677 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1679 // Like SourceMgr::printMessage() we need to print the include stack if any
1680 // before printing the message.
1681 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1682 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1683 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1684 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1687 // If we have not parsed a cpp hash line filename comment or the source
1688 // manager changed or buffer changed (like in a nested include) then just
1689 // print the normal diagnostic using its Filename and LineNo.
1690 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1691 DiagBuf != CppHashBuf) {
1692 if (Parser->SavedDiagHandler)
1693 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1699 // Use the CppHashFilename and calculate a line number based on the
1700 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1702 const std::string &Filename = Parser->CppHashFilename;
1704 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1705 int CppHashLocLineNo =
1706 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1708 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1710 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1711 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1712 Diag.getLineContents(), Diag.getRanges());
1714 if (Parser->SavedDiagHandler)
1715 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1717 NewDiag.print(0, OS);
1720 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1721 // difference being that that function accepts '@' as part of identifiers and
1722 // we can't do that. AsmLexer.cpp should probably be changed to handle
1723 // '@' as a special case when needed.
1724 static bool isIdentifierChar(char c) {
1725 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1729 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1730 ArrayRef<MCAsmMacroParameter> Parameters,
1731 ArrayRef<MCAsmMacroArgument> A, const SMLoc &L) {
1732 unsigned NParameters = Parameters.size();
1733 if (NParameters != 0 && NParameters != A.size())
1734 return Error(L, "Wrong number of arguments");
1736 // A macro without parameters is handled differently on Darwin:
1737 // gas accepts no arguments and does no substitutions
1738 while (!Body.empty()) {
1739 // Scan for the next substitution.
1740 std::size_t End = Body.size(), Pos = 0;
1741 for (; Pos != End; ++Pos) {
1742 // Check for a substitution or escape.
1744 // This macro has no parameters, look for $0, $1, etc.
1745 if (Body[Pos] != '$' || Pos + 1 == End)
1748 char Next = Body[Pos + 1];
1749 if (Next == '$' || Next == 'n' ||
1750 isdigit(static_cast<unsigned char>(Next)))
1753 // This macro has parameters, look for \foo, \bar, etc.
1754 if (Body[Pos] == '\\' && Pos + 1 != End)
1760 OS << Body.slice(0, Pos);
1762 // Check if we reached the end.
1767 switch (Body[Pos + 1]) {
1773 // $n => number of arguments
1778 // $[0-9] => argument
1780 // Missing arguments are ignored.
1781 unsigned Index = Body[Pos + 1] - '0';
1782 if (Index >= A.size())
1785 // Otherwise substitute with the token values, with spaces eliminated.
1786 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1787 ie = A[Index].end();
1789 OS << it->getString();
1795 unsigned I = Pos + 1;
1796 while (isIdentifierChar(Body[I]) && I + 1 != End)
1799 const char *Begin = Body.data() + Pos + 1;
1800 StringRef Argument(Begin, I - (Pos + 1));
1802 for (; Index < NParameters; ++Index)
1803 if (Parameters[Index].Name == Argument)
1806 if (Index == NParameters) {
1807 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1810 OS << '\\' << Argument;
1814 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1815 ie = A[Index].end();
1817 if (it->getKind() == AsmToken::String)
1818 OS << it->getStringContents();
1820 OS << it->getString();
1822 Pos += 1 + Argument.size();
1825 // Update the scan point.
1826 Body = Body.substr(Pos);
1832 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1833 SMLoc EL, MemoryBuffer *I)
1834 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1837 static bool isOperator(AsmToken::TokenKind kind) {
1841 case AsmToken::Plus:
1842 case AsmToken::Minus:
1843 case AsmToken::Tilde:
1844 case AsmToken::Slash:
1845 case AsmToken::Star:
1847 case AsmToken::Equal:
1848 case AsmToken::EqualEqual:
1849 case AsmToken::Pipe:
1850 case AsmToken::PipePipe:
1851 case AsmToken::Caret:
1853 case AsmToken::AmpAmp:
1854 case AsmToken::Exclaim:
1855 case AsmToken::ExclaimEqual:
1856 case AsmToken::Percent:
1857 case AsmToken::Less:
1858 case AsmToken::LessEqual:
1859 case AsmToken::LessLess:
1860 case AsmToken::LessGreater:
1861 case AsmToken::Greater:
1862 case AsmToken::GreaterEqual:
1863 case AsmToken::GreaterGreater:
1869 class AsmLexerSkipSpaceRAII {
1871 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1872 Lexer.setSkipSpace(SkipSpace);
1875 ~AsmLexerSkipSpaceRAII() {
1876 Lexer.setSkipSpace(true);
1884 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA) {
1885 unsigned ParenLevel = 0;
1886 unsigned AddTokens = 0;
1888 // Darwin doesn't use spaces to delmit arguments.
1889 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1892 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1893 return TokError("unexpected token in macro instantiation");
1895 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1898 if (Lexer.is(AsmToken::Space)) {
1899 Lex(); // Eat spaces
1901 // Spaces can delimit parameters, but could also be part an expression.
1902 // If the token after a space is an operator, add the token and the next
1903 // one into this argument
1905 if (isOperator(Lexer.getKind())) {
1906 // Check to see whether the token is used as an operator,
1907 // or part of an identifier
1908 const char *NextChar = getTok().getEndLoc().getPointer();
1909 if (*NextChar == ' ')
1913 if (!AddTokens && ParenLevel == 0) {
1919 // handleMacroEntry relies on not advancing the lexer here
1920 // to be able to fill in the remaining default parameter values
1921 if (Lexer.is(AsmToken::EndOfStatement))
1924 // Adjust the current parentheses level.
1925 if (Lexer.is(AsmToken::LParen))
1927 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1930 // Append the token to the current argument list.
1931 MA.push_back(getTok());
1937 if (ParenLevel != 0)
1938 return TokError("unbalanced parentheses in macro argument");
1942 // Parse the macro instantiation arguments.
1943 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1944 MCAsmMacroArguments &A) {
1945 const unsigned NParameters = M ? M->Parameters.size() : 0;
1946 bool NamedParametersFound = false;
1947 SmallVector<SMLoc, 4> FALocs;
1949 A.resize(NParameters);
1950 FALocs.resize(NParameters);
1952 // Parse two kinds of macro invocations:
1953 // - macros defined without any parameters accept an arbitrary number of them
1954 // - macros defined with parameters accept at most that many of them
1955 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1957 SMLoc IDLoc = Lexer.getLoc();
1958 MCAsmMacroParameter FA;
1960 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
1961 if (parseIdentifier(FA.Name)) {
1962 Error(IDLoc, "invalid argument identifier for formal argument");
1963 eatToEndOfStatement();
1967 if (!Lexer.is(AsmToken::Equal)) {
1968 TokError("expected '=' after formal parameter identifier");
1969 eatToEndOfStatement();
1974 NamedParametersFound = true;
1977 if (NamedParametersFound && FA.Name.empty()) {
1978 Error(IDLoc, "cannot mix positional and keyword arguments");
1979 eatToEndOfStatement();
1983 if (parseMacroArgument(FA.Value))
1986 unsigned PI = Parameter;
1987 if (!FA.Name.empty()) {
1989 for (FAI = 0; FAI < NParameters; ++FAI)
1990 if (M->Parameters[FAI].Name == FA.Name)
1993 if (FAI >= NParameters) {
1995 "parameter named '" + FA.Name + "' does not exist for macro '" +
2002 if (!FA.Value.empty()) {
2007 if (FALocs.size() <= PI)
2008 FALocs.resize(PI + 1);
2010 FALocs[PI] = Lexer.getLoc();
2013 // At the end of the statement, fill in remaining arguments that have
2014 // default values. If there aren't any, then the next argument is
2015 // required but missing
2016 if (Lexer.is(AsmToken::EndOfStatement)) {
2017 bool Failure = false;
2018 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2019 if (A[FAI].empty()) {
2020 if (M->Parameters[FAI].Required) {
2021 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2022 "missing value for required parameter "
2023 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2027 if (!M->Parameters[FAI].Value.empty())
2028 A[FAI] = M->Parameters[FAI].Value;
2034 if (Lexer.is(AsmToken::Comma))
2038 return TokError("too many positional arguments");
2041 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2042 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2043 return (I == MacroMap.end()) ? NULL : I->getValue();
2046 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
2047 MacroMap[Name] = new MCAsmMacro(Macro);
2050 void AsmParser::undefineMacro(StringRef Name) {
2051 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2052 if (I != MacroMap.end()) {
2053 delete I->getValue();
2058 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2059 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2060 // this, although we should protect against infinite loops.
2061 if (ActiveMacros.size() == 20)
2062 return TokError("macros cannot be nested more than 20 levels deep");
2064 MCAsmMacroArguments A;
2065 if (parseMacroArguments(M, A))
2068 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2069 // to hold the macro body with substitutions.
2070 SmallString<256> Buf;
2071 StringRef Body = M->Body;
2072 raw_svector_ostream OS(Buf);
2074 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2077 // We include the .endmacro in the buffer as our cue to exit the macro
2079 OS << ".endmacro\n";
2081 MemoryBuffer *Instantiation =
2082 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2084 // Create the macro instantiation object and add to the current macro
2085 // instantiation stack.
2086 MacroInstantiation *MI = new MacroInstantiation(
2087 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
2088 ActiveMacros.push_back(MI);
2090 // Jump to the macro instantiation and prime the lexer.
2091 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2092 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2098 void AsmParser::handleMacroExit() {
2099 // Jump to the EndOfStatement we should return to, and consume it.
2100 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2103 // Pop the instantiation entry.
2104 delete ActiveMacros.back();
2105 ActiveMacros.pop_back();
2108 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2109 switch (Value->getKind()) {
2110 case MCExpr::Binary: {
2111 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2112 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2114 case MCExpr::Target:
2115 case MCExpr::Constant:
2117 case MCExpr::SymbolRef: {
2119 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2121 return isUsedIn(Sym, S.getVariableValue());
2125 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2128 llvm_unreachable("Unknown expr kind!");
2131 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2133 // FIXME: Use better location, we should use proper tokens.
2134 SMLoc EqualLoc = Lexer.getLoc();
2136 const MCExpr *Value;
2137 if (parseExpression(Value))
2140 // Note: we don't count b as used in "a = b". This is to allow
2144 if (Lexer.isNot(AsmToken::EndOfStatement))
2145 return TokError("unexpected token in assignment");
2147 // Eat the end of statement marker.
2150 // Validate that the LHS is allowed to be a variable (either it has not been
2151 // used as a symbol, or it is an absolute symbol).
2152 MCSymbol *Sym = getContext().LookupSymbol(Name);
2154 // Diagnose assignment to a label.
2156 // FIXME: Diagnostics. Note the location of the definition as a label.
2157 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2158 if (isUsedIn(Sym, Value))
2159 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2160 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2161 ; // Allow redefinitions of undefined symbols only used in directives.
2162 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2163 ; // Allow redefinitions of variables that haven't yet been used.
2164 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2165 return Error(EqualLoc, "redefinition of '" + Name + "'");
2166 else if (!Sym->isVariable())
2167 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2168 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2169 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2172 // Don't count these checks as uses.
2173 Sym->setUsed(false);
2174 } else if (Name == ".") {
2175 if (Out.EmitValueToOffset(Value, 0)) {
2176 Error(EqualLoc, "expected absolute expression");
2177 eatToEndOfStatement();
2181 Sym = getContext().GetOrCreateSymbol(Name);
2183 // Do the assignment.
2184 Out.EmitAssignment(Sym, Value);
2186 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2191 /// parseIdentifier:
2194 bool AsmParser::parseIdentifier(StringRef &Res) {
2195 // The assembler has relaxed rules for accepting identifiers, in particular we
2196 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2197 // separate tokens. At this level, we have already lexed so we cannot (currently)
2198 // handle this as a context dependent token, instead we detect adjacent tokens
2199 // and return the combined identifier.
2200 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2201 SMLoc PrefixLoc = getLexer().getLoc();
2203 // Consume the prefix character, and check for a following identifier.
2205 if (Lexer.isNot(AsmToken::Identifier))
2208 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2209 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2212 // Construct the joined identifier and consume the token.
2214 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2219 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2222 Res = getTok().getIdentifier();
2224 Lex(); // Consume the identifier token.
2229 /// parseDirectiveSet:
2230 /// ::= .equ identifier ',' expression
2231 /// ::= .equiv identifier ',' expression
2232 /// ::= .set identifier ',' expression
2233 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2236 if (parseIdentifier(Name))
2237 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2239 if (getLexer().isNot(AsmToken::Comma))
2240 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2243 return parseAssignment(Name, allow_redef, true);
2246 bool AsmParser::parseEscapedString(std::string &Data) {
2247 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2250 StringRef Str = getTok().getStringContents();
2251 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2252 if (Str[i] != '\\') {
2257 // Recognize escaped characters. Note that this escape semantics currently
2258 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2261 return TokError("unexpected backslash at end of string");
2263 // Recognize octal sequences.
2264 if ((unsigned)(Str[i] - '0') <= 7) {
2265 // Consume up to three octal characters.
2266 unsigned Value = Str[i] - '0';
2268 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2270 Value = Value * 8 + (Str[i] - '0');
2272 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2274 Value = Value * 8 + (Str[i] - '0');
2279 return TokError("invalid octal escape sequence (out of range)");
2281 Data += (unsigned char)Value;
2285 // Otherwise recognize individual escapes.
2288 // Just reject invalid escape sequences for now.
2289 return TokError("invalid escape sequence (unrecognized character)");
2291 case 'b': Data += '\b'; break;
2292 case 'f': Data += '\f'; break;
2293 case 'n': Data += '\n'; break;
2294 case 'r': Data += '\r'; break;
2295 case 't': Data += '\t'; break;
2296 case '"': Data += '"'; break;
2297 case '\\': Data += '\\'; break;
2304 /// parseDirectiveAscii:
2305 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2306 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2307 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2308 checkForValidSection();
2311 if (getLexer().isNot(AsmToken::String))
2312 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2315 if (parseEscapedString(Data))
2318 getStreamer().EmitBytes(Data);
2320 getStreamer().EmitBytes(StringRef("\0", 1));
2324 if (getLexer().is(AsmToken::EndOfStatement))
2327 if (getLexer().isNot(AsmToken::Comma))
2328 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2337 /// parseDirectiveValue
2338 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2339 bool AsmParser::parseDirectiveValue(unsigned Size) {
2340 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2341 checkForValidSection();
2344 const MCExpr *Value;
2345 SMLoc ExprLoc = getLexer().getLoc();
2346 if (parseExpression(Value))
2349 // Special case constant expressions to match code generator.
2350 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2351 assert(Size <= 8 && "Invalid size");
2352 uint64_t IntValue = MCE->getValue();
2353 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2354 return Error(ExprLoc, "literal value out of range for directive");
2355 getStreamer().EmitIntValue(IntValue, Size);
2357 getStreamer().EmitValue(Value, Size);
2359 if (getLexer().is(AsmToken::EndOfStatement))
2362 // FIXME: Improve diagnostic.
2363 if (getLexer().isNot(AsmToken::Comma))
2364 return TokError("unexpected token in directive");
2373 /// ParseDirectiveOctaValue
2374 /// ::= .octa [ hexconstant (, hexconstant)* ]
2375 bool AsmParser::parseDirectiveOctaValue() {
2376 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2377 checkForValidSection();
2380 if (Lexer.getKind() == AsmToken::Error)
2382 if (Lexer.getKind() != AsmToken::Integer &&
2383 Lexer.getKind() != AsmToken::BigNum)
2384 return TokError("unknown token in expression");
2386 SMLoc ExprLoc = getLexer().getLoc();
2387 APInt IntValue = getTok().getAPIntVal();
2391 if (IntValue.isIntN(64)) {
2393 lo = IntValue.getZExtValue();
2394 } else if (IntValue.isIntN(128)) {
2395 // It might actually have more than 128 bits, but the top ones are zero.
2396 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2397 lo = IntValue.getLoBits(64).getZExtValue();
2399 return Error(ExprLoc, "literal value out of range for directive");
2401 if (MAI.isLittleEndian()) {
2402 getStreamer().EmitIntValue(lo, 8);
2403 getStreamer().EmitIntValue(hi, 8);
2405 getStreamer().EmitIntValue(hi, 8);
2406 getStreamer().EmitIntValue(lo, 8);
2409 if (getLexer().is(AsmToken::EndOfStatement))
2412 // FIXME: Improve diagnostic.
2413 if (getLexer().isNot(AsmToken::Comma))
2414 return TokError("unexpected token in directive");
2423 /// parseDirectiveRealValue
2424 /// ::= (.single | .double) [ expression (, expression)* ]
2425 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2426 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2427 checkForValidSection();
2430 // We don't truly support arithmetic on floating point expressions, so we
2431 // have to manually parse unary prefixes.
2433 if (getLexer().is(AsmToken::Minus)) {
2436 } else if (getLexer().is(AsmToken::Plus))
2439 if (getLexer().isNot(AsmToken::Integer) &&
2440 getLexer().isNot(AsmToken::Real) &&
2441 getLexer().isNot(AsmToken::Identifier))
2442 return TokError("unexpected token in directive");
2444 // Convert to an APFloat.
2445 APFloat Value(Semantics);
2446 StringRef IDVal = getTok().getString();
2447 if (getLexer().is(AsmToken::Identifier)) {
2448 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2449 Value = APFloat::getInf(Semantics);
2450 else if (!IDVal.compare_lower("nan"))
2451 Value = APFloat::getNaN(Semantics, false, ~0);
2453 return TokError("invalid floating point literal");
2454 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2455 APFloat::opInvalidOp)
2456 return TokError("invalid floating point literal");
2460 // Consume the numeric token.
2463 // Emit the value as an integer.
2464 APInt AsInt = Value.bitcastToAPInt();
2465 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2466 AsInt.getBitWidth() / 8);
2468 if (getLexer().is(AsmToken::EndOfStatement))
2471 if (getLexer().isNot(AsmToken::Comma))
2472 return TokError("unexpected token in directive");
2481 /// parseDirectiveZero
2482 /// ::= .zero expression
2483 bool AsmParser::parseDirectiveZero() {
2484 checkForValidSection();
2487 if (parseAbsoluteExpression(NumBytes))
2491 if (getLexer().is(AsmToken::Comma)) {
2493 if (parseAbsoluteExpression(Val))
2497 if (getLexer().isNot(AsmToken::EndOfStatement))
2498 return TokError("unexpected token in '.zero' directive");
2502 getStreamer().EmitFill(NumBytes, Val);
2507 /// parseDirectiveFill
2508 /// ::= .fill expression [ , expression [ , expression ] ]
2509 bool AsmParser::parseDirectiveFill() {
2510 checkForValidSection();
2512 SMLoc RepeatLoc = getLexer().getLoc();
2514 if (parseAbsoluteExpression(NumValues))
2517 if (NumValues < 0) {
2519 "'.fill' directive with negative repeat count has no effect");
2523 int64_t FillSize = 1;
2524 int64_t FillExpr = 0;
2526 SMLoc SizeLoc, ExprLoc;
2527 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2528 if (getLexer().isNot(AsmToken::Comma))
2529 return TokError("unexpected token in '.fill' directive");
2532 SizeLoc = getLexer().getLoc();
2533 if (parseAbsoluteExpression(FillSize))
2536 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2537 if (getLexer().isNot(AsmToken::Comma))
2538 return TokError("unexpected token in '.fill' directive");
2541 ExprLoc = getLexer().getLoc();
2542 if (parseAbsoluteExpression(FillExpr))
2545 if (getLexer().isNot(AsmToken::EndOfStatement))
2546 return TokError("unexpected token in '.fill' directive");
2553 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2557 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2561 if (!isUInt<32>(FillExpr) && FillSize > 4)
2562 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2564 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2565 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2567 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2568 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2569 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2575 /// parseDirectiveOrg
2576 /// ::= .org expression [ , expression ]
2577 bool AsmParser::parseDirectiveOrg() {
2578 checkForValidSection();
2580 const MCExpr *Offset;
2581 SMLoc Loc = getTok().getLoc();
2582 if (parseExpression(Offset))
2585 // Parse optional fill expression.
2586 int64_t FillExpr = 0;
2587 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2588 if (getLexer().isNot(AsmToken::Comma))
2589 return TokError("unexpected token in '.org' directive");
2592 if (parseAbsoluteExpression(FillExpr))
2595 if (getLexer().isNot(AsmToken::EndOfStatement))
2596 return TokError("unexpected token in '.org' directive");
2601 // Only limited forms of relocatable expressions are accepted here, it
2602 // has to be relative to the current section. The streamer will return
2603 // 'true' if the expression wasn't evaluatable.
2604 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2605 return Error(Loc, "expected assembly-time absolute expression");
2610 /// parseDirectiveAlign
2611 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2612 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2613 checkForValidSection();
2615 SMLoc AlignmentLoc = getLexer().getLoc();
2617 if (parseAbsoluteExpression(Alignment))
2621 bool HasFillExpr = false;
2622 int64_t FillExpr = 0;
2623 int64_t MaxBytesToFill = 0;
2624 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2625 if (getLexer().isNot(AsmToken::Comma))
2626 return TokError("unexpected token in directive");
2629 // The fill expression can be omitted while specifying a maximum number of
2630 // alignment bytes, e.g:
2632 if (getLexer().isNot(AsmToken::Comma)) {
2634 if (parseAbsoluteExpression(FillExpr))
2638 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2639 if (getLexer().isNot(AsmToken::Comma))
2640 return TokError("unexpected token in directive");
2643 MaxBytesLoc = getLexer().getLoc();
2644 if (parseAbsoluteExpression(MaxBytesToFill))
2647 if (getLexer().isNot(AsmToken::EndOfStatement))
2648 return TokError("unexpected token in directive");
2657 // Compute alignment in bytes.
2659 // FIXME: Diagnose overflow.
2660 if (Alignment >= 32) {
2661 Error(AlignmentLoc, "invalid alignment value");
2665 Alignment = 1ULL << Alignment;
2667 // Reject alignments that aren't a power of two, for gas compatibility.
2668 if (!isPowerOf2_64(Alignment))
2669 Error(AlignmentLoc, "alignment must be a power of 2");
2672 // Diagnose non-sensical max bytes to align.
2673 if (MaxBytesLoc.isValid()) {
2674 if (MaxBytesToFill < 1) {
2675 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2676 "many bytes, ignoring maximum bytes expression");
2680 if (MaxBytesToFill >= Alignment) {
2681 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2687 // Check whether we should use optimal code alignment for this .align
2689 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2690 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2691 ValueSize == 1 && UseCodeAlign) {
2692 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2694 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2695 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2702 /// parseDirectiveFile
2703 /// ::= .file [number] filename
2704 /// ::= .file number directory filename
2705 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2706 // FIXME: I'm not sure what this is.
2707 int64_t FileNumber = -1;
2708 SMLoc FileNumberLoc = getLexer().getLoc();
2709 if (getLexer().is(AsmToken::Integer)) {
2710 FileNumber = getTok().getIntVal();
2714 return TokError("file number less than one");
2717 if (getLexer().isNot(AsmToken::String))
2718 return TokError("unexpected token in '.file' directive");
2720 // Usually the directory and filename together, otherwise just the directory.
2721 // Allow the strings to have escaped octal character sequence.
2722 std::string Path = getTok().getString();
2723 if (parseEscapedString(Path))
2727 StringRef Directory;
2729 std::string FilenameData;
2730 if (getLexer().is(AsmToken::String)) {
2731 if (FileNumber == -1)
2732 return TokError("explicit path specified, but no file number");
2733 if (parseEscapedString(FilenameData))
2735 Filename = FilenameData;
2742 if (getLexer().isNot(AsmToken::EndOfStatement))
2743 return TokError("unexpected token in '.file' directive");
2745 if (FileNumber == -1)
2746 getStreamer().EmitFileDirective(Filename);
2748 if (getContext().getGenDwarfForAssembly() == true)
2750 "input can't have .file dwarf directives when -g is "
2751 "used to generate dwarf debug info for assembly code");
2753 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2754 Error(FileNumberLoc, "file number already allocated");
2760 /// parseDirectiveLine
2761 /// ::= .line [number]
2762 bool AsmParser::parseDirectiveLine() {
2763 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2764 if (getLexer().isNot(AsmToken::Integer))
2765 return TokError("unexpected token in '.line' directive");
2767 int64_t LineNumber = getTok().getIntVal();
2771 // FIXME: Do something with the .line.
2774 if (getLexer().isNot(AsmToken::EndOfStatement))
2775 return TokError("unexpected token in '.line' directive");
2780 /// parseDirectiveLoc
2781 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2782 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2783 /// The first number is a file number, must have been previously assigned with
2784 /// a .file directive, the second number is the line number and optionally the
2785 /// third number is a column position (zero if not specified). The remaining
2786 /// optional items are .loc sub-directives.
2787 bool AsmParser::parseDirectiveLoc() {
2788 if (getLexer().isNot(AsmToken::Integer))
2789 return TokError("unexpected token in '.loc' directive");
2790 int64_t FileNumber = getTok().getIntVal();
2792 return TokError("file number less than one in '.loc' directive");
2793 if (!getContext().isValidDwarfFileNumber(FileNumber))
2794 return TokError("unassigned file number in '.loc' directive");
2797 int64_t LineNumber = 0;
2798 if (getLexer().is(AsmToken::Integer)) {
2799 LineNumber = getTok().getIntVal();
2801 return TokError("line number less than zero in '.loc' directive");
2805 int64_t ColumnPos = 0;
2806 if (getLexer().is(AsmToken::Integer)) {
2807 ColumnPos = getTok().getIntVal();
2809 return TokError("column position less than zero in '.loc' directive");
2813 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2815 int64_t Discriminator = 0;
2816 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2818 if (getLexer().is(AsmToken::EndOfStatement))
2822 SMLoc Loc = getTok().getLoc();
2823 if (parseIdentifier(Name))
2824 return TokError("unexpected token in '.loc' directive");
2826 if (Name == "basic_block")
2827 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2828 else if (Name == "prologue_end")
2829 Flags |= DWARF2_FLAG_PROLOGUE_END;
2830 else if (Name == "epilogue_begin")
2831 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2832 else if (Name == "is_stmt") {
2833 Loc = getTok().getLoc();
2834 const MCExpr *Value;
2835 if (parseExpression(Value))
2837 // The expression must be the constant 0 or 1.
2838 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2839 int Value = MCE->getValue();
2841 Flags &= ~DWARF2_FLAG_IS_STMT;
2842 else if (Value == 1)
2843 Flags |= DWARF2_FLAG_IS_STMT;
2845 return Error(Loc, "is_stmt value not 0 or 1");
2847 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2849 } else if (Name == "isa") {
2850 Loc = getTok().getLoc();
2851 const MCExpr *Value;
2852 if (parseExpression(Value))
2854 // The expression must be a constant greater or equal to 0.
2855 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2856 int Value = MCE->getValue();
2858 return Error(Loc, "isa number less than zero");
2861 return Error(Loc, "isa number not a constant value");
2863 } else if (Name == "discriminator") {
2864 if (parseAbsoluteExpression(Discriminator))
2867 return Error(Loc, "unknown sub-directive in '.loc' directive");
2870 if (getLexer().is(AsmToken::EndOfStatement))
2875 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2876 Isa, Discriminator, StringRef());
2881 /// parseDirectiveStabs
2882 /// ::= .stabs string, number, number, number
2883 bool AsmParser::parseDirectiveStabs() {
2884 return TokError("unsupported directive '.stabs'");
2887 /// parseDirectiveCFISections
2888 /// ::= .cfi_sections section [, section]
2889 bool AsmParser::parseDirectiveCFISections() {
2894 if (parseIdentifier(Name))
2895 return TokError("Expected an identifier");
2897 if (Name == ".eh_frame")
2899 else if (Name == ".debug_frame")
2902 if (getLexer().is(AsmToken::Comma)) {
2905 if (parseIdentifier(Name))
2906 return TokError("Expected an identifier");
2908 if (Name == ".eh_frame")
2910 else if (Name == ".debug_frame")
2914 getStreamer().EmitCFISections(EH, Debug);
2918 /// parseDirectiveCFIStartProc
2919 /// ::= .cfi_startproc [simple]
2920 bool AsmParser::parseDirectiveCFIStartProc() {
2922 if (getLexer().isNot(AsmToken::EndOfStatement))
2923 if (parseIdentifier(Simple) || Simple != "simple")
2924 return TokError("unexpected token in .cfi_startproc directive");
2926 getStreamer().EmitCFIStartProc(!Simple.empty());
2930 /// parseDirectiveCFIEndProc
2931 /// ::= .cfi_endproc
2932 bool AsmParser::parseDirectiveCFIEndProc() {
2933 getStreamer().EmitCFIEndProc();
2937 /// \brief parse register name or number.
2938 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2939 SMLoc DirectiveLoc) {
2942 if (getLexer().isNot(AsmToken::Integer)) {
2943 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2945 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2947 return parseAbsoluteExpression(Register);
2952 /// parseDirectiveCFIDefCfa
2953 /// ::= .cfi_def_cfa register, offset
2954 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2955 int64_t Register = 0;
2956 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2959 if (getLexer().isNot(AsmToken::Comma))
2960 return TokError("unexpected token in directive");
2964 if (parseAbsoluteExpression(Offset))
2967 getStreamer().EmitCFIDefCfa(Register, Offset);
2971 /// parseDirectiveCFIDefCfaOffset
2972 /// ::= .cfi_def_cfa_offset offset
2973 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2975 if (parseAbsoluteExpression(Offset))
2978 getStreamer().EmitCFIDefCfaOffset(Offset);
2982 /// parseDirectiveCFIRegister
2983 /// ::= .cfi_register register, register
2984 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2985 int64_t Register1 = 0;
2986 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2989 if (getLexer().isNot(AsmToken::Comma))
2990 return TokError("unexpected token in directive");
2993 int64_t Register2 = 0;
2994 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2997 getStreamer().EmitCFIRegister(Register1, Register2);
3001 /// parseDirectiveCFIWindowSave
3002 /// ::= .cfi_window_save
3003 bool AsmParser::parseDirectiveCFIWindowSave() {
3004 getStreamer().EmitCFIWindowSave();
3008 /// parseDirectiveCFIAdjustCfaOffset
3009 /// ::= .cfi_adjust_cfa_offset adjustment
3010 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3011 int64_t Adjustment = 0;
3012 if (parseAbsoluteExpression(Adjustment))
3015 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3019 /// parseDirectiveCFIDefCfaRegister
3020 /// ::= .cfi_def_cfa_register register
3021 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3022 int64_t Register = 0;
3023 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3026 getStreamer().EmitCFIDefCfaRegister(Register);
3030 /// parseDirectiveCFIOffset
3031 /// ::= .cfi_offset register, offset
3032 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3033 int64_t Register = 0;
3036 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3039 if (getLexer().isNot(AsmToken::Comma))
3040 return TokError("unexpected token in directive");
3043 if (parseAbsoluteExpression(Offset))
3046 getStreamer().EmitCFIOffset(Register, Offset);
3050 /// parseDirectiveCFIRelOffset
3051 /// ::= .cfi_rel_offset register, offset
3052 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3053 int64_t Register = 0;
3055 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3058 if (getLexer().isNot(AsmToken::Comma))
3059 return TokError("unexpected token in directive");
3063 if (parseAbsoluteExpression(Offset))
3066 getStreamer().EmitCFIRelOffset(Register, Offset);
3070 static bool isValidEncoding(int64_t Encoding) {
3071 if (Encoding & ~0xff)
3074 if (Encoding == dwarf::DW_EH_PE_omit)
3077 const unsigned Format = Encoding & 0xf;
3078 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3079 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3080 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3081 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3084 const unsigned Application = Encoding & 0x70;
3085 if (Application != dwarf::DW_EH_PE_absptr &&
3086 Application != dwarf::DW_EH_PE_pcrel)
3092 /// parseDirectiveCFIPersonalityOrLsda
3093 /// IsPersonality true for cfi_personality, false for cfi_lsda
3094 /// ::= .cfi_personality encoding, [symbol_name]
3095 /// ::= .cfi_lsda encoding, [symbol_name]
3096 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3097 int64_t Encoding = 0;
3098 if (parseAbsoluteExpression(Encoding))
3100 if (Encoding == dwarf::DW_EH_PE_omit)
3103 if (!isValidEncoding(Encoding))
3104 return TokError("unsupported encoding.");
3106 if (getLexer().isNot(AsmToken::Comma))
3107 return TokError("unexpected token in directive");
3111 if (parseIdentifier(Name))
3112 return TokError("expected identifier in directive");
3114 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3117 getStreamer().EmitCFIPersonality(Sym, Encoding);
3119 getStreamer().EmitCFILsda(Sym, Encoding);
3123 /// parseDirectiveCFIRememberState
3124 /// ::= .cfi_remember_state
3125 bool AsmParser::parseDirectiveCFIRememberState() {
3126 getStreamer().EmitCFIRememberState();
3130 /// parseDirectiveCFIRestoreState
3131 /// ::= .cfi_remember_state
3132 bool AsmParser::parseDirectiveCFIRestoreState() {
3133 getStreamer().EmitCFIRestoreState();
3137 /// parseDirectiveCFISameValue
3138 /// ::= .cfi_same_value register
3139 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3140 int64_t Register = 0;
3142 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3145 getStreamer().EmitCFISameValue(Register);
3149 /// parseDirectiveCFIRestore
3150 /// ::= .cfi_restore register
3151 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3152 int64_t Register = 0;
3153 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3156 getStreamer().EmitCFIRestore(Register);
3160 /// parseDirectiveCFIEscape
3161 /// ::= .cfi_escape expression[,...]
3162 bool AsmParser::parseDirectiveCFIEscape() {
3165 if (parseAbsoluteExpression(CurrValue))
3168 Values.push_back((uint8_t)CurrValue);
3170 while (getLexer().is(AsmToken::Comma)) {
3173 if (parseAbsoluteExpression(CurrValue))
3176 Values.push_back((uint8_t)CurrValue);
3179 getStreamer().EmitCFIEscape(Values);
3183 /// parseDirectiveCFISignalFrame
3184 /// ::= .cfi_signal_frame
3185 bool AsmParser::parseDirectiveCFISignalFrame() {
3186 if (getLexer().isNot(AsmToken::EndOfStatement))
3187 return Error(getLexer().getLoc(),
3188 "unexpected token in '.cfi_signal_frame'");
3190 getStreamer().EmitCFISignalFrame();
3194 /// parseDirectiveCFIUndefined
3195 /// ::= .cfi_undefined register
3196 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3197 int64_t Register = 0;
3199 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3202 getStreamer().EmitCFIUndefined(Register);
3206 /// parseDirectiveMacrosOnOff
3209 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3210 if (getLexer().isNot(AsmToken::EndOfStatement))
3211 return Error(getLexer().getLoc(),
3212 "unexpected token in '" + Directive + "' directive");
3214 setMacrosEnabled(Directive == ".macros_on");
3218 /// parseDirectiveMacro
3219 /// ::= .macro name[,] [parameters]
3220 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3222 if (parseIdentifier(Name))
3223 return TokError("expected identifier in '.macro' directive");
3225 if (getLexer().is(AsmToken::Comma))
3228 MCAsmMacroParameters Parameters;
3229 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3230 MCAsmMacroParameter Parameter;
3231 if (parseIdentifier(Parameter.Name))
3232 return TokError("expected identifier in '.macro' directive");
3234 if (Lexer.is(AsmToken::Colon)) {
3235 Lex(); // consume ':'
3238 StringRef Qualifier;
3240 QualLoc = Lexer.getLoc();
3241 if (parseIdentifier(Qualifier))
3242 return Error(QualLoc, "missing parameter qualifier for "
3243 "'" + Parameter.Name + "' in macro '" + Name + "'");
3245 if (Qualifier == "req")
3246 Parameter.Required = true;
3248 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3249 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3252 if (getLexer().is(AsmToken::Equal)) {
3257 ParamLoc = Lexer.getLoc();
3258 if (parseMacroArgument(Parameter.Value))
3261 if (Parameter.Required)
3262 Warning(ParamLoc, "pointless default value for required parameter "
3263 "'" + Parameter.Name + "' in macro '" + Name + "'");
3266 Parameters.push_back(Parameter);
3268 if (getLexer().is(AsmToken::Comma))
3272 // Eat the end of statement.
3275 AsmToken EndToken, StartToken = getTok();
3276 unsigned MacroDepth = 0;
3278 // Lex the macro definition.
3280 // Check whether we have reached the end of the file.
3281 if (getLexer().is(AsmToken::Eof))
3282 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3284 // Otherwise, check whether we have reach the .endmacro.
3285 if (getLexer().is(AsmToken::Identifier)) {
3286 if (getTok().getIdentifier() == ".endm" ||
3287 getTok().getIdentifier() == ".endmacro") {
3288 if (MacroDepth == 0) { // Outermost macro.
3289 EndToken = getTok();
3291 if (getLexer().isNot(AsmToken::EndOfStatement))
3292 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3296 // Otherwise we just found the end of an inner macro.
3299 } else if (getTok().getIdentifier() == ".macro") {
3300 // We allow nested macros. Those aren't instantiated until the outermost
3301 // macro is expanded so just ignore them for now.
3306 // Otherwise, scan til the end of the statement.
3307 eatToEndOfStatement();
3310 if (lookupMacro(Name)) {
3311 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3314 const char *BodyStart = StartToken.getLoc().getPointer();
3315 const char *BodyEnd = EndToken.getLoc().getPointer();
3316 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3317 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3318 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3322 /// checkForBadMacro
3324 /// With the support added for named parameters there may be code out there that
3325 /// is transitioning from positional parameters. In versions of gas that did
3326 /// not support named parameters they would be ignored on the macro definition.
3327 /// But to support both styles of parameters this is not possible so if a macro
3328 /// definition has named parameters but does not use them and has what appears
3329 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3330 /// warning that the positional parameter found in body which have no effect.
3331 /// Hoping the developer will either remove the named parameters from the macro
3332 /// definition so the positional parameters get used if that was what was
3333 /// intended or change the macro to use the named parameters. It is possible
3334 /// this warning will trigger when the none of the named parameters are used
3335 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3336 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3338 ArrayRef<MCAsmMacroParameter> Parameters) {
3339 // If this macro is not defined with named parameters the warning we are
3340 // checking for here doesn't apply.
3341 unsigned NParameters = Parameters.size();
3342 if (NParameters == 0)
3345 bool NamedParametersFound = false;
3346 bool PositionalParametersFound = false;
3348 // Look at the body of the macro for use of both the named parameters and what
3349 // are likely to be positional parameters. This is what expandMacro() is
3350 // doing when it finds the parameters in the body.
3351 while (!Body.empty()) {
3352 // Scan for the next possible parameter.
3353 std::size_t End = Body.size(), Pos = 0;
3354 for (; Pos != End; ++Pos) {
3355 // Check for a substitution or escape.
3356 // This macro is defined with parameters, look for \foo, \bar, etc.
3357 if (Body[Pos] == '\\' && Pos + 1 != End)
3360 // This macro should have parameters, but look for $0, $1, ..., $n too.
3361 if (Body[Pos] != '$' || Pos + 1 == End)
3363 char Next = Body[Pos + 1];
3364 if (Next == '$' || Next == 'n' ||
3365 isdigit(static_cast<unsigned char>(Next)))
3369 // Check if we reached the end.
3373 if (Body[Pos] == '$') {
3374 switch (Body[Pos + 1]) {
3379 // $n => number of arguments
3381 PositionalParametersFound = true;
3384 // $[0-9] => argument
3386 PositionalParametersFound = true;
3392 unsigned I = Pos + 1;
3393 while (isIdentifierChar(Body[I]) && I + 1 != End)
3396 const char *Begin = Body.data() + Pos + 1;
3397 StringRef Argument(Begin, I - (Pos + 1));
3399 for (; Index < NParameters; ++Index)
3400 if (Parameters[Index].Name == Argument)
3403 if (Index == NParameters) {
3404 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3410 NamedParametersFound = true;
3411 Pos += 1 + Argument.size();
3414 // Update the scan point.
3415 Body = Body.substr(Pos);
3418 if (!NamedParametersFound && PositionalParametersFound)
3419 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3420 "used in macro body, possible positional parameter "
3421 "found in body which will have no effect");
3424 /// parseDirectiveEndMacro
3427 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3428 if (getLexer().isNot(AsmToken::EndOfStatement))
3429 return TokError("unexpected token in '" + Directive + "' directive");
3431 // If we are inside a macro instantiation, terminate the current
3433 if (isInsideMacroInstantiation()) {
3438 // Otherwise, this .endmacro is a stray entry in the file; well formed
3439 // .endmacro directives are handled during the macro definition parsing.
3440 return TokError("unexpected '" + Directive + "' in file, "
3441 "no current macro definition");
3444 /// parseDirectivePurgeMacro
3446 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3448 if (parseIdentifier(Name))
3449 return TokError("expected identifier in '.purgem' directive");
3451 if (getLexer().isNot(AsmToken::EndOfStatement))
3452 return TokError("unexpected token in '.purgem' directive");
3454 if (!lookupMacro(Name))
3455 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3457 undefineMacro(Name);
3461 /// parseDirectiveBundleAlignMode
3462 /// ::= {.bundle_align_mode} expression
3463 bool AsmParser::parseDirectiveBundleAlignMode() {
3464 checkForValidSection();
3466 // Expect a single argument: an expression that evaluates to a constant
3467 // in the inclusive range 0-30.
3468 SMLoc ExprLoc = getLexer().getLoc();
3469 int64_t AlignSizePow2;
3470 if (parseAbsoluteExpression(AlignSizePow2))
3472 else if (getLexer().isNot(AsmToken::EndOfStatement))
3473 return TokError("unexpected token after expression in"
3474 " '.bundle_align_mode' directive");
3475 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3476 return Error(ExprLoc,
3477 "invalid bundle alignment size (expected between 0 and 30)");
3481 // Because of AlignSizePow2's verified range we can safely truncate it to
3483 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3487 /// parseDirectiveBundleLock
3488 /// ::= {.bundle_lock} [align_to_end]
3489 bool AsmParser::parseDirectiveBundleLock() {
3490 checkForValidSection();
3491 bool AlignToEnd = false;
3493 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3495 SMLoc Loc = getTok().getLoc();
3496 const char *kInvalidOptionError =
3497 "invalid option for '.bundle_lock' directive";
3499 if (parseIdentifier(Option))
3500 return Error(Loc, kInvalidOptionError);
3502 if (Option != "align_to_end")
3503 return Error(Loc, kInvalidOptionError);
3504 else if (getLexer().isNot(AsmToken::EndOfStatement))
3506 "unexpected token after '.bundle_lock' directive option");
3512 getStreamer().EmitBundleLock(AlignToEnd);
3516 /// parseDirectiveBundleLock
3517 /// ::= {.bundle_lock}
3518 bool AsmParser::parseDirectiveBundleUnlock() {
3519 checkForValidSection();
3521 if (getLexer().isNot(AsmToken::EndOfStatement))
3522 return TokError("unexpected token in '.bundle_unlock' directive");
3525 getStreamer().EmitBundleUnlock();
3529 /// parseDirectiveSpace
3530 /// ::= (.skip | .space) expression [ , expression ]
3531 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3532 checkForValidSection();
3535 if (parseAbsoluteExpression(NumBytes))
3538 int64_t FillExpr = 0;
3539 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3540 if (getLexer().isNot(AsmToken::Comma))
3541 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3544 if (parseAbsoluteExpression(FillExpr))
3547 if (getLexer().isNot(AsmToken::EndOfStatement))
3548 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3554 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3557 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3558 getStreamer().EmitFill(NumBytes, FillExpr);
3563 /// parseDirectiveLEB128
3564 /// ::= (.sleb128 | .uleb128) expression
3565 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3566 checkForValidSection();
3567 const MCExpr *Value;
3569 if (parseExpression(Value))
3572 if (getLexer().isNot(AsmToken::EndOfStatement))
3573 return TokError("unexpected token in directive");
3576 getStreamer().EmitSLEB128Value(Value);
3578 getStreamer().EmitULEB128Value(Value);
3583 /// parseDirectiveSymbolAttribute
3584 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3585 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3586 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3589 SMLoc Loc = getTok().getLoc();
3591 if (parseIdentifier(Name))
3592 return Error(Loc, "expected identifier in directive");
3594 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3596 // Assembler local symbols don't make any sense here. Complain loudly.
3597 if (Sym->isTemporary())
3598 return Error(Loc, "non-local symbol required in directive");
3600 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3601 return Error(Loc, "unable to emit symbol attribute");
3603 if (getLexer().is(AsmToken::EndOfStatement))
3606 if (getLexer().isNot(AsmToken::Comma))
3607 return TokError("unexpected token in directive");
3616 /// parseDirectiveComm
3617 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3618 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3619 checkForValidSection();
3621 SMLoc IDLoc = getLexer().getLoc();
3623 if (parseIdentifier(Name))
3624 return TokError("expected identifier in directive");
3626 // Handle the identifier as the key symbol.
3627 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3629 if (getLexer().isNot(AsmToken::Comma))
3630 return TokError("unexpected token in directive");
3634 SMLoc SizeLoc = getLexer().getLoc();
3635 if (parseAbsoluteExpression(Size))
3638 int64_t Pow2Alignment = 0;
3639 SMLoc Pow2AlignmentLoc;
3640 if (getLexer().is(AsmToken::Comma)) {
3642 Pow2AlignmentLoc = getLexer().getLoc();
3643 if (parseAbsoluteExpression(Pow2Alignment))
3646 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3647 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3648 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3650 // If this target takes alignments in bytes (not log) validate and convert.
3651 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3652 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3653 if (!isPowerOf2_64(Pow2Alignment))
3654 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3655 Pow2Alignment = Log2_64(Pow2Alignment);
3659 if (getLexer().isNot(AsmToken::EndOfStatement))
3660 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3664 // NOTE: a size of zero for a .comm should create a undefined symbol
3665 // but a size of .lcomm creates a bss symbol of size zero.
3667 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3668 "be less than zero");
3670 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3671 // may internally end up wanting an alignment in bytes.
3672 // FIXME: Diagnose overflow.
3673 if (Pow2Alignment < 0)
3674 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3675 "alignment, can't be less than zero");
3677 if (!Sym->isUndefined())
3678 return Error(IDLoc, "invalid symbol redefinition");
3680 // Create the Symbol as a common or local common with Size and Pow2Alignment
3682 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3686 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3690 /// parseDirectiveAbort
3691 /// ::= .abort [... message ...]
3692 bool AsmParser::parseDirectiveAbort() {
3693 // FIXME: Use loc from directive.
3694 SMLoc Loc = getLexer().getLoc();
3696 StringRef Str = parseStringToEndOfStatement();
3697 if (getLexer().isNot(AsmToken::EndOfStatement))
3698 return TokError("unexpected token in '.abort' directive");
3703 Error(Loc, ".abort detected. Assembly stopping.");
3705 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3706 // FIXME: Actually abort assembly here.
3711 /// parseDirectiveInclude
3712 /// ::= .include "filename"
3713 bool AsmParser::parseDirectiveInclude() {
3714 if (getLexer().isNot(AsmToken::String))
3715 return TokError("expected string in '.include' directive");
3717 // Allow the strings to have escaped octal character sequence.
3718 std::string Filename;
3719 if (parseEscapedString(Filename))
3721 SMLoc IncludeLoc = getLexer().getLoc();
3724 if (getLexer().isNot(AsmToken::EndOfStatement))
3725 return TokError("unexpected token in '.include' directive");
3727 // Attempt to switch the lexer to the included file before consuming the end
3728 // of statement to avoid losing it when we switch.
3729 if (enterIncludeFile(Filename)) {
3730 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3737 /// parseDirectiveIncbin
3738 /// ::= .incbin "filename"
3739 bool AsmParser::parseDirectiveIncbin() {
3740 if (getLexer().isNot(AsmToken::String))
3741 return TokError("expected string in '.incbin' directive");
3743 // Allow the strings to have escaped octal character sequence.
3744 std::string Filename;
3745 if (parseEscapedString(Filename))
3747 SMLoc IncbinLoc = getLexer().getLoc();
3750 if (getLexer().isNot(AsmToken::EndOfStatement))
3751 return TokError("unexpected token in '.incbin' directive");
3753 // Attempt to process the included file.
3754 if (processIncbinFile(Filename)) {
3755 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3762 /// parseDirectiveIf
3763 /// ::= .if expression
3764 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3765 TheCondStack.push_back(TheCondState);
3766 TheCondState.TheCond = AsmCond::IfCond;
3767 if (TheCondState.Ignore) {
3768 eatToEndOfStatement();
3771 if (parseAbsoluteExpression(ExprValue))
3774 if (getLexer().isNot(AsmToken::EndOfStatement))
3775 return TokError("unexpected token in '.if' directive");
3779 TheCondState.CondMet = ExprValue;
3780 TheCondState.Ignore = !TheCondState.CondMet;
3786 /// parseDirectiveIfb
3788 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3789 TheCondStack.push_back(TheCondState);
3790 TheCondState.TheCond = AsmCond::IfCond;
3792 if (TheCondState.Ignore) {
3793 eatToEndOfStatement();
3795 StringRef Str = parseStringToEndOfStatement();
3797 if (getLexer().isNot(AsmToken::EndOfStatement))
3798 return TokError("unexpected token in '.ifb' directive");
3802 TheCondState.CondMet = ExpectBlank == Str.empty();
3803 TheCondState.Ignore = !TheCondState.CondMet;
3809 /// parseDirectiveIfc
3810 /// ::= .ifc string1, string2
3811 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3812 TheCondStack.push_back(TheCondState);
3813 TheCondState.TheCond = AsmCond::IfCond;
3815 if (TheCondState.Ignore) {
3816 eatToEndOfStatement();
3818 StringRef Str1 = parseStringToComma();
3820 if (getLexer().isNot(AsmToken::Comma))
3821 return TokError("unexpected token in '.ifc' directive");
3825 StringRef Str2 = parseStringToEndOfStatement();
3827 if (getLexer().isNot(AsmToken::EndOfStatement))
3828 return TokError("unexpected token in '.ifc' directive");
3832 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3833 TheCondState.Ignore = !TheCondState.CondMet;
3839 /// parseDirectiveIfdef
3840 /// ::= .ifdef symbol
3841 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3843 TheCondStack.push_back(TheCondState);
3844 TheCondState.TheCond = AsmCond::IfCond;
3846 if (TheCondState.Ignore) {
3847 eatToEndOfStatement();
3849 if (parseIdentifier(Name))
3850 return TokError("expected identifier after '.ifdef'");
3854 MCSymbol *Sym = getContext().LookupSymbol(Name);
3857 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3859 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3860 TheCondState.Ignore = !TheCondState.CondMet;
3866 /// parseDirectiveElseIf
3867 /// ::= .elseif expression
3868 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3869 if (TheCondState.TheCond != AsmCond::IfCond &&
3870 TheCondState.TheCond != AsmCond::ElseIfCond)
3871 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3873 TheCondState.TheCond = AsmCond::ElseIfCond;
3875 bool LastIgnoreState = false;
3876 if (!TheCondStack.empty())
3877 LastIgnoreState = TheCondStack.back().Ignore;
3878 if (LastIgnoreState || TheCondState.CondMet) {
3879 TheCondState.Ignore = true;
3880 eatToEndOfStatement();
3883 if (parseAbsoluteExpression(ExprValue))
3886 if (getLexer().isNot(AsmToken::EndOfStatement))
3887 return TokError("unexpected token in '.elseif' directive");
3890 TheCondState.CondMet = ExprValue;
3891 TheCondState.Ignore = !TheCondState.CondMet;
3897 /// parseDirectiveElse
3899 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3900 if (getLexer().isNot(AsmToken::EndOfStatement))
3901 return TokError("unexpected token in '.else' directive");
3905 if (TheCondState.TheCond != AsmCond::IfCond &&
3906 TheCondState.TheCond != AsmCond::ElseIfCond)
3907 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3909 TheCondState.TheCond = AsmCond::ElseCond;
3910 bool LastIgnoreState = false;
3911 if (!TheCondStack.empty())
3912 LastIgnoreState = TheCondStack.back().Ignore;
3913 if (LastIgnoreState || TheCondState.CondMet)
3914 TheCondState.Ignore = true;
3916 TheCondState.Ignore = false;
3921 /// parseDirectiveEnd
3923 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
3924 if (getLexer().isNot(AsmToken::EndOfStatement))
3925 return TokError("unexpected token in '.end' directive");
3929 while (Lexer.isNot(AsmToken::Eof))
3935 /// parseDirectiveEndIf
3937 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
3938 if (getLexer().isNot(AsmToken::EndOfStatement))
3939 return TokError("unexpected token in '.endif' directive");
3943 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
3944 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3946 if (!TheCondStack.empty()) {
3947 TheCondState = TheCondStack.back();
3948 TheCondStack.pop_back();
3954 void AsmParser::initializeDirectiveKindMap() {
3955 DirectiveKindMap[".set"] = DK_SET;
3956 DirectiveKindMap[".equ"] = DK_EQU;
3957 DirectiveKindMap[".equiv"] = DK_EQUIV;
3958 DirectiveKindMap[".ascii"] = DK_ASCII;
3959 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3960 DirectiveKindMap[".string"] = DK_STRING;
3961 DirectiveKindMap[".byte"] = DK_BYTE;
3962 DirectiveKindMap[".short"] = DK_SHORT;
3963 DirectiveKindMap[".value"] = DK_VALUE;
3964 DirectiveKindMap[".2byte"] = DK_2BYTE;
3965 DirectiveKindMap[".long"] = DK_LONG;
3966 DirectiveKindMap[".int"] = DK_INT;
3967 DirectiveKindMap[".4byte"] = DK_4BYTE;
3968 DirectiveKindMap[".quad"] = DK_QUAD;
3969 DirectiveKindMap[".8byte"] = DK_8BYTE;
3970 DirectiveKindMap[".octa"] = DK_OCTA;
3971 DirectiveKindMap[".single"] = DK_SINGLE;
3972 DirectiveKindMap[".float"] = DK_FLOAT;
3973 DirectiveKindMap[".double"] = DK_DOUBLE;
3974 DirectiveKindMap[".align"] = DK_ALIGN;
3975 DirectiveKindMap[".align32"] = DK_ALIGN32;
3976 DirectiveKindMap[".balign"] = DK_BALIGN;
3977 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3978 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3979 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3980 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3981 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3982 DirectiveKindMap[".org"] = DK_ORG;
3983 DirectiveKindMap[".fill"] = DK_FILL;
3984 DirectiveKindMap[".zero"] = DK_ZERO;
3985 DirectiveKindMap[".extern"] = DK_EXTERN;
3986 DirectiveKindMap[".globl"] = DK_GLOBL;
3987 DirectiveKindMap[".global"] = DK_GLOBAL;
3988 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3989 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3990 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3991 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3992 DirectiveKindMap[".reference"] = DK_REFERENCE;
3993 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3994 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3995 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3996 DirectiveKindMap[".comm"] = DK_COMM;
3997 DirectiveKindMap[".common"] = DK_COMMON;
3998 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3999 DirectiveKindMap[".abort"] = DK_ABORT;
4000 DirectiveKindMap[".include"] = DK_INCLUDE;
4001 DirectiveKindMap[".incbin"] = DK_INCBIN;
4002 DirectiveKindMap[".code16"] = DK_CODE16;
4003 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4004 DirectiveKindMap[".rept"] = DK_REPT;
4005 DirectiveKindMap[".rep"] = DK_REPT;
4006 DirectiveKindMap[".irp"] = DK_IRP;
4007 DirectiveKindMap[".irpc"] = DK_IRPC;
4008 DirectiveKindMap[".endr"] = DK_ENDR;
4009 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4010 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4011 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4012 DirectiveKindMap[".if"] = DK_IF;
4013 DirectiveKindMap[".ifb"] = DK_IFB;
4014 DirectiveKindMap[".ifnb"] = DK_IFNB;
4015 DirectiveKindMap[".ifc"] = DK_IFC;
4016 DirectiveKindMap[".ifnc"] = DK_IFNC;
4017 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4018 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4019 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4020 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4021 DirectiveKindMap[".else"] = DK_ELSE;
4022 DirectiveKindMap[".end"] = DK_END;
4023 DirectiveKindMap[".endif"] = DK_ENDIF;
4024 DirectiveKindMap[".skip"] = DK_SKIP;
4025 DirectiveKindMap[".space"] = DK_SPACE;
4026 DirectiveKindMap[".file"] = DK_FILE;
4027 DirectiveKindMap[".line"] = DK_LINE;
4028 DirectiveKindMap[".loc"] = DK_LOC;
4029 DirectiveKindMap[".stabs"] = DK_STABS;
4030 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4031 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4032 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4033 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4034 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4035 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4036 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4037 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4038 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4039 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4040 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4041 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4042 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4043 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4044 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4045 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4046 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4047 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4048 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4049 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4050 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4051 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4052 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4053 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4054 DirectiveKindMap[".macro"] = DK_MACRO;
4055 DirectiveKindMap[".endm"] = DK_ENDM;
4056 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4057 DirectiveKindMap[".purgem"] = DK_PURGEM;
4060 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4061 AsmToken EndToken, StartToken = getTok();
4063 unsigned NestLevel = 0;
4065 // Check whether we have reached the end of the file.
4066 if (getLexer().is(AsmToken::Eof)) {
4067 Error(DirectiveLoc, "no matching '.endr' in definition");
4071 if (Lexer.is(AsmToken::Identifier) &&
4072 (getTok().getIdentifier() == ".rept")) {
4076 // Otherwise, check whether we have reached the .endr.
4077 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4078 if (NestLevel == 0) {
4079 EndToken = getTok();
4081 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4082 TokError("unexpected token in '.endr' directive");
4090 // Otherwise, scan till the end of the statement.
4091 eatToEndOfStatement();
4094 const char *BodyStart = StartToken.getLoc().getPointer();
4095 const char *BodyEnd = EndToken.getLoc().getPointer();
4096 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4098 // We Are Anonymous.
4099 MacroLikeBodies.push_back(MCAsmMacro(StringRef(), Body, None));
4100 return &MacroLikeBodies.back();
4103 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4104 raw_svector_ostream &OS) {
4107 MemoryBuffer *Instantiation =
4108 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4110 // Create the macro instantiation object and add to the current macro
4111 // instantiation stack.
4112 MacroInstantiation *MI = new MacroInstantiation(
4113 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
4114 ActiveMacros.push_back(MI);
4116 // Jump to the macro instantiation and prime the lexer.
4117 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
4118 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
4122 /// parseDirectiveRept
4123 /// ::= .rep | .rept count
4124 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4125 const MCExpr *CountExpr;
4126 SMLoc CountLoc = getTok().getLoc();
4127 if (parseExpression(CountExpr))
4131 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4132 eatToEndOfStatement();
4133 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4137 return Error(CountLoc, "Count is negative");
4139 if (Lexer.isNot(AsmToken::EndOfStatement))
4140 return TokError("unexpected token in '" + Dir + "' directive");
4142 // Eat the end of statement.
4145 // Lex the rept definition.
4146 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4150 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4151 // to hold the macro body with substitutions.
4152 SmallString<256> Buf;
4153 raw_svector_ostream OS(Buf);
4155 if (expandMacro(OS, M->Body, None, None, getTok().getLoc()))
4158 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4163 /// parseDirectiveIrp
4164 /// ::= .irp symbol,values
4165 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4166 MCAsmMacroParameter Parameter;
4168 if (parseIdentifier(Parameter.Name))
4169 return TokError("expected identifier in '.irp' directive");
4171 if (Lexer.isNot(AsmToken::Comma))
4172 return TokError("expected comma in '.irp' directive");
4176 MCAsmMacroArguments A;
4177 if (parseMacroArguments(0, A))
4180 // Eat the end of statement.
4183 // Lex the irp definition.
4184 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4188 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4189 // to hold the macro body with substitutions.
4190 SmallString<256> Buf;
4191 raw_svector_ostream OS(Buf);
4193 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4194 if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc()))
4198 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4203 /// parseDirectiveIrpc
4204 /// ::= .irpc symbol,values
4205 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4206 MCAsmMacroParameter Parameter;
4208 if (parseIdentifier(Parameter.Name))
4209 return TokError("expected identifier in '.irpc' directive");
4211 if (Lexer.isNot(AsmToken::Comma))
4212 return TokError("expected comma in '.irpc' directive");
4216 MCAsmMacroArguments A;
4217 if (parseMacroArguments(0, A))
4220 if (A.size() != 1 || A.front().size() != 1)
4221 return TokError("unexpected token in '.irpc' directive");
4223 // Eat the end of statement.
4226 // Lex the irpc definition.
4227 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4231 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4232 // to hold the macro body with substitutions.
4233 SmallString<256> Buf;
4234 raw_svector_ostream OS(Buf);
4236 StringRef Values = A.front().front().getString();
4237 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4238 MCAsmMacroArgument Arg;
4239 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4241 if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc()))
4245 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4250 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4251 if (ActiveMacros.empty())
4252 return TokError("unmatched '.endr' directive");
4254 // The only .repl that should get here are the ones created by
4255 // instantiateMacroLikeBody.
4256 assert(getLexer().is(AsmToken::EndOfStatement));
4262 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4264 const MCExpr *Value;
4265 SMLoc ExprLoc = getLexer().getLoc();
4266 if (parseExpression(Value))
4268 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4270 return Error(ExprLoc, "unexpected expression in _emit");
4271 uint64_t IntValue = MCE->getValue();
4272 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4273 return Error(ExprLoc, "literal value out of range for directive");
4275 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4279 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4280 const MCExpr *Value;
4281 SMLoc ExprLoc = getLexer().getLoc();
4282 if (parseExpression(Value))
4284 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4286 return Error(ExprLoc, "unexpected expression in align");
4287 uint64_t IntValue = MCE->getValue();
4288 if (!isPowerOf2_64(IntValue))
4289 return Error(ExprLoc, "literal value not a power of two greater then zero");
4291 Info.AsmRewrites->push_back(
4292 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4296 // We are comparing pointers, but the pointers are relative to a single string.
4297 // Thus, this should always be deterministic.
4298 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4299 const AsmRewrite *AsmRewriteB) {
4300 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4302 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4305 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4306 // rewrite to the same location. Make sure the SizeDirective rewrite is
4307 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4308 // ensures the sort algorithm is stable.
4309 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4310 AsmRewritePrecedence[AsmRewriteB->Kind])
4313 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4314 AsmRewritePrecedence[AsmRewriteB->Kind])
4316 llvm_unreachable("Unstable rewrite sort.");
4319 bool AsmParser::parseMSInlineAsm(
4320 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4321 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4322 SmallVectorImpl<std::string> &Constraints,
4323 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4324 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4325 SmallVector<void *, 4> InputDecls;
4326 SmallVector<void *, 4> OutputDecls;
4327 SmallVector<bool, 4> InputDeclsAddressOf;
4328 SmallVector<bool, 4> OutputDeclsAddressOf;
4329 SmallVector<std::string, 4> InputConstraints;
4330 SmallVector<std::string, 4> OutputConstraints;
4331 SmallVector<unsigned, 4> ClobberRegs;
4333 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4338 // While we have input, parse each statement.
4339 unsigned InputIdx = 0;
4340 unsigned OutputIdx = 0;
4341 while (getLexer().isNot(AsmToken::Eof)) {
4342 ParseStatementInfo Info(&AsmStrRewrites);
4343 if (parseStatement(Info))
4346 if (Info.ParseError)
4349 if (Info.Opcode == ~0U)
4352 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4354 // Build the list of clobbers, outputs and inputs.
4355 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4356 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4359 if (Operand->isImm())
4362 // Register operand.
4363 if (Operand->isReg() && !Operand->needAddressOf()) {
4364 unsigned NumDefs = Desc.getNumDefs();
4366 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4367 ClobberRegs.push_back(Operand->getReg());
4371 // Expr/Input or Output.
4372 StringRef SymName = Operand->getSymName();
4373 if (SymName.empty())
4376 void *OpDecl = Operand->getOpDecl();
4380 bool isOutput = (i == 1) && Desc.mayStore();
4381 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4384 OutputDecls.push_back(OpDecl);
4385 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4386 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4387 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4389 InputDecls.push_back(OpDecl);
4390 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4391 InputConstraints.push_back(Operand->getConstraint().str());
4392 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4396 // Consider implicit defs to be clobbers. Think of cpuid and push.
4397 const uint16_t *ImpDefs = Desc.getImplicitDefs();
4398 for (unsigned I = 0, E = Desc.getNumImplicitDefs(); I != E; ++I)
4399 ClobberRegs.push_back(ImpDefs[I]);
4402 // Set the number of Outputs and Inputs.
4403 NumOutputs = OutputDecls.size();
4404 NumInputs = InputDecls.size();
4406 // Set the unique clobbers.
4407 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4408 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4410 Clobbers.assign(ClobberRegs.size(), std::string());
4411 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4412 raw_string_ostream OS(Clobbers[I]);
4413 IP->printRegName(OS, ClobberRegs[I]);
4416 // Merge the various outputs and inputs. Output are expected first.
4417 if (NumOutputs || NumInputs) {
4418 unsigned NumExprs = NumOutputs + NumInputs;
4419 OpDecls.resize(NumExprs);
4420 Constraints.resize(NumExprs);
4421 for (unsigned i = 0; i < NumOutputs; ++i) {
4422 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4423 Constraints[i] = OutputConstraints[i];
4425 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4426 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4427 Constraints[j] = InputConstraints[i];
4431 // Build the IR assembly string.
4432 std::string AsmStringIR;
4433 raw_string_ostream OS(AsmStringIR);
4434 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4435 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4436 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4437 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4438 E = AsmStrRewrites.end();
4440 AsmRewriteKind Kind = (*I).Kind;
4441 if (Kind == AOK_Delete)
4444 const char *Loc = (*I).Loc.getPointer();
4445 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4447 // Emit everything up to the immediate/expression.
4448 unsigned Len = Loc - AsmStart;
4450 OS << StringRef(AsmStart, Len);
4452 // Skip the original expression.
4453 if (Kind == AOK_Skip) {
4454 AsmStart = Loc + (*I).Len;
4458 unsigned AdditionalSkip = 0;
4459 // Rewrite expressions in $N notation.
4464 OS << "$$" << (*I).Val;
4470 OS << '$' << InputIdx++;
4473 OS << '$' << OutputIdx++;
4475 case AOK_SizeDirective:
4478 case 8: OS << "byte ptr "; break;
4479 case 16: OS << "word ptr "; break;
4480 case 32: OS << "dword ptr "; break;
4481 case 64: OS << "qword ptr "; break;
4482 case 80: OS << "xword ptr "; break;
4483 case 128: OS << "xmmword ptr "; break;
4484 case 256: OS << "ymmword ptr "; break;
4491 unsigned Val = (*I).Val;
4492 OS << ".align " << Val;
4494 // Skip the original immediate.
4495 assert(Val < 10 && "Expected alignment less then 2^10.");
4496 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4499 case AOK_DotOperator:
4504 // Skip the original expression.
4505 AsmStart = Loc + (*I).Len + AdditionalSkip;
4508 // Emit the remainder of the asm string.
4509 if (AsmStart != AsmEnd)
4510 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4512 AsmString = OS.str();
4516 /// \brief Create an MCAsmParser instance.
4517 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4518 MCStreamer &Out, const MCAsmInfo &MAI) {
4519 return new AsmParser(SM, C, Out, MAI);