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 return Error(SMLoc::getFromPointer(Split.second.begin()),
837 "invalid variant '" + Split.second + "'");
841 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
843 // If this is an absolute variable reference, substitute it now to preserve
844 // semantics in the face of reassignment.
845 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
847 return Error(EndLoc, "unexpected modifier on variable reference");
849 Res = Sym->getVariableValue();
853 // Otherwise create a symbol ref.
854 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
857 case AsmToken::BigNum:
858 return TokError("literal value out of range for directive");
859 case AsmToken::Integer: {
860 SMLoc Loc = getTok().getLoc();
861 int64_t IntVal = getTok().getIntVal();
862 Res = MCConstantExpr::Create(IntVal, getContext());
863 EndLoc = Lexer.getTok().getEndLoc();
865 // Look for 'b' or 'f' following an Integer as a directional label
866 if (Lexer.getKind() == AsmToken::Identifier) {
867 StringRef IDVal = getTok().getString();
868 // Lookup the symbol variant if used.
869 std::pair<StringRef, StringRef> Split = IDVal.split('@');
870 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
871 if (Split.first.size() != IDVal.size()) {
872 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
873 if (Variant == MCSymbolRefExpr::VK_Invalid) {
874 Variant = MCSymbolRefExpr::VK_None;
875 return TokError("invalid variant '" + Split.second + "'");
879 if (IDVal == "f" || IDVal == "b") {
881 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "f" ? 1 : 0);
882 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
883 if (IDVal == "b" && Sym->isUndefined())
884 return Error(Loc, "invalid reference to undefined symbol");
885 EndLoc = Lexer.getTok().getEndLoc();
886 Lex(); // Eat identifier.
891 case AsmToken::Real: {
892 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
893 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
894 Res = MCConstantExpr::Create(IntVal, getContext());
895 EndLoc = Lexer.getTok().getEndLoc();
899 case AsmToken::Dot: {
900 // This is a '.' reference, which references the current PC. Emit a
901 // temporary label to the streamer and refer to it.
902 MCSymbol *Sym = Ctx.CreateTempSymbol();
904 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
905 EndLoc = Lexer.getTok().getEndLoc();
906 Lex(); // Eat identifier.
909 case AsmToken::LParen:
910 Lex(); // Eat the '('.
911 return parseParenExpr(Res, EndLoc);
912 case AsmToken::LBrac:
913 if (!PlatformParser->HasBracketExpressions())
914 return TokError("brackets expression not supported on this target");
915 Lex(); // Eat the '['.
916 return parseBracketExpr(Res, EndLoc);
917 case AsmToken::Minus:
918 Lex(); // Eat the operator.
919 if (parsePrimaryExpr(Res, EndLoc))
921 Res = MCUnaryExpr::CreateMinus(Res, getContext());
924 Lex(); // Eat the operator.
925 if (parsePrimaryExpr(Res, EndLoc))
927 Res = MCUnaryExpr::CreatePlus(Res, getContext());
929 case AsmToken::Tilde:
930 Lex(); // Eat the operator.
931 if (parsePrimaryExpr(Res, EndLoc))
933 Res = MCUnaryExpr::CreateNot(Res, getContext());
938 bool AsmParser::parseExpression(const MCExpr *&Res) {
940 return parseExpression(Res, EndLoc);
944 AsmParser::applyModifierToExpr(const MCExpr *E,
945 MCSymbolRefExpr::VariantKind Variant) {
946 // Ask the target implementation about this expression first.
947 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
950 // Recurse over the given expression, rebuilding it to apply the given variant
951 // if there is exactly one symbol.
952 switch (E->getKind()) {
954 case MCExpr::Constant:
957 case MCExpr::SymbolRef: {
958 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
960 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
961 TokError("invalid variant on expression '" + getTok().getIdentifier() +
962 "' (already modified)");
966 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
969 case MCExpr::Unary: {
970 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
971 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
974 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
977 case MCExpr::Binary: {
978 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
979 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
980 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
990 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
994 llvm_unreachable("Invalid expression kind!");
997 /// \brief Parse an expression and return it.
999 /// expr ::= expr &&,|| expr -> lowest.
1000 /// expr ::= expr |,^,&,! expr
1001 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1002 /// expr ::= expr <<,>> expr
1003 /// expr ::= expr +,- expr
1004 /// expr ::= expr *,/,% expr -> highest.
1005 /// expr ::= primaryexpr
1007 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1008 // Parse the expression.
1010 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1013 // As a special case, we support 'a op b @ modifier' by rewriting the
1014 // expression to include the modifier. This is inefficient, but in general we
1015 // expect users to use 'a@modifier op b'.
1016 if (Lexer.getKind() == AsmToken::At) {
1019 if (Lexer.isNot(AsmToken::Identifier))
1020 return TokError("unexpected symbol modifier following '@'");
1022 MCSymbolRefExpr::VariantKind Variant =
1023 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1024 if (Variant == MCSymbolRefExpr::VK_Invalid)
1025 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1027 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1029 return TokError("invalid modifier '" + getTok().getIdentifier() +
1030 "' (no symbols present)");
1037 // Try to constant fold it up front, if possible.
1039 if (Res->EvaluateAsAbsolute(Value))
1040 Res = MCConstantExpr::Create(Value, getContext());
1045 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1047 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1050 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1053 SMLoc StartLoc = Lexer.getLoc();
1054 if (parseExpression(Expr))
1057 if (!Expr->EvaluateAsAbsolute(Res))
1058 return Error(StartLoc, "expected absolute expression");
1063 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1064 MCBinaryExpr::Opcode &Kind) {
1067 return 0; // not a binop.
1069 // Lowest Precedence: &&, ||
1070 case AsmToken::AmpAmp:
1071 Kind = MCBinaryExpr::LAnd;
1073 case AsmToken::PipePipe:
1074 Kind = MCBinaryExpr::LOr;
1077 // Low Precedence: |, &, ^
1079 // FIXME: gas seems to support '!' as an infix operator?
1080 case AsmToken::Pipe:
1081 Kind = MCBinaryExpr::Or;
1083 case AsmToken::Caret:
1084 Kind = MCBinaryExpr::Xor;
1087 Kind = MCBinaryExpr::And;
1090 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1091 case AsmToken::EqualEqual:
1092 Kind = MCBinaryExpr::EQ;
1094 case AsmToken::ExclaimEqual:
1095 case AsmToken::LessGreater:
1096 Kind = MCBinaryExpr::NE;
1098 case AsmToken::Less:
1099 Kind = MCBinaryExpr::LT;
1101 case AsmToken::LessEqual:
1102 Kind = MCBinaryExpr::LTE;
1104 case AsmToken::Greater:
1105 Kind = MCBinaryExpr::GT;
1107 case AsmToken::GreaterEqual:
1108 Kind = MCBinaryExpr::GTE;
1111 // Intermediate Precedence: <<, >>
1112 case AsmToken::LessLess:
1113 Kind = MCBinaryExpr::Shl;
1115 case AsmToken::GreaterGreater:
1116 Kind = MCBinaryExpr::Shr;
1119 // High Intermediate Precedence: +, -
1120 case AsmToken::Plus:
1121 Kind = MCBinaryExpr::Add;
1123 case AsmToken::Minus:
1124 Kind = MCBinaryExpr::Sub;
1127 // Highest Precedence: *, /, %
1128 case AsmToken::Star:
1129 Kind = MCBinaryExpr::Mul;
1131 case AsmToken::Slash:
1132 Kind = MCBinaryExpr::Div;
1134 case AsmToken::Percent:
1135 Kind = MCBinaryExpr::Mod;
1140 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1141 /// Res contains the LHS of the expression on input.
1142 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1145 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1146 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1148 // If the next token is lower precedence than we are allowed to eat, return
1149 // successfully with what we ate already.
1150 if (TokPrec < Precedence)
1155 // Eat the next primary expression.
1157 if (parsePrimaryExpr(RHS, EndLoc))
1160 // If BinOp binds less tightly with RHS than the operator after RHS, let
1161 // the pending operator take RHS as its LHS.
1162 MCBinaryExpr::Opcode Dummy;
1163 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1164 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1167 // Merge LHS and RHS according to operator.
1168 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1173 /// ::= EndOfStatement
1174 /// ::= Label* Directive ...Operands... EndOfStatement
1175 /// ::= Label* Identifier OperandList* EndOfStatement
1176 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1177 if (Lexer.is(AsmToken::EndOfStatement)) {
1183 // Statements always start with an identifier or are a full line comment.
1184 AsmToken ID = getTok();
1185 SMLoc IDLoc = ID.getLoc();
1187 int64_t LocalLabelVal = -1;
1188 // A full line comment is a '#' as the first token.
1189 if (Lexer.is(AsmToken::Hash))
1190 return parseCppHashLineFilenameComment(IDLoc);
1192 // Allow an integer followed by a ':' as a directional local label.
1193 if (Lexer.is(AsmToken::Integer)) {
1194 LocalLabelVal = getTok().getIntVal();
1195 if (LocalLabelVal < 0) {
1196 if (!TheCondState.Ignore)
1197 return TokError("unexpected token at start of statement");
1200 IDVal = getTok().getString();
1201 Lex(); // Consume the integer token to be used as an identifier token.
1202 if (Lexer.getKind() != AsmToken::Colon) {
1203 if (!TheCondState.Ignore)
1204 return TokError("unexpected token at start of statement");
1207 } else if (Lexer.is(AsmToken::Dot)) {
1208 // Treat '.' as a valid identifier in this context.
1211 } else if (parseIdentifier(IDVal)) {
1212 if (!TheCondState.Ignore)
1213 return TokError("unexpected token at start of statement");
1217 // Handle conditional assembly here before checking for skipping. We
1218 // have to do this so that .endif isn't skipped in a ".if 0" block for
1220 StringMap<DirectiveKind>::const_iterator DirKindIt =
1221 DirectiveKindMap.find(IDVal);
1222 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1224 : DirKindIt->getValue();
1229 return parseDirectiveIf(IDLoc);
1231 return parseDirectiveIfb(IDLoc, true);
1233 return parseDirectiveIfb(IDLoc, false);
1235 return parseDirectiveIfc(IDLoc, true);
1237 return parseDirectiveIfc(IDLoc, false);
1239 return parseDirectiveIfdef(IDLoc, true);
1242 return parseDirectiveIfdef(IDLoc, false);
1244 return parseDirectiveElseIf(IDLoc);
1246 return parseDirectiveElse(IDLoc);
1248 return parseDirectiveEndIf(IDLoc);
1251 // Ignore the statement if in the middle of inactive conditional
1253 if (TheCondState.Ignore) {
1254 eatToEndOfStatement();
1258 // FIXME: Recurse on local labels?
1260 // See what kind of statement we have.
1261 switch (Lexer.getKind()) {
1262 case AsmToken::Colon: {
1263 checkForValidSection();
1265 // identifier ':' -> Label.
1268 // Diagnose attempt to use '.' as a label.
1270 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1272 // Diagnose attempt to use a variable as a label.
1274 // FIXME: Diagnostics. Note the location of the definition as a label.
1275 // FIXME: This doesn't diagnose assignment to a symbol which has been
1276 // implicitly marked as external.
1278 if (LocalLabelVal == -1)
1279 Sym = getContext().GetOrCreateSymbol(IDVal);
1281 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1282 if (!Sym->isUndefined() || Sym->isVariable())
1283 return Error(IDLoc, "invalid symbol redefinition");
1286 if (!ParsingInlineAsm)
1289 // If we are generating dwarf for assembly source files then gather the
1290 // info to make a dwarf label entry for this label if needed.
1291 if (getContext().getGenDwarfForAssembly())
1292 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1295 getTargetParser().onLabelParsed(Sym);
1297 // Consume any end of statement token, if present, to avoid spurious
1298 // AddBlankLine calls().
1299 if (Lexer.is(AsmToken::EndOfStatement)) {
1301 if (Lexer.is(AsmToken::Eof))
1308 case AsmToken::Equal:
1309 // identifier '=' ... -> assignment statement
1312 return parseAssignment(IDVal, true);
1314 default: // Normal instruction or directive.
1318 // If macros are enabled, check to see if this is a macro instantiation.
1319 if (areMacrosEnabled())
1320 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1321 return handleMacroEntry(M, IDLoc);
1324 // Otherwise, we have a normal instruction or directive.
1326 // Directives start with "."
1327 if (IDVal[0] == '.' && IDVal != ".") {
1328 // There are several entities interested in parsing directives:
1330 // 1. The target-specific assembly parser. Some directives are target
1331 // specific or may potentially behave differently on certain targets.
1332 // 2. Asm parser extensions. For example, platform-specific parsers
1333 // (like the ELF parser) register themselves as extensions.
1334 // 3. The generic directive parser implemented by this class. These are
1335 // all the directives that behave in a target and platform independent
1336 // manner, or at least have a default behavior that's shared between
1337 // all targets and platforms.
1339 // First query the target-specific parser. It will return 'true' if it
1340 // isn't interested in this directive.
1341 if (!getTargetParser().ParseDirective(ID))
1344 // Next, check the extension directive map to see if any extension has
1345 // registered itself to parse this directive.
1346 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1347 ExtensionDirectiveMap.lookup(IDVal);
1349 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1351 // Finally, if no one else is interested in this directive, it must be
1352 // generic and familiar to this class.
1358 return parseDirectiveSet(IDVal, true);
1360 return parseDirectiveSet(IDVal, false);
1362 return parseDirectiveAscii(IDVal, false);
1365 return parseDirectiveAscii(IDVal, true);
1367 return parseDirectiveValue(1);
1371 return parseDirectiveValue(2);
1375 return parseDirectiveValue(4);
1378 return parseDirectiveValue(8);
1380 return parseDirectiveOctaValue();
1383 return parseDirectiveRealValue(APFloat::IEEEsingle);
1385 return parseDirectiveRealValue(APFloat::IEEEdouble);
1387 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1388 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1391 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1392 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1395 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1397 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1399 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1401 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1403 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1405 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1407 return parseDirectiveOrg();
1409 return parseDirectiveFill();
1411 return parseDirectiveZero();
1413 eatToEndOfStatement(); // .extern is the default, ignore it.
1417 return parseDirectiveSymbolAttribute(MCSA_Global);
1418 case DK_LAZY_REFERENCE:
1419 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1420 case DK_NO_DEAD_STRIP:
1421 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1422 case DK_SYMBOL_RESOLVER:
1423 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1424 case DK_PRIVATE_EXTERN:
1425 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1427 return parseDirectiveSymbolAttribute(MCSA_Reference);
1428 case DK_WEAK_DEFINITION:
1429 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1430 case DK_WEAK_REFERENCE:
1431 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1432 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1433 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1436 return parseDirectiveComm(/*IsLocal=*/false);
1438 return parseDirectiveComm(/*IsLocal=*/true);
1440 return parseDirectiveAbort();
1442 return parseDirectiveInclude();
1444 return parseDirectiveIncbin();
1447 return TokError(Twine(IDVal) + " not supported yet");
1449 return parseDirectiveRept(IDLoc, IDVal);
1451 return parseDirectiveIrp(IDLoc);
1453 return parseDirectiveIrpc(IDLoc);
1455 return parseDirectiveEndr(IDLoc);
1456 case DK_BUNDLE_ALIGN_MODE:
1457 return parseDirectiveBundleAlignMode();
1458 case DK_BUNDLE_LOCK:
1459 return parseDirectiveBundleLock();
1460 case DK_BUNDLE_UNLOCK:
1461 return parseDirectiveBundleUnlock();
1463 return parseDirectiveLEB128(true);
1465 return parseDirectiveLEB128(false);
1468 return parseDirectiveSpace(IDVal);
1470 return parseDirectiveFile(IDLoc);
1472 return parseDirectiveLine();
1474 return parseDirectiveLoc();
1476 return parseDirectiveStabs();
1477 case DK_CFI_SECTIONS:
1478 return parseDirectiveCFISections();
1479 case DK_CFI_STARTPROC:
1480 return parseDirectiveCFIStartProc();
1481 case DK_CFI_ENDPROC:
1482 return parseDirectiveCFIEndProc();
1483 case DK_CFI_DEF_CFA:
1484 return parseDirectiveCFIDefCfa(IDLoc);
1485 case DK_CFI_DEF_CFA_OFFSET:
1486 return parseDirectiveCFIDefCfaOffset();
1487 case DK_CFI_ADJUST_CFA_OFFSET:
1488 return parseDirectiveCFIAdjustCfaOffset();
1489 case DK_CFI_DEF_CFA_REGISTER:
1490 return parseDirectiveCFIDefCfaRegister(IDLoc);
1492 return parseDirectiveCFIOffset(IDLoc);
1493 case DK_CFI_REL_OFFSET:
1494 return parseDirectiveCFIRelOffset(IDLoc);
1495 case DK_CFI_PERSONALITY:
1496 return parseDirectiveCFIPersonalityOrLsda(true);
1498 return parseDirectiveCFIPersonalityOrLsda(false);
1499 case DK_CFI_REMEMBER_STATE:
1500 return parseDirectiveCFIRememberState();
1501 case DK_CFI_RESTORE_STATE:
1502 return parseDirectiveCFIRestoreState();
1503 case DK_CFI_SAME_VALUE:
1504 return parseDirectiveCFISameValue(IDLoc);
1505 case DK_CFI_RESTORE:
1506 return parseDirectiveCFIRestore(IDLoc);
1508 return parseDirectiveCFIEscape();
1509 case DK_CFI_SIGNAL_FRAME:
1510 return parseDirectiveCFISignalFrame();
1511 case DK_CFI_UNDEFINED:
1512 return parseDirectiveCFIUndefined(IDLoc);
1513 case DK_CFI_REGISTER:
1514 return parseDirectiveCFIRegister(IDLoc);
1515 case DK_CFI_WINDOW_SAVE:
1516 return parseDirectiveCFIWindowSave();
1519 return parseDirectiveMacrosOnOff(IDVal);
1521 return parseDirectiveMacro(IDLoc);
1524 return parseDirectiveEndMacro(IDVal);
1526 return parseDirectivePurgeMacro(IDLoc);
1528 return parseDirectiveEnd(IDLoc);
1531 return Error(IDLoc, "unknown directive");
1534 // __asm _emit or __asm __emit
1535 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1536 IDVal == "_EMIT" || IDVal == "__EMIT"))
1537 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1540 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1541 return parseDirectiveMSAlign(IDLoc, Info);
1543 checkForValidSection();
1545 // Canonicalize the opcode to lower case.
1546 std::string OpcodeStr = IDVal.lower();
1547 ParseInstructionInfo IInfo(Info.AsmRewrites);
1548 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1549 Info.ParsedOperands);
1550 Info.ParseError = HadError;
1552 // Dump the parsed representation, if requested.
1553 if (getShowParsedOperands()) {
1554 SmallString<256> Str;
1555 raw_svector_ostream OS(Str);
1556 OS << "parsed instruction: [";
1557 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1560 Info.ParsedOperands[i]->print(OS);
1564 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1567 // If we are generating dwarf for assembly source files and the current
1568 // section is the initial text section then generate a .loc directive for
1570 if (!HadError && getContext().getGenDwarfForAssembly() &&
1571 getContext().getGenDwarfSection() ==
1572 getStreamer().getCurrentSection().first) {
1574 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1576 // If we previously parsed a cpp hash file line comment then make sure the
1577 // current Dwarf File is for the CppHashFilename if not then emit the
1578 // Dwarf File table for it and adjust the line number for the .loc.
1579 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
1580 getContext().getMCDwarfFiles();
1581 if (CppHashFilename.size() != 0) {
1582 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1584 getStreamer().EmitDwarfFileDirective(
1585 getContext().nextGenDwarfFileNumber(), StringRef(),
1588 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1589 // cache with the different Loc from the call above we save the last
1590 // info we queried here with SrcMgr.FindLineNumber().
1591 unsigned CppHashLocLineNo;
1592 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1593 CppHashLocLineNo = LastQueryLine;
1595 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1596 LastQueryLine = CppHashLocLineNo;
1597 LastQueryIDLoc = CppHashLoc;
1598 LastQueryBuffer = CppHashBuf;
1600 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1603 getStreamer().EmitDwarfLocDirective(
1604 getContext().getGenDwarfFileNumber(), Line, 0,
1605 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1609 // If parsing succeeded, match the instruction.
1612 HadError = getTargetParser().MatchAndEmitInstruction(
1613 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
1617 // Don't skip the rest of the line, the instruction parser is responsible for
1622 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1623 /// since they may not be able to be tokenized to get to the end of line token.
1624 void AsmParser::eatToEndOfLine() {
1625 if (!Lexer.is(AsmToken::EndOfStatement))
1626 Lexer.LexUntilEndOfLine();
1631 /// parseCppHashLineFilenameComment as this:
1632 /// ::= # number "filename"
1633 /// or just as a full line comment if it doesn't have a number and a string.
1634 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1635 Lex(); // Eat the hash token.
1637 if (getLexer().isNot(AsmToken::Integer)) {
1638 // Consume the line since in cases it is not a well-formed line directive,
1639 // as if were simply a full line comment.
1644 int64_t LineNumber = getTok().getIntVal();
1647 if (getLexer().isNot(AsmToken::String)) {
1652 StringRef Filename = getTok().getString();
1653 // Get rid of the enclosing quotes.
1654 Filename = Filename.substr(1, Filename.size() - 2);
1656 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1658 CppHashFilename = Filename;
1659 CppHashLineNumber = LineNumber;
1660 CppHashBuf = CurBuffer;
1662 // Ignore any trailing characters, they're just comment.
1667 /// \brief will use the last parsed cpp hash line filename comment
1668 /// for the Filename and LineNo if any in the diagnostic.
1669 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1670 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1671 raw_ostream &OS = errs();
1673 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1674 const SMLoc &DiagLoc = Diag.getLoc();
1675 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1676 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1678 // Like SourceMgr::printMessage() we need to print the include stack if any
1679 // before printing the message.
1680 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1681 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1682 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1683 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1686 // If we have not parsed a cpp hash line filename comment or the source
1687 // manager changed or buffer changed (like in a nested include) then just
1688 // print the normal diagnostic using its Filename and LineNo.
1689 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1690 DiagBuf != CppHashBuf) {
1691 if (Parser->SavedDiagHandler)
1692 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1698 // Use the CppHashFilename and calculate a line number based on the
1699 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1701 const std::string &Filename = Parser->CppHashFilename;
1703 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1704 int CppHashLocLineNo =
1705 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1707 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1709 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1710 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1711 Diag.getLineContents(), Diag.getRanges());
1713 if (Parser->SavedDiagHandler)
1714 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1716 NewDiag.print(0, OS);
1719 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1720 // difference being that that function accepts '@' as part of identifiers and
1721 // we can't do that. AsmLexer.cpp should probably be changed to handle
1722 // '@' as a special case when needed.
1723 static bool isIdentifierChar(char c) {
1724 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1728 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1729 ArrayRef<MCAsmMacroParameter> Parameters,
1730 ArrayRef<MCAsmMacroArgument> A, const SMLoc &L) {
1731 unsigned NParameters = Parameters.size();
1732 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1733 return Error(L, "Wrong number of arguments");
1735 // A macro without parameters is handled differently on Darwin:
1736 // gas accepts no arguments and does no substitutions
1737 while (!Body.empty()) {
1738 // Scan for the next substitution.
1739 std::size_t End = Body.size(), Pos = 0;
1740 for (; Pos != End; ++Pos) {
1741 // Check for a substitution or escape.
1742 if (IsDarwin && !NParameters) {
1743 // This macro has no parameters, look for $0, $1, etc.
1744 if (Body[Pos] != '$' || Pos + 1 == End)
1747 char Next = Body[Pos + 1];
1748 if (Next == '$' || Next == 'n' ||
1749 isdigit(static_cast<unsigned char>(Next)))
1752 // This macro has parameters, look for \foo, \bar, etc.
1753 if (Body[Pos] == '\\' && Pos + 1 != End)
1759 OS << Body.slice(0, Pos);
1761 // Check if we reached the end.
1765 if (IsDarwin && !NParameters) {
1766 switch (Body[Pos + 1]) {
1772 // $n => number of arguments
1777 // $[0-9] => argument
1779 // Missing arguments are ignored.
1780 unsigned Index = Body[Pos + 1] - '0';
1781 if (Index >= A.size())
1784 // Otherwise substitute with the token values, with spaces eliminated.
1785 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1786 ie = A[Index].end();
1788 OS << it->getString();
1794 unsigned I = Pos + 1;
1795 while (isIdentifierChar(Body[I]) && I + 1 != End)
1798 const char *Begin = Body.data() + Pos + 1;
1799 StringRef Argument(Begin, I - (Pos + 1));
1801 for (; Index < NParameters; ++Index)
1802 if (Parameters[Index].Name == Argument)
1805 if (Index == NParameters) {
1806 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1809 OS << '\\' << Argument;
1813 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1814 ie = A[Index].end();
1816 if (it->getKind() == AsmToken::String)
1817 OS << it->getStringContents();
1819 OS << it->getString();
1821 Pos += 1 + Argument.size();
1824 // Update the scan point.
1825 Body = Body.substr(Pos);
1831 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1832 SMLoc EL, MemoryBuffer *I)
1833 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1836 static bool isOperator(AsmToken::TokenKind kind) {
1840 case AsmToken::Plus:
1841 case AsmToken::Minus:
1842 case AsmToken::Tilde:
1843 case AsmToken::Slash:
1844 case AsmToken::Star:
1846 case AsmToken::Equal:
1847 case AsmToken::EqualEqual:
1848 case AsmToken::Pipe:
1849 case AsmToken::PipePipe:
1850 case AsmToken::Caret:
1852 case AsmToken::AmpAmp:
1853 case AsmToken::Exclaim:
1854 case AsmToken::ExclaimEqual:
1855 case AsmToken::Percent:
1856 case AsmToken::Less:
1857 case AsmToken::LessEqual:
1858 case AsmToken::LessLess:
1859 case AsmToken::LessGreater:
1860 case AsmToken::Greater:
1861 case AsmToken::GreaterEqual:
1862 case AsmToken::GreaterGreater:
1868 class AsmLexerSkipSpaceRAII {
1870 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1871 Lexer.setSkipSpace(SkipSpace);
1874 ~AsmLexerSkipSpaceRAII() {
1875 Lexer.setSkipSpace(true);
1883 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA) {
1884 unsigned ParenLevel = 0;
1885 unsigned AddTokens = 0;
1887 // Darwin doesn't use spaces to delmit arguments.
1888 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1891 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1892 return TokError("unexpected token in macro instantiation");
1894 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1897 if (Lexer.is(AsmToken::Space)) {
1898 Lex(); // Eat spaces
1900 // Spaces can delimit parameters, but could also be part an expression.
1901 // If the token after a space is an operator, add the token and the next
1902 // one into this argument
1904 if (isOperator(Lexer.getKind())) {
1905 // Check to see whether the token is used as an operator,
1906 // or part of an identifier
1907 const char *NextChar = getTok().getEndLoc().getPointer();
1908 if (*NextChar == ' ')
1912 if (!AddTokens && ParenLevel == 0) {
1918 // handleMacroEntry relies on not advancing the lexer here
1919 // to be able to fill in the remaining default parameter values
1920 if (Lexer.is(AsmToken::EndOfStatement))
1923 // Adjust the current parentheses level.
1924 if (Lexer.is(AsmToken::LParen))
1926 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1929 // Append the token to the current argument list.
1930 MA.push_back(getTok());
1936 if (ParenLevel != 0)
1937 return TokError("unbalanced parentheses in macro argument");
1941 // Parse the macro instantiation arguments.
1942 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1943 MCAsmMacroArguments &A) {
1944 const unsigned NParameters = M ? M->Parameters.size() : 0;
1945 bool NamedParametersFound = false;
1946 SmallVector<SMLoc, 4> FALocs;
1948 A.resize(NParameters);
1949 FALocs.resize(NParameters);
1951 // Parse two kinds of macro invocations:
1952 // - macros defined without any parameters accept an arbitrary number of them
1953 // - macros defined with parameters accept at most that many of them
1954 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1956 SMLoc IDLoc = Lexer.getLoc();
1957 MCAsmMacroParameter FA;
1959 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
1960 if (parseIdentifier(FA.Name)) {
1961 Error(IDLoc, "invalid argument identifier for formal argument");
1962 eatToEndOfStatement();
1966 if (!Lexer.is(AsmToken::Equal)) {
1967 TokError("expected '=' after formal parameter identifier");
1968 eatToEndOfStatement();
1973 NamedParametersFound = true;
1976 if (NamedParametersFound && FA.Name.empty()) {
1977 Error(IDLoc, "cannot mix positional and keyword arguments");
1978 eatToEndOfStatement();
1982 if (parseMacroArgument(FA.Value))
1985 unsigned PI = Parameter;
1986 if (!FA.Name.empty()) {
1988 for (FAI = 0; FAI < NParameters; ++FAI)
1989 if (M->Parameters[FAI].Name == FA.Name)
1992 if (FAI >= NParameters) {
1994 "parameter named '" + FA.Name + "' does not exist for macro '" +
2001 if (!FA.Value.empty()) {
2006 if (FALocs.size() <= PI)
2007 FALocs.resize(PI + 1);
2009 FALocs[PI] = Lexer.getLoc();
2012 // At the end of the statement, fill in remaining arguments that have
2013 // default values. If there aren't any, then the next argument is
2014 // required but missing
2015 if (Lexer.is(AsmToken::EndOfStatement)) {
2016 bool Failure = false;
2017 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2018 if (A[FAI].empty()) {
2019 if (M->Parameters[FAI].Required) {
2020 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2021 "missing value for required parameter "
2022 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2026 if (!M->Parameters[FAI].Value.empty())
2027 A[FAI] = M->Parameters[FAI].Value;
2033 if (Lexer.is(AsmToken::Comma))
2037 return TokError("too many positional arguments");
2040 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2041 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2042 return (I == MacroMap.end()) ? NULL : I->getValue();
2045 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
2046 MacroMap[Name] = new MCAsmMacro(Macro);
2049 void AsmParser::undefineMacro(StringRef Name) {
2050 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2051 if (I != MacroMap.end()) {
2052 delete I->getValue();
2057 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2058 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2059 // this, although we should protect against infinite loops.
2060 if (ActiveMacros.size() == 20)
2061 return TokError("macros cannot be nested more than 20 levels deep");
2063 MCAsmMacroArguments A;
2064 if (parseMacroArguments(M, A))
2067 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2068 // to hold the macro body with substitutions.
2069 SmallString<256> Buf;
2070 StringRef Body = M->Body;
2071 raw_svector_ostream OS(Buf);
2073 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2076 // We include the .endmacro in the buffer as our cue to exit the macro
2078 OS << ".endmacro\n";
2080 MemoryBuffer *Instantiation =
2081 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2083 // Create the macro instantiation object and add to the current macro
2084 // instantiation stack.
2085 MacroInstantiation *MI = new MacroInstantiation(
2086 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
2087 ActiveMacros.push_back(MI);
2089 // Jump to the macro instantiation and prime the lexer.
2090 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2091 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2097 void AsmParser::handleMacroExit() {
2098 // Jump to the EndOfStatement we should return to, and consume it.
2099 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2102 // Pop the instantiation entry.
2103 delete ActiveMacros.back();
2104 ActiveMacros.pop_back();
2107 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2108 switch (Value->getKind()) {
2109 case MCExpr::Binary: {
2110 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2111 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2113 case MCExpr::Target:
2114 case MCExpr::Constant:
2116 case MCExpr::SymbolRef: {
2118 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2120 return isUsedIn(Sym, S.getVariableValue());
2124 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2127 llvm_unreachable("Unknown expr kind!");
2130 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2132 // FIXME: Use better location, we should use proper tokens.
2133 SMLoc EqualLoc = Lexer.getLoc();
2135 const MCExpr *Value;
2136 if (parseExpression(Value))
2139 // Note: we don't count b as used in "a = b". This is to allow
2143 if (Lexer.isNot(AsmToken::EndOfStatement))
2144 return TokError("unexpected token in assignment");
2146 // Eat the end of statement marker.
2149 // Validate that the LHS is allowed to be a variable (either it has not been
2150 // used as a symbol, or it is an absolute symbol).
2151 MCSymbol *Sym = getContext().LookupSymbol(Name);
2153 // Diagnose assignment to a label.
2155 // FIXME: Diagnostics. Note the location of the definition as a label.
2156 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2157 if (isUsedIn(Sym, Value))
2158 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2159 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2160 ; // Allow redefinitions of undefined symbols only used in directives.
2161 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2162 ; // Allow redefinitions of variables that haven't yet been used.
2163 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2164 return Error(EqualLoc, "redefinition of '" + Name + "'");
2165 else if (!Sym->isVariable())
2166 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2167 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2168 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2171 // Don't count these checks as uses.
2172 Sym->setUsed(false);
2173 } else if (Name == ".") {
2174 if (Out.EmitValueToOffset(Value, 0)) {
2175 Error(EqualLoc, "expected absolute expression");
2176 eatToEndOfStatement();
2180 Sym = getContext().GetOrCreateSymbol(Name);
2182 // Do the assignment.
2183 Out.EmitAssignment(Sym, Value);
2185 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2190 /// parseIdentifier:
2193 bool AsmParser::parseIdentifier(StringRef &Res) {
2194 // The assembler has relaxed rules for accepting identifiers, in particular we
2195 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2196 // separate tokens. At this level, we have already lexed so we cannot (currently)
2197 // handle this as a context dependent token, instead we detect adjacent tokens
2198 // and return the combined identifier.
2199 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2200 SMLoc PrefixLoc = getLexer().getLoc();
2202 // Consume the prefix character, and check for a following identifier.
2204 if (Lexer.isNot(AsmToken::Identifier))
2207 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2208 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2211 // Construct the joined identifier and consume the token.
2213 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2218 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2221 Res = getTok().getIdentifier();
2223 Lex(); // Consume the identifier token.
2228 /// parseDirectiveSet:
2229 /// ::= .equ identifier ',' expression
2230 /// ::= .equiv identifier ',' expression
2231 /// ::= .set identifier ',' expression
2232 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2235 if (parseIdentifier(Name))
2236 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2238 if (getLexer().isNot(AsmToken::Comma))
2239 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2242 return parseAssignment(Name, allow_redef, true);
2245 bool AsmParser::parseEscapedString(std::string &Data) {
2246 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2249 StringRef Str = getTok().getStringContents();
2250 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2251 if (Str[i] != '\\') {
2256 // Recognize escaped characters. Note that this escape semantics currently
2257 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2260 return TokError("unexpected backslash at end of string");
2262 // Recognize octal sequences.
2263 if ((unsigned)(Str[i] - '0') <= 7) {
2264 // Consume up to three octal characters.
2265 unsigned Value = Str[i] - '0';
2267 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2269 Value = Value * 8 + (Str[i] - '0');
2271 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2273 Value = Value * 8 + (Str[i] - '0');
2278 return TokError("invalid octal escape sequence (out of range)");
2280 Data += (unsigned char)Value;
2284 // Otherwise recognize individual escapes.
2287 // Just reject invalid escape sequences for now.
2288 return TokError("invalid escape sequence (unrecognized character)");
2290 case 'b': Data += '\b'; break;
2291 case 'f': Data += '\f'; break;
2292 case 'n': Data += '\n'; break;
2293 case 'r': Data += '\r'; break;
2294 case 't': Data += '\t'; break;
2295 case '"': Data += '"'; break;
2296 case '\\': Data += '\\'; break;
2303 /// parseDirectiveAscii:
2304 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2305 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2306 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2307 checkForValidSection();
2310 if (getLexer().isNot(AsmToken::String))
2311 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2314 if (parseEscapedString(Data))
2317 getStreamer().EmitBytes(Data);
2319 getStreamer().EmitBytes(StringRef("\0", 1));
2323 if (getLexer().is(AsmToken::EndOfStatement))
2326 if (getLexer().isNot(AsmToken::Comma))
2327 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2336 /// parseDirectiveValue
2337 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2338 bool AsmParser::parseDirectiveValue(unsigned Size) {
2339 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2340 checkForValidSection();
2343 const MCExpr *Value;
2344 SMLoc ExprLoc = getLexer().getLoc();
2345 if (parseExpression(Value))
2348 // Special case constant expressions to match code generator.
2349 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2350 assert(Size <= 8 && "Invalid size");
2351 uint64_t IntValue = MCE->getValue();
2352 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2353 return Error(ExprLoc, "literal value out of range for directive");
2354 getStreamer().EmitIntValue(IntValue, Size);
2356 getStreamer().EmitValue(Value, Size);
2358 if (getLexer().is(AsmToken::EndOfStatement))
2361 // FIXME: Improve diagnostic.
2362 if (getLexer().isNot(AsmToken::Comma))
2363 return TokError("unexpected token in directive");
2372 /// ParseDirectiveOctaValue
2373 /// ::= .octa [ hexconstant (, hexconstant)* ]
2374 bool AsmParser::parseDirectiveOctaValue() {
2375 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2376 checkForValidSection();
2379 if (Lexer.getKind() == AsmToken::Error)
2381 if (Lexer.getKind() != AsmToken::Integer &&
2382 Lexer.getKind() != AsmToken::BigNum)
2383 return TokError("unknown token in expression");
2385 SMLoc ExprLoc = getLexer().getLoc();
2386 APInt IntValue = getTok().getAPIntVal();
2390 if (IntValue.isIntN(64)) {
2392 lo = IntValue.getZExtValue();
2393 } else if (IntValue.isIntN(128)) {
2394 // It might actually have more than 128 bits, but the top ones are zero.
2395 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2396 lo = IntValue.getLoBits(64).getZExtValue();
2398 return Error(ExprLoc, "literal value out of range for directive");
2400 if (MAI.isLittleEndian()) {
2401 getStreamer().EmitIntValue(lo, 8);
2402 getStreamer().EmitIntValue(hi, 8);
2404 getStreamer().EmitIntValue(hi, 8);
2405 getStreamer().EmitIntValue(lo, 8);
2408 if (getLexer().is(AsmToken::EndOfStatement))
2411 // FIXME: Improve diagnostic.
2412 if (getLexer().isNot(AsmToken::Comma))
2413 return TokError("unexpected token in directive");
2422 /// parseDirectiveRealValue
2423 /// ::= (.single | .double) [ expression (, expression)* ]
2424 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2425 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2426 checkForValidSection();
2429 // We don't truly support arithmetic on floating point expressions, so we
2430 // have to manually parse unary prefixes.
2432 if (getLexer().is(AsmToken::Minus)) {
2435 } else if (getLexer().is(AsmToken::Plus))
2438 if (getLexer().isNot(AsmToken::Integer) &&
2439 getLexer().isNot(AsmToken::Real) &&
2440 getLexer().isNot(AsmToken::Identifier))
2441 return TokError("unexpected token in directive");
2443 // Convert to an APFloat.
2444 APFloat Value(Semantics);
2445 StringRef IDVal = getTok().getString();
2446 if (getLexer().is(AsmToken::Identifier)) {
2447 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2448 Value = APFloat::getInf(Semantics);
2449 else if (!IDVal.compare_lower("nan"))
2450 Value = APFloat::getNaN(Semantics, false, ~0);
2452 return TokError("invalid floating point literal");
2453 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2454 APFloat::opInvalidOp)
2455 return TokError("invalid floating point literal");
2459 // Consume the numeric token.
2462 // Emit the value as an integer.
2463 APInt AsInt = Value.bitcastToAPInt();
2464 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2465 AsInt.getBitWidth() / 8);
2467 if (getLexer().is(AsmToken::EndOfStatement))
2470 if (getLexer().isNot(AsmToken::Comma))
2471 return TokError("unexpected token in directive");
2480 /// parseDirectiveZero
2481 /// ::= .zero expression
2482 bool AsmParser::parseDirectiveZero() {
2483 checkForValidSection();
2486 if (parseAbsoluteExpression(NumBytes))
2490 if (getLexer().is(AsmToken::Comma)) {
2492 if (parseAbsoluteExpression(Val))
2496 if (getLexer().isNot(AsmToken::EndOfStatement))
2497 return TokError("unexpected token in '.zero' directive");
2501 getStreamer().EmitFill(NumBytes, Val);
2506 /// parseDirectiveFill
2507 /// ::= .fill expression [ , expression [ , expression ] ]
2508 bool AsmParser::parseDirectiveFill() {
2509 checkForValidSection();
2511 SMLoc RepeatLoc = getLexer().getLoc();
2513 if (parseAbsoluteExpression(NumValues))
2516 if (NumValues < 0) {
2518 "'.fill' directive with negative repeat count has no effect");
2522 int64_t FillSize = 1;
2523 int64_t FillExpr = 0;
2525 SMLoc SizeLoc, ExprLoc;
2526 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2527 if (getLexer().isNot(AsmToken::Comma))
2528 return TokError("unexpected token in '.fill' directive");
2531 SizeLoc = getLexer().getLoc();
2532 if (parseAbsoluteExpression(FillSize))
2535 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2536 if (getLexer().isNot(AsmToken::Comma))
2537 return TokError("unexpected token in '.fill' directive");
2540 ExprLoc = getLexer().getLoc();
2541 if (parseAbsoluteExpression(FillExpr))
2544 if (getLexer().isNot(AsmToken::EndOfStatement))
2545 return TokError("unexpected token in '.fill' directive");
2552 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2556 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2560 if (!isUInt<32>(FillExpr) && FillSize > 4)
2561 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2563 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2564 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2566 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2567 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2568 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2574 /// parseDirectiveOrg
2575 /// ::= .org expression [ , expression ]
2576 bool AsmParser::parseDirectiveOrg() {
2577 checkForValidSection();
2579 const MCExpr *Offset;
2580 SMLoc Loc = getTok().getLoc();
2581 if (parseExpression(Offset))
2584 // Parse optional fill expression.
2585 int64_t FillExpr = 0;
2586 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2587 if (getLexer().isNot(AsmToken::Comma))
2588 return TokError("unexpected token in '.org' directive");
2591 if (parseAbsoluteExpression(FillExpr))
2594 if (getLexer().isNot(AsmToken::EndOfStatement))
2595 return TokError("unexpected token in '.org' directive");
2600 // Only limited forms of relocatable expressions are accepted here, it
2601 // has to be relative to the current section. The streamer will return
2602 // 'true' if the expression wasn't evaluatable.
2603 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2604 return Error(Loc, "expected assembly-time absolute expression");
2609 /// parseDirectiveAlign
2610 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2611 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2612 checkForValidSection();
2614 SMLoc AlignmentLoc = getLexer().getLoc();
2616 if (parseAbsoluteExpression(Alignment))
2620 bool HasFillExpr = false;
2621 int64_t FillExpr = 0;
2622 int64_t MaxBytesToFill = 0;
2623 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2624 if (getLexer().isNot(AsmToken::Comma))
2625 return TokError("unexpected token in directive");
2628 // The fill expression can be omitted while specifying a maximum number of
2629 // alignment bytes, e.g:
2631 if (getLexer().isNot(AsmToken::Comma)) {
2633 if (parseAbsoluteExpression(FillExpr))
2637 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2638 if (getLexer().isNot(AsmToken::Comma))
2639 return TokError("unexpected token in directive");
2642 MaxBytesLoc = getLexer().getLoc();
2643 if (parseAbsoluteExpression(MaxBytesToFill))
2646 if (getLexer().isNot(AsmToken::EndOfStatement))
2647 return TokError("unexpected token in directive");
2656 // Compute alignment in bytes.
2658 // FIXME: Diagnose overflow.
2659 if (Alignment >= 32) {
2660 Error(AlignmentLoc, "invalid alignment value");
2664 Alignment = 1ULL << Alignment;
2666 // Reject alignments that aren't a power of two, for gas compatibility.
2667 if (!isPowerOf2_64(Alignment))
2668 Error(AlignmentLoc, "alignment must be a power of 2");
2671 // Diagnose non-sensical max bytes to align.
2672 if (MaxBytesLoc.isValid()) {
2673 if (MaxBytesToFill < 1) {
2674 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2675 "many bytes, ignoring maximum bytes expression");
2679 if (MaxBytesToFill >= Alignment) {
2680 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2686 // Check whether we should use optimal code alignment for this .align
2688 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
2689 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2690 ValueSize == 1 && UseCodeAlign) {
2691 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2693 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2694 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2701 /// parseDirectiveFile
2702 /// ::= .file [number] filename
2703 /// ::= .file number directory filename
2704 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2705 // FIXME: I'm not sure what this is.
2706 int64_t FileNumber = -1;
2707 SMLoc FileNumberLoc = getLexer().getLoc();
2708 if (getLexer().is(AsmToken::Integer)) {
2709 FileNumber = getTok().getIntVal();
2713 return TokError("file number less than one");
2716 if (getLexer().isNot(AsmToken::String))
2717 return TokError("unexpected token in '.file' directive");
2719 // Usually the directory and filename together, otherwise just the directory.
2720 // Allow the strings to have escaped octal character sequence.
2721 std::string Path = getTok().getString();
2722 if (parseEscapedString(Path))
2726 StringRef Directory;
2728 std::string FilenameData;
2729 if (getLexer().is(AsmToken::String)) {
2730 if (FileNumber == -1)
2731 return TokError("explicit path specified, but no file number");
2732 if (parseEscapedString(FilenameData))
2734 Filename = FilenameData;
2741 if (getLexer().isNot(AsmToken::EndOfStatement))
2742 return TokError("unexpected token in '.file' directive");
2744 if (FileNumber == -1)
2745 getStreamer().EmitFileDirective(Filename);
2747 if (getContext().getGenDwarfForAssembly() == true)
2749 "input can't have .file dwarf directives when -g is "
2750 "used to generate dwarf debug info for assembly code");
2752 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2753 Error(FileNumberLoc, "file number already allocated");
2759 /// parseDirectiveLine
2760 /// ::= .line [number]
2761 bool AsmParser::parseDirectiveLine() {
2762 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2763 if (getLexer().isNot(AsmToken::Integer))
2764 return TokError("unexpected token in '.line' directive");
2766 int64_t LineNumber = getTok().getIntVal();
2770 // FIXME: Do something with the .line.
2773 if (getLexer().isNot(AsmToken::EndOfStatement))
2774 return TokError("unexpected token in '.line' directive");
2779 /// parseDirectiveLoc
2780 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2781 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2782 /// The first number is a file number, must have been previously assigned with
2783 /// a .file directive, the second number is the line number and optionally the
2784 /// third number is a column position (zero if not specified). The remaining
2785 /// optional items are .loc sub-directives.
2786 bool AsmParser::parseDirectiveLoc() {
2787 if (getLexer().isNot(AsmToken::Integer))
2788 return TokError("unexpected token in '.loc' directive");
2789 int64_t FileNumber = getTok().getIntVal();
2791 return TokError("file number less than one in '.loc' directive");
2792 if (!getContext().isValidDwarfFileNumber(FileNumber))
2793 return TokError("unassigned file number in '.loc' directive");
2796 int64_t LineNumber = 0;
2797 if (getLexer().is(AsmToken::Integer)) {
2798 LineNumber = getTok().getIntVal();
2800 return TokError("line number less than zero in '.loc' directive");
2804 int64_t ColumnPos = 0;
2805 if (getLexer().is(AsmToken::Integer)) {
2806 ColumnPos = getTok().getIntVal();
2808 return TokError("column position less than zero in '.loc' directive");
2812 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2814 int64_t Discriminator = 0;
2815 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2817 if (getLexer().is(AsmToken::EndOfStatement))
2821 SMLoc Loc = getTok().getLoc();
2822 if (parseIdentifier(Name))
2823 return TokError("unexpected token in '.loc' directive");
2825 if (Name == "basic_block")
2826 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2827 else if (Name == "prologue_end")
2828 Flags |= DWARF2_FLAG_PROLOGUE_END;
2829 else if (Name == "epilogue_begin")
2830 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2831 else if (Name == "is_stmt") {
2832 Loc = getTok().getLoc();
2833 const MCExpr *Value;
2834 if (parseExpression(Value))
2836 // The expression must be the constant 0 or 1.
2837 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2838 int Value = MCE->getValue();
2840 Flags &= ~DWARF2_FLAG_IS_STMT;
2841 else if (Value == 1)
2842 Flags |= DWARF2_FLAG_IS_STMT;
2844 return Error(Loc, "is_stmt value not 0 or 1");
2846 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2848 } else if (Name == "isa") {
2849 Loc = getTok().getLoc();
2850 const MCExpr *Value;
2851 if (parseExpression(Value))
2853 // The expression must be a constant greater or equal to 0.
2854 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2855 int Value = MCE->getValue();
2857 return Error(Loc, "isa number less than zero");
2860 return Error(Loc, "isa number not a constant value");
2862 } else if (Name == "discriminator") {
2863 if (parseAbsoluteExpression(Discriminator))
2866 return Error(Loc, "unknown sub-directive in '.loc' directive");
2869 if (getLexer().is(AsmToken::EndOfStatement))
2874 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2875 Isa, Discriminator, StringRef());
2880 /// parseDirectiveStabs
2881 /// ::= .stabs string, number, number, number
2882 bool AsmParser::parseDirectiveStabs() {
2883 return TokError("unsupported directive '.stabs'");
2886 /// parseDirectiveCFISections
2887 /// ::= .cfi_sections section [, section]
2888 bool AsmParser::parseDirectiveCFISections() {
2893 if (parseIdentifier(Name))
2894 return TokError("Expected an identifier");
2896 if (Name == ".eh_frame")
2898 else if (Name == ".debug_frame")
2901 if (getLexer().is(AsmToken::Comma)) {
2904 if (parseIdentifier(Name))
2905 return TokError("Expected an identifier");
2907 if (Name == ".eh_frame")
2909 else if (Name == ".debug_frame")
2913 getStreamer().EmitCFISections(EH, Debug);
2917 /// parseDirectiveCFIStartProc
2918 /// ::= .cfi_startproc [simple]
2919 bool AsmParser::parseDirectiveCFIStartProc() {
2921 if (getLexer().isNot(AsmToken::EndOfStatement))
2922 if (parseIdentifier(Simple) || Simple != "simple")
2923 return TokError("unexpected token in .cfi_startproc directive");
2925 getStreamer().EmitCFIStartProc(!Simple.empty());
2929 /// parseDirectiveCFIEndProc
2930 /// ::= .cfi_endproc
2931 bool AsmParser::parseDirectiveCFIEndProc() {
2932 getStreamer().EmitCFIEndProc();
2936 /// \brief parse register name or number.
2937 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2938 SMLoc DirectiveLoc) {
2941 if (getLexer().isNot(AsmToken::Integer)) {
2942 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2944 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2946 return parseAbsoluteExpression(Register);
2951 /// parseDirectiveCFIDefCfa
2952 /// ::= .cfi_def_cfa register, offset
2953 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2954 int64_t Register = 0;
2955 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2958 if (getLexer().isNot(AsmToken::Comma))
2959 return TokError("unexpected token in directive");
2963 if (parseAbsoluteExpression(Offset))
2966 getStreamer().EmitCFIDefCfa(Register, Offset);
2970 /// parseDirectiveCFIDefCfaOffset
2971 /// ::= .cfi_def_cfa_offset offset
2972 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2974 if (parseAbsoluteExpression(Offset))
2977 getStreamer().EmitCFIDefCfaOffset(Offset);
2981 /// parseDirectiveCFIRegister
2982 /// ::= .cfi_register register, register
2983 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2984 int64_t Register1 = 0;
2985 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2988 if (getLexer().isNot(AsmToken::Comma))
2989 return TokError("unexpected token in directive");
2992 int64_t Register2 = 0;
2993 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2996 getStreamer().EmitCFIRegister(Register1, Register2);
3000 /// parseDirectiveCFIWindowSave
3001 /// ::= .cfi_window_save
3002 bool AsmParser::parseDirectiveCFIWindowSave() {
3003 getStreamer().EmitCFIWindowSave();
3007 /// parseDirectiveCFIAdjustCfaOffset
3008 /// ::= .cfi_adjust_cfa_offset adjustment
3009 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3010 int64_t Adjustment = 0;
3011 if (parseAbsoluteExpression(Adjustment))
3014 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3018 /// parseDirectiveCFIDefCfaRegister
3019 /// ::= .cfi_def_cfa_register register
3020 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3021 int64_t Register = 0;
3022 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3025 getStreamer().EmitCFIDefCfaRegister(Register);
3029 /// parseDirectiveCFIOffset
3030 /// ::= .cfi_offset register, offset
3031 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3032 int64_t Register = 0;
3035 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3038 if (getLexer().isNot(AsmToken::Comma))
3039 return TokError("unexpected token in directive");
3042 if (parseAbsoluteExpression(Offset))
3045 getStreamer().EmitCFIOffset(Register, Offset);
3049 /// parseDirectiveCFIRelOffset
3050 /// ::= .cfi_rel_offset register, offset
3051 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3052 int64_t Register = 0;
3054 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3057 if (getLexer().isNot(AsmToken::Comma))
3058 return TokError("unexpected token in directive");
3062 if (parseAbsoluteExpression(Offset))
3065 getStreamer().EmitCFIRelOffset(Register, Offset);
3069 static bool isValidEncoding(int64_t Encoding) {
3070 if (Encoding & ~0xff)
3073 if (Encoding == dwarf::DW_EH_PE_omit)
3076 const unsigned Format = Encoding & 0xf;
3077 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3078 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3079 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3080 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3083 const unsigned Application = Encoding & 0x70;
3084 if (Application != dwarf::DW_EH_PE_absptr &&
3085 Application != dwarf::DW_EH_PE_pcrel)
3091 /// parseDirectiveCFIPersonalityOrLsda
3092 /// IsPersonality true for cfi_personality, false for cfi_lsda
3093 /// ::= .cfi_personality encoding, [symbol_name]
3094 /// ::= .cfi_lsda encoding, [symbol_name]
3095 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3096 int64_t Encoding = 0;
3097 if (parseAbsoluteExpression(Encoding))
3099 if (Encoding == dwarf::DW_EH_PE_omit)
3102 if (!isValidEncoding(Encoding))
3103 return TokError("unsupported encoding.");
3105 if (getLexer().isNot(AsmToken::Comma))
3106 return TokError("unexpected token in directive");
3110 if (parseIdentifier(Name))
3111 return TokError("expected identifier in directive");
3113 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3116 getStreamer().EmitCFIPersonality(Sym, Encoding);
3118 getStreamer().EmitCFILsda(Sym, Encoding);
3122 /// parseDirectiveCFIRememberState
3123 /// ::= .cfi_remember_state
3124 bool AsmParser::parseDirectiveCFIRememberState() {
3125 getStreamer().EmitCFIRememberState();
3129 /// parseDirectiveCFIRestoreState
3130 /// ::= .cfi_remember_state
3131 bool AsmParser::parseDirectiveCFIRestoreState() {
3132 getStreamer().EmitCFIRestoreState();
3136 /// parseDirectiveCFISameValue
3137 /// ::= .cfi_same_value register
3138 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3139 int64_t Register = 0;
3141 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3144 getStreamer().EmitCFISameValue(Register);
3148 /// parseDirectiveCFIRestore
3149 /// ::= .cfi_restore register
3150 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3151 int64_t Register = 0;
3152 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3155 getStreamer().EmitCFIRestore(Register);
3159 /// parseDirectiveCFIEscape
3160 /// ::= .cfi_escape expression[,...]
3161 bool AsmParser::parseDirectiveCFIEscape() {
3164 if (parseAbsoluteExpression(CurrValue))
3167 Values.push_back((uint8_t)CurrValue);
3169 while (getLexer().is(AsmToken::Comma)) {
3172 if (parseAbsoluteExpression(CurrValue))
3175 Values.push_back((uint8_t)CurrValue);
3178 getStreamer().EmitCFIEscape(Values);
3182 /// parseDirectiveCFISignalFrame
3183 /// ::= .cfi_signal_frame
3184 bool AsmParser::parseDirectiveCFISignalFrame() {
3185 if (getLexer().isNot(AsmToken::EndOfStatement))
3186 return Error(getLexer().getLoc(),
3187 "unexpected token in '.cfi_signal_frame'");
3189 getStreamer().EmitCFISignalFrame();
3193 /// parseDirectiveCFIUndefined
3194 /// ::= .cfi_undefined register
3195 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3196 int64_t Register = 0;
3198 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3201 getStreamer().EmitCFIUndefined(Register);
3205 /// parseDirectiveMacrosOnOff
3208 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3209 if (getLexer().isNot(AsmToken::EndOfStatement))
3210 return Error(getLexer().getLoc(),
3211 "unexpected token in '" + Directive + "' directive");
3213 setMacrosEnabled(Directive == ".macros_on");
3217 /// parseDirectiveMacro
3218 /// ::= .macro name[,] [parameters]
3219 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3221 if (parseIdentifier(Name))
3222 return TokError("expected identifier in '.macro' directive");
3224 if (getLexer().is(AsmToken::Comma))
3227 MCAsmMacroParameters Parameters;
3228 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3229 MCAsmMacroParameter Parameter;
3230 if (parseIdentifier(Parameter.Name))
3231 return TokError("expected identifier in '.macro' directive");
3233 if (Lexer.is(AsmToken::Colon)) {
3234 Lex(); // consume ':'
3237 StringRef Qualifier;
3239 QualLoc = Lexer.getLoc();
3240 if (parseIdentifier(Qualifier))
3241 return Error(QualLoc, "missing parameter qualifier for "
3242 "'" + Parameter.Name + "' in macro '" + Name + "'");
3244 if (Qualifier == "req")
3245 Parameter.Required = true;
3247 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3248 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3251 if (getLexer().is(AsmToken::Equal)) {
3256 ParamLoc = Lexer.getLoc();
3257 if (parseMacroArgument(Parameter.Value))
3260 if (Parameter.Required)
3261 Warning(ParamLoc, "pointless default value for required parameter "
3262 "'" + Parameter.Name + "' in macro '" + Name + "'");
3265 Parameters.push_back(Parameter);
3267 if (getLexer().is(AsmToken::Comma))
3271 // Eat the end of statement.
3274 AsmToken EndToken, StartToken = getTok();
3275 unsigned MacroDepth = 0;
3277 // Lex the macro definition.
3279 // Check whether we have reached the end of the file.
3280 if (getLexer().is(AsmToken::Eof))
3281 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3283 // Otherwise, check whether we have reach the .endmacro.
3284 if (getLexer().is(AsmToken::Identifier)) {
3285 if (getTok().getIdentifier() == ".endm" ||
3286 getTok().getIdentifier() == ".endmacro") {
3287 if (MacroDepth == 0) { // Outermost macro.
3288 EndToken = getTok();
3290 if (getLexer().isNot(AsmToken::EndOfStatement))
3291 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3295 // Otherwise we just found the end of an inner macro.
3298 } else if (getTok().getIdentifier() == ".macro") {
3299 // We allow nested macros. Those aren't instantiated until the outermost
3300 // macro is expanded so just ignore them for now.
3305 // Otherwise, scan til the end of the statement.
3306 eatToEndOfStatement();
3309 if (lookupMacro(Name)) {
3310 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3313 const char *BodyStart = StartToken.getLoc().getPointer();
3314 const char *BodyEnd = EndToken.getLoc().getPointer();
3315 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3316 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3317 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3321 /// checkForBadMacro
3323 /// With the support added for named parameters there may be code out there that
3324 /// is transitioning from positional parameters. In versions of gas that did
3325 /// not support named parameters they would be ignored on the macro definition.
3326 /// But to support both styles of parameters this is not possible so if a macro
3327 /// definition has named parameters but does not use them and has what appears
3328 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3329 /// warning that the positional parameter found in body which have no effect.
3330 /// Hoping the developer will either remove the named parameters from the macro
3331 /// definition so the positional parameters get used if that was what was
3332 /// intended or change the macro to use the named parameters. It is possible
3333 /// this warning will trigger when the none of the named parameters are used
3334 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3335 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3337 ArrayRef<MCAsmMacroParameter> Parameters) {
3338 // If this macro is not defined with named parameters the warning we are
3339 // checking for here doesn't apply.
3340 unsigned NParameters = Parameters.size();
3341 if (NParameters == 0)
3344 bool NamedParametersFound = false;
3345 bool PositionalParametersFound = false;
3347 // Look at the body of the macro for use of both the named parameters and what
3348 // are likely to be positional parameters. This is what expandMacro() is
3349 // doing when it finds the parameters in the body.
3350 while (!Body.empty()) {
3351 // Scan for the next possible parameter.
3352 std::size_t End = Body.size(), Pos = 0;
3353 for (; Pos != End; ++Pos) {
3354 // Check for a substitution or escape.
3355 // This macro is defined with parameters, look for \foo, \bar, etc.
3356 if (Body[Pos] == '\\' && Pos + 1 != End)
3359 // This macro should have parameters, but look for $0, $1, ..., $n too.
3360 if (Body[Pos] != '$' || Pos + 1 == End)
3362 char Next = Body[Pos + 1];
3363 if (Next == '$' || Next == 'n' ||
3364 isdigit(static_cast<unsigned char>(Next)))
3368 // Check if we reached the end.
3372 if (Body[Pos] == '$') {
3373 switch (Body[Pos + 1]) {
3378 // $n => number of arguments
3380 PositionalParametersFound = true;
3383 // $[0-9] => argument
3385 PositionalParametersFound = true;
3391 unsigned I = Pos + 1;
3392 while (isIdentifierChar(Body[I]) && I + 1 != End)
3395 const char *Begin = Body.data() + Pos + 1;
3396 StringRef Argument(Begin, I - (Pos + 1));
3398 for (; Index < NParameters; ++Index)
3399 if (Parameters[Index].Name == Argument)
3402 if (Index == NParameters) {
3403 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3409 NamedParametersFound = true;
3410 Pos += 1 + Argument.size();
3413 // Update the scan point.
3414 Body = Body.substr(Pos);
3417 if (!NamedParametersFound && PositionalParametersFound)
3418 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3419 "used in macro body, possible positional parameter "
3420 "found in body which will have no effect");
3423 /// parseDirectiveEndMacro
3426 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3427 if (getLexer().isNot(AsmToken::EndOfStatement))
3428 return TokError("unexpected token in '" + Directive + "' directive");
3430 // If we are inside a macro instantiation, terminate the current
3432 if (isInsideMacroInstantiation()) {
3437 // Otherwise, this .endmacro is a stray entry in the file; well formed
3438 // .endmacro directives are handled during the macro definition parsing.
3439 return TokError("unexpected '" + Directive + "' in file, "
3440 "no current macro definition");
3443 /// parseDirectivePurgeMacro
3445 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3447 if (parseIdentifier(Name))
3448 return TokError("expected identifier in '.purgem' directive");
3450 if (getLexer().isNot(AsmToken::EndOfStatement))
3451 return TokError("unexpected token in '.purgem' directive");
3453 if (!lookupMacro(Name))
3454 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3456 undefineMacro(Name);
3460 /// parseDirectiveBundleAlignMode
3461 /// ::= {.bundle_align_mode} expression
3462 bool AsmParser::parseDirectiveBundleAlignMode() {
3463 checkForValidSection();
3465 // Expect a single argument: an expression that evaluates to a constant
3466 // in the inclusive range 0-30.
3467 SMLoc ExprLoc = getLexer().getLoc();
3468 int64_t AlignSizePow2;
3469 if (parseAbsoluteExpression(AlignSizePow2))
3471 else if (getLexer().isNot(AsmToken::EndOfStatement))
3472 return TokError("unexpected token after expression in"
3473 " '.bundle_align_mode' directive");
3474 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3475 return Error(ExprLoc,
3476 "invalid bundle alignment size (expected between 0 and 30)");
3480 // Because of AlignSizePow2's verified range we can safely truncate it to
3482 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3486 /// parseDirectiveBundleLock
3487 /// ::= {.bundle_lock} [align_to_end]
3488 bool AsmParser::parseDirectiveBundleLock() {
3489 checkForValidSection();
3490 bool AlignToEnd = false;
3492 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3494 SMLoc Loc = getTok().getLoc();
3495 const char *kInvalidOptionError =
3496 "invalid option for '.bundle_lock' directive";
3498 if (parseIdentifier(Option))
3499 return Error(Loc, kInvalidOptionError);
3501 if (Option != "align_to_end")
3502 return Error(Loc, kInvalidOptionError);
3503 else if (getLexer().isNot(AsmToken::EndOfStatement))
3505 "unexpected token after '.bundle_lock' directive option");
3511 getStreamer().EmitBundleLock(AlignToEnd);
3515 /// parseDirectiveBundleLock
3516 /// ::= {.bundle_lock}
3517 bool AsmParser::parseDirectiveBundleUnlock() {
3518 checkForValidSection();
3520 if (getLexer().isNot(AsmToken::EndOfStatement))
3521 return TokError("unexpected token in '.bundle_unlock' directive");
3524 getStreamer().EmitBundleUnlock();
3528 /// parseDirectiveSpace
3529 /// ::= (.skip | .space) expression [ , expression ]
3530 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3531 checkForValidSection();
3534 if (parseAbsoluteExpression(NumBytes))
3537 int64_t FillExpr = 0;
3538 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3539 if (getLexer().isNot(AsmToken::Comma))
3540 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3543 if (parseAbsoluteExpression(FillExpr))
3546 if (getLexer().isNot(AsmToken::EndOfStatement))
3547 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3553 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3556 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3557 getStreamer().EmitFill(NumBytes, FillExpr);
3562 /// parseDirectiveLEB128
3563 /// ::= (.sleb128 | .uleb128) expression
3564 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3565 checkForValidSection();
3566 const MCExpr *Value;
3568 if (parseExpression(Value))
3571 if (getLexer().isNot(AsmToken::EndOfStatement))
3572 return TokError("unexpected token in directive");
3575 getStreamer().EmitSLEB128Value(Value);
3577 getStreamer().EmitULEB128Value(Value);
3582 /// parseDirectiveSymbolAttribute
3583 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3584 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3585 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3588 SMLoc Loc = getTok().getLoc();
3590 if (parseIdentifier(Name))
3591 return Error(Loc, "expected identifier in directive");
3593 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3595 // Assembler local symbols don't make any sense here. Complain loudly.
3596 if (Sym->isTemporary())
3597 return Error(Loc, "non-local symbol required in directive");
3599 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3600 return Error(Loc, "unable to emit symbol attribute");
3602 if (getLexer().is(AsmToken::EndOfStatement))
3605 if (getLexer().isNot(AsmToken::Comma))
3606 return TokError("unexpected token in directive");
3615 /// parseDirectiveComm
3616 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3617 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3618 checkForValidSection();
3620 SMLoc IDLoc = getLexer().getLoc();
3622 if (parseIdentifier(Name))
3623 return TokError("expected identifier in directive");
3625 // Handle the identifier as the key symbol.
3626 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3628 if (getLexer().isNot(AsmToken::Comma))
3629 return TokError("unexpected token in directive");
3633 SMLoc SizeLoc = getLexer().getLoc();
3634 if (parseAbsoluteExpression(Size))
3637 int64_t Pow2Alignment = 0;
3638 SMLoc Pow2AlignmentLoc;
3639 if (getLexer().is(AsmToken::Comma)) {
3641 Pow2AlignmentLoc = getLexer().getLoc();
3642 if (parseAbsoluteExpression(Pow2Alignment))
3645 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3646 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3647 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3649 // If this target takes alignments in bytes (not log) validate and convert.
3650 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3651 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3652 if (!isPowerOf2_64(Pow2Alignment))
3653 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3654 Pow2Alignment = Log2_64(Pow2Alignment);
3658 if (getLexer().isNot(AsmToken::EndOfStatement))
3659 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3663 // NOTE: a size of zero for a .comm should create a undefined symbol
3664 // but a size of .lcomm creates a bss symbol of size zero.
3666 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3667 "be less than zero");
3669 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3670 // may internally end up wanting an alignment in bytes.
3671 // FIXME: Diagnose overflow.
3672 if (Pow2Alignment < 0)
3673 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3674 "alignment, can't be less than zero");
3676 if (!Sym->isUndefined())
3677 return Error(IDLoc, "invalid symbol redefinition");
3679 // Create the Symbol as a common or local common with Size and Pow2Alignment
3681 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3685 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3689 /// parseDirectiveAbort
3690 /// ::= .abort [... message ...]
3691 bool AsmParser::parseDirectiveAbort() {
3692 // FIXME: Use loc from directive.
3693 SMLoc Loc = getLexer().getLoc();
3695 StringRef Str = parseStringToEndOfStatement();
3696 if (getLexer().isNot(AsmToken::EndOfStatement))
3697 return TokError("unexpected token in '.abort' directive");
3702 Error(Loc, ".abort detected. Assembly stopping.");
3704 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3705 // FIXME: Actually abort assembly here.
3710 /// parseDirectiveInclude
3711 /// ::= .include "filename"
3712 bool AsmParser::parseDirectiveInclude() {
3713 if (getLexer().isNot(AsmToken::String))
3714 return TokError("expected string in '.include' directive");
3716 // Allow the strings to have escaped octal character sequence.
3717 std::string Filename;
3718 if (parseEscapedString(Filename))
3720 SMLoc IncludeLoc = getLexer().getLoc();
3723 if (getLexer().isNot(AsmToken::EndOfStatement))
3724 return TokError("unexpected token in '.include' directive");
3726 // Attempt to switch the lexer to the included file before consuming the end
3727 // of statement to avoid losing it when we switch.
3728 if (enterIncludeFile(Filename)) {
3729 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3736 /// parseDirectiveIncbin
3737 /// ::= .incbin "filename"
3738 bool AsmParser::parseDirectiveIncbin() {
3739 if (getLexer().isNot(AsmToken::String))
3740 return TokError("expected string in '.incbin' directive");
3742 // Allow the strings to have escaped octal character sequence.
3743 std::string Filename;
3744 if (parseEscapedString(Filename))
3746 SMLoc IncbinLoc = getLexer().getLoc();
3749 if (getLexer().isNot(AsmToken::EndOfStatement))
3750 return TokError("unexpected token in '.incbin' directive");
3752 // Attempt to process the included file.
3753 if (processIncbinFile(Filename)) {
3754 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3761 /// parseDirectiveIf
3762 /// ::= .if expression
3763 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3764 TheCondStack.push_back(TheCondState);
3765 TheCondState.TheCond = AsmCond::IfCond;
3766 if (TheCondState.Ignore) {
3767 eatToEndOfStatement();
3770 if (parseAbsoluteExpression(ExprValue))
3773 if (getLexer().isNot(AsmToken::EndOfStatement))
3774 return TokError("unexpected token in '.if' directive");
3778 TheCondState.CondMet = ExprValue;
3779 TheCondState.Ignore = !TheCondState.CondMet;
3785 /// parseDirectiveIfb
3787 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3788 TheCondStack.push_back(TheCondState);
3789 TheCondState.TheCond = AsmCond::IfCond;
3791 if (TheCondState.Ignore) {
3792 eatToEndOfStatement();
3794 StringRef Str = parseStringToEndOfStatement();
3796 if (getLexer().isNot(AsmToken::EndOfStatement))
3797 return TokError("unexpected token in '.ifb' directive");
3801 TheCondState.CondMet = ExpectBlank == Str.empty();
3802 TheCondState.Ignore = !TheCondState.CondMet;
3808 /// parseDirectiveIfc
3809 /// ::= .ifc string1, string2
3810 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3811 TheCondStack.push_back(TheCondState);
3812 TheCondState.TheCond = AsmCond::IfCond;
3814 if (TheCondState.Ignore) {
3815 eatToEndOfStatement();
3817 StringRef Str1 = parseStringToComma();
3819 if (getLexer().isNot(AsmToken::Comma))
3820 return TokError("unexpected token in '.ifc' directive");
3824 StringRef Str2 = parseStringToEndOfStatement();
3826 if (getLexer().isNot(AsmToken::EndOfStatement))
3827 return TokError("unexpected token in '.ifc' directive");
3831 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3832 TheCondState.Ignore = !TheCondState.CondMet;
3838 /// parseDirectiveIfdef
3839 /// ::= .ifdef symbol
3840 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3842 TheCondStack.push_back(TheCondState);
3843 TheCondState.TheCond = AsmCond::IfCond;
3845 if (TheCondState.Ignore) {
3846 eatToEndOfStatement();
3848 if (parseIdentifier(Name))
3849 return TokError("expected identifier after '.ifdef'");
3853 MCSymbol *Sym = getContext().LookupSymbol(Name);
3856 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3858 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3859 TheCondState.Ignore = !TheCondState.CondMet;
3865 /// parseDirectiveElseIf
3866 /// ::= .elseif expression
3867 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3868 if (TheCondState.TheCond != AsmCond::IfCond &&
3869 TheCondState.TheCond != AsmCond::ElseIfCond)
3870 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3872 TheCondState.TheCond = AsmCond::ElseIfCond;
3874 bool LastIgnoreState = false;
3875 if (!TheCondStack.empty())
3876 LastIgnoreState = TheCondStack.back().Ignore;
3877 if (LastIgnoreState || TheCondState.CondMet) {
3878 TheCondState.Ignore = true;
3879 eatToEndOfStatement();
3882 if (parseAbsoluteExpression(ExprValue))
3885 if (getLexer().isNot(AsmToken::EndOfStatement))
3886 return TokError("unexpected token in '.elseif' directive");
3889 TheCondState.CondMet = ExprValue;
3890 TheCondState.Ignore = !TheCondState.CondMet;
3896 /// parseDirectiveElse
3898 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3899 if (getLexer().isNot(AsmToken::EndOfStatement))
3900 return TokError("unexpected token in '.else' directive");
3904 if (TheCondState.TheCond != AsmCond::IfCond &&
3905 TheCondState.TheCond != AsmCond::ElseIfCond)
3906 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3908 TheCondState.TheCond = AsmCond::ElseCond;
3909 bool LastIgnoreState = false;
3910 if (!TheCondStack.empty())
3911 LastIgnoreState = TheCondStack.back().Ignore;
3912 if (LastIgnoreState || TheCondState.CondMet)
3913 TheCondState.Ignore = true;
3915 TheCondState.Ignore = false;
3920 /// parseDirectiveEnd
3922 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
3923 if (getLexer().isNot(AsmToken::EndOfStatement))
3924 return TokError("unexpected token in '.end' directive");
3928 while (Lexer.isNot(AsmToken::Eof))
3934 /// parseDirectiveEndIf
3936 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
3937 if (getLexer().isNot(AsmToken::EndOfStatement))
3938 return TokError("unexpected token in '.endif' directive");
3942 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
3943 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3945 if (!TheCondStack.empty()) {
3946 TheCondState = TheCondStack.back();
3947 TheCondStack.pop_back();
3953 void AsmParser::initializeDirectiveKindMap() {
3954 DirectiveKindMap[".set"] = DK_SET;
3955 DirectiveKindMap[".equ"] = DK_EQU;
3956 DirectiveKindMap[".equiv"] = DK_EQUIV;
3957 DirectiveKindMap[".ascii"] = DK_ASCII;
3958 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3959 DirectiveKindMap[".string"] = DK_STRING;
3960 DirectiveKindMap[".byte"] = DK_BYTE;
3961 DirectiveKindMap[".short"] = DK_SHORT;
3962 DirectiveKindMap[".value"] = DK_VALUE;
3963 DirectiveKindMap[".2byte"] = DK_2BYTE;
3964 DirectiveKindMap[".long"] = DK_LONG;
3965 DirectiveKindMap[".int"] = DK_INT;
3966 DirectiveKindMap[".4byte"] = DK_4BYTE;
3967 DirectiveKindMap[".quad"] = DK_QUAD;
3968 DirectiveKindMap[".8byte"] = DK_8BYTE;
3969 DirectiveKindMap[".octa"] = DK_OCTA;
3970 DirectiveKindMap[".single"] = DK_SINGLE;
3971 DirectiveKindMap[".float"] = DK_FLOAT;
3972 DirectiveKindMap[".double"] = DK_DOUBLE;
3973 DirectiveKindMap[".align"] = DK_ALIGN;
3974 DirectiveKindMap[".align32"] = DK_ALIGN32;
3975 DirectiveKindMap[".balign"] = DK_BALIGN;
3976 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3977 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3978 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3979 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3980 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3981 DirectiveKindMap[".org"] = DK_ORG;
3982 DirectiveKindMap[".fill"] = DK_FILL;
3983 DirectiveKindMap[".zero"] = DK_ZERO;
3984 DirectiveKindMap[".extern"] = DK_EXTERN;
3985 DirectiveKindMap[".globl"] = DK_GLOBL;
3986 DirectiveKindMap[".global"] = DK_GLOBAL;
3987 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3988 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3989 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3990 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3991 DirectiveKindMap[".reference"] = DK_REFERENCE;
3992 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3993 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3994 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3995 DirectiveKindMap[".comm"] = DK_COMM;
3996 DirectiveKindMap[".common"] = DK_COMMON;
3997 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3998 DirectiveKindMap[".abort"] = DK_ABORT;
3999 DirectiveKindMap[".include"] = DK_INCLUDE;
4000 DirectiveKindMap[".incbin"] = DK_INCBIN;
4001 DirectiveKindMap[".code16"] = DK_CODE16;
4002 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4003 DirectiveKindMap[".rept"] = DK_REPT;
4004 DirectiveKindMap[".rep"] = DK_REPT;
4005 DirectiveKindMap[".irp"] = DK_IRP;
4006 DirectiveKindMap[".irpc"] = DK_IRPC;
4007 DirectiveKindMap[".endr"] = DK_ENDR;
4008 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4009 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4010 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4011 DirectiveKindMap[".if"] = DK_IF;
4012 DirectiveKindMap[".ifb"] = DK_IFB;
4013 DirectiveKindMap[".ifnb"] = DK_IFNB;
4014 DirectiveKindMap[".ifc"] = DK_IFC;
4015 DirectiveKindMap[".ifnc"] = DK_IFNC;
4016 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4017 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4018 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4019 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4020 DirectiveKindMap[".else"] = DK_ELSE;
4021 DirectiveKindMap[".end"] = DK_END;
4022 DirectiveKindMap[".endif"] = DK_ENDIF;
4023 DirectiveKindMap[".skip"] = DK_SKIP;
4024 DirectiveKindMap[".space"] = DK_SPACE;
4025 DirectiveKindMap[".file"] = DK_FILE;
4026 DirectiveKindMap[".line"] = DK_LINE;
4027 DirectiveKindMap[".loc"] = DK_LOC;
4028 DirectiveKindMap[".stabs"] = DK_STABS;
4029 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4030 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4031 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4032 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4033 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4034 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4035 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4036 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4037 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4038 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4039 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4040 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4041 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4042 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4043 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4044 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4045 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4046 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4047 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4048 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4049 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4050 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4051 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4052 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4053 DirectiveKindMap[".macro"] = DK_MACRO;
4054 DirectiveKindMap[".endm"] = DK_ENDM;
4055 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4056 DirectiveKindMap[".purgem"] = DK_PURGEM;
4059 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4060 AsmToken EndToken, StartToken = getTok();
4062 unsigned NestLevel = 0;
4064 // Check whether we have reached the end of the file.
4065 if (getLexer().is(AsmToken::Eof)) {
4066 Error(DirectiveLoc, "no matching '.endr' in definition");
4070 if (Lexer.is(AsmToken::Identifier) &&
4071 (getTok().getIdentifier() == ".rept")) {
4075 // Otherwise, check whether we have reached the .endr.
4076 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4077 if (NestLevel == 0) {
4078 EndToken = getTok();
4080 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4081 TokError("unexpected token in '.endr' directive");
4089 // Otherwise, scan till the end of the statement.
4090 eatToEndOfStatement();
4093 const char *BodyStart = StartToken.getLoc().getPointer();
4094 const char *BodyEnd = EndToken.getLoc().getPointer();
4095 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4097 // We Are Anonymous.
4098 MacroLikeBodies.push_back(MCAsmMacro(StringRef(), Body, None));
4099 return &MacroLikeBodies.back();
4102 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4103 raw_svector_ostream &OS) {
4106 MemoryBuffer *Instantiation =
4107 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4109 // Create the macro instantiation object and add to the current macro
4110 // instantiation stack.
4111 MacroInstantiation *MI = new MacroInstantiation(
4112 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
4113 ActiveMacros.push_back(MI);
4115 // Jump to the macro instantiation and prime the lexer.
4116 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
4117 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
4121 /// parseDirectiveRept
4122 /// ::= .rep | .rept count
4123 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4124 const MCExpr *CountExpr;
4125 SMLoc CountLoc = getTok().getLoc();
4126 if (parseExpression(CountExpr))
4130 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4131 eatToEndOfStatement();
4132 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4136 return Error(CountLoc, "Count is negative");
4138 if (Lexer.isNot(AsmToken::EndOfStatement))
4139 return TokError("unexpected token in '" + Dir + "' directive");
4141 // Eat the end of statement.
4144 // Lex the rept definition.
4145 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4149 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4150 // to hold the macro body with substitutions.
4151 SmallString<256> Buf;
4152 raw_svector_ostream OS(Buf);
4154 if (expandMacro(OS, M->Body, None, None, getTok().getLoc()))
4157 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4162 /// parseDirectiveIrp
4163 /// ::= .irp symbol,values
4164 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4165 MCAsmMacroParameter Parameter;
4167 if (parseIdentifier(Parameter.Name))
4168 return TokError("expected identifier in '.irp' directive");
4170 if (Lexer.isNot(AsmToken::Comma))
4171 return TokError("expected comma in '.irp' directive");
4175 MCAsmMacroArguments A;
4176 if (parseMacroArguments(0, A))
4179 // Eat the end of statement.
4182 // Lex the irp definition.
4183 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4187 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4188 // to hold the macro body with substitutions.
4189 SmallString<256> Buf;
4190 raw_svector_ostream OS(Buf);
4192 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4193 if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc()))
4197 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4202 /// parseDirectiveIrpc
4203 /// ::= .irpc symbol,values
4204 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4205 MCAsmMacroParameter Parameter;
4207 if (parseIdentifier(Parameter.Name))
4208 return TokError("expected identifier in '.irpc' directive");
4210 if (Lexer.isNot(AsmToken::Comma))
4211 return TokError("expected comma in '.irpc' directive");
4215 MCAsmMacroArguments A;
4216 if (parseMacroArguments(0, A))
4219 if (A.size() != 1 || A.front().size() != 1)
4220 return TokError("unexpected token in '.irpc' directive");
4222 // Eat the end of statement.
4225 // Lex the irpc definition.
4226 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4230 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4231 // to hold the macro body with substitutions.
4232 SmallString<256> Buf;
4233 raw_svector_ostream OS(Buf);
4235 StringRef Values = A.front().front().getString();
4236 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4237 MCAsmMacroArgument Arg;
4238 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4240 if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc()))
4244 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4249 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4250 if (ActiveMacros.empty())
4251 return TokError("unmatched '.endr' directive");
4253 // The only .repl that should get here are the ones created by
4254 // instantiateMacroLikeBody.
4255 assert(getLexer().is(AsmToken::EndOfStatement));
4261 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4263 const MCExpr *Value;
4264 SMLoc ExprLoc = getLexer().getLoc();
4265 if (parseExpression(Value))
4267 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4269 return Error(ExprLoc, "unexpected expression in _emit");
4270 uint64_t IntValue = MCE->getValue();
4271 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4272 return Error(ExprLoc, "literal value out of range for directive");
4274 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4278 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4279 const MCExpr *Value;
4280 SMLoc ExprLoc = getLexer().getLoc();
4281 if (parseExpression(Value))
4283 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4285 return Error(ExprLoc, "unexpected expression in align");
4286 uint64_t IntValue = MCE->getValue();
4287 if (!isPowerOf2_64(IntValue))
4288 return Error(ExprLoc, "literal value not a power of two greater then zero");
4290 Info.AsmRewrites->push_back(
4291 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4295 // We are comparing pointers, but the pointers are relative to a single string.
4296 // Thus, this should always be deterministic.
4297 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4298 const AsmRewrite *AsmRewriteB) {
4299 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4301 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4304 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4305 // rewrite to the same location. Make sure the SizeDirective rewrite is
4306 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4307 // ensures the sort algorithm is stable.
4308 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4309 AsmRewritePrecedence[AsmRewriteB->Kind])
4312 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4313 AsmRewritePrecedence[AsmRewriteB->Kind])
4315 llvm_unreachable("Unstable rewrite sort.");
4318 bool AsmParser::parseMSInlineAsm(
4319 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4320 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4321 SmallVectorImpl<std::string> &Constraints,
4322 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4323 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4324 SmallVector<void *, 4> InputDecls;
4325 SmallVector<void *, 4> OutputDecls;
4326 SmallVector<bool, 4> InputDeclsAddressOf;
4327 SmallVector<bool, 4> OutputDeclsAddressOf;
4328 SmallVector<std::string, 4> InputConstraints;
4329 SmallVector<std::string, 4> OutputConstraints;
4330 SmallVector<unsigned, 4> ClobberRegs;
4332 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4337 // While we have input, parse each statement.
4338 unsigned InputIdx = 0;
4339 unsigned OutputIdx = 0;
4340 while (getLexer().isNot(AsmToken::Eof)) {
4341 ParseStatementInfo Info(&AsmStrRewrites);
4342 if (parseStatement(Info))
4345 if (Info.ParseError)
4348 if (Info.Opcode == ~0U)
4351 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4353 // Build the list of clobbers, outputs and inputs.
4354 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4355 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4358 if (Operand->isImm())
4361 // Register operand.
4362 if (Operand->isReg() && !Operand->needAddressOf()) {
4363 unsigned NumDefs = Desc.getNumDefs();
4365 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4366 ClobberRegs.push_back(Operand->getReg());
4370 // Expr/Input or Output.
4371 StringRef SymName = Operand->getSymName();
4372 if (SymName.empty())
4375 void *OpDecl = Operand->getOpDecl();
4379 bool isOutput = (i == 1) && Desc.mayStore();
4380 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4383 OutputDecls.push_back(OpDecl);
4384 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4385 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4386 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4388 InputDecls.push_back(OpDecl);
4389 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4390 InputConstraints.push_back(Operand->getConstraint().str());
4391 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4395 // Consider implicit defs to be clobbers. Think of cpuid and push.
4396 const uint16_t *ImpDefs = Desc.getImplicitDefs();
4397 for (unsigned I = 0, E = Desc.getNumImplicitDefs(); I != E; ++I)
4398 ClobberRegs.push_back(ImpDefs[I]);
4401 // Set the number of Outputs and Inputs.
4402 NumOutputs = OutputDecls.size();
4403 NumInputs = InputDecls.size();
4405 // Set the unique clobbers.
4406 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4407 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4409 Clobbers.assign(ClobberRegs.size(), std::string());
4410 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4411 raw_string_ostream OS(Clobbers[I]);
4412 IP->printRegName(OS, ClobberRegs[I]);
4415 // Merge the various outputs and inputs. Output are expected first.
4416 if (NumOutputs || NumInputs) {
4417 unsigned NumExprs = NumOutputs + NumInputs;
4418 OpDecls.resize(NumExprs);
4419 Constraints.resize(NumExprs);
4420 for (unsigned i = 0; i < NumOutputs; ++i) {
4421 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4422 Constraints[i] = OutputConstraints[i];
4424 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4425 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4426 Constraints[j] = InputConstraints[i];
4430 // Build the IR assembly string.
4431 std::string AsmStringIR;
4432 raw_string_ostream OS(AsmStringIR);
4433 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4434 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4435 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4436 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4437 E = AsmStrRewrites.end();
4439 AsmRewriteKind Kind = (*I).Kind;
4440 if (Kind == AOK_Delete)
4443 const char *Loc = (*I).Loc.getPointer();
4444 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4446 // Emit everything up to the immediate/expression.
4447 unsigned Len = Loc - AsmStart;
4449 OS << StringRef(AsmStart, Len);
4451 // Skip the original expression.
4452 if (Kind == AOK_Skip) {
4453 AsmStart = Loc + (*I).Len;
4457 unsigned AdditionalSkip = 0;
4458 // Rewrite expressions in $N notation.
4463 OS << "$$" << (*I).Val;
4469 OS << '$' << InputIdx++;
4472 OS << '$' << OutputIdx++;
4474 case AOK_SizeDirective:
4477 case 8: OS << "byte ptr "; break;
4478 case 16: OS << "word ptr "; break;
4479 case 32: OS << "dword ptr "; break;
4480 case 64: OS << "qword ptr "; break;
4481 case 80: OS << "xword ptr "; break;
4482 case 128: OS << "xmmword ptr "; break;
4483 case 256: OS << "ymmword ptr "; break;
4490 unsigned Val = (*I).Val;
4491 OS << ".align " << Val;
4493 // Skip the original immediate.
4494 assert(Val < 10 && "Expected alignment less then 2^10.");
4495 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4498 case AOK_DotOperator:
4503 // Skip the original expression.
4504 AsmStart = Loc + (*I).Len + AdditionalSkip;
4507 // Emit the remainder of the asm string.
4508 if (AsmStart != AsmEnd)
4509 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4511 AsmString = OS.str();
4515 /// \brief Create an MCAsmParser instance.
4516 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4517 MCStreamer &Out, const MCAsmInfo &MAI) {
4518 return new AsmParser(SM, C, Out, MAI);