1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCDwarf.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInstPrinter.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCParser/AsmCond.h"
25 #include "llvm/MC/MCParser/AsmLexer.h"
26 #include "llvm/MC/MCParser/MCAsmParser.h"
27 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSectionMachO.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/MC/MCTargetAsmParser.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/raw_ostream.h"
46 FatalAssemblerWarnings("fatal-assembler-warnings",
47 cl::desc("Consider warnings as error"));
49 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
53 /// \brief Helper class for tracking macro definitions.
54 typedef std::vector<AsmToken> MacroArgument;
55 typedef std::vector<MacroArgument> MacroArguments;
56 typedef std::pair<StringRef, MacroArgument> MacroParameter;
57 typedef std::vector<MacroParameter> MacroParameters;
62 MacroParameters Parameters;
65 Macro(StringRef N, StringRef B, const MacroParameters &P) :
66 Name(N), Body(B), Parameters(P) {}
69 /// \brief Helper class for storing information about an active macro
71 struct MacroInstantiation {
72 /// The macro being instantiated.
73 const Macro *TheMacro;
75 /// The macro instantiation with substitutions.
76 MemoryBuffer *Instantiation;
78 /// The location of the instantiation.
79 SMLoc InstantiationLoc;
81 /// The buffer where parsing should resume upon instantiation completion.
84 /// The location where parsing should resume upon instantiation completion.
88 MacroInstantiation(const Macro *M, SMLoc IL, int EB, SMLoc EL,
93 struct ParseStatementInfo {
94 /// ParsedOperands - The parsed operands from the last parsed statement.
95 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
97 /// Opcode - The opcode from the last parsed instruction.
100 /// Error - Was there an error parsing the inline assembly?
103 SmallVectorImpl<AsmRewrite> *AsmRewrites;
105 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
106 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
107 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
109 ~ParseStatementInfo() {
110 // Free any parsed operands.
111 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
112 delete ParsedOperands[i];
113 ParsedOperands.clear();
117 /// \brief The concrete assembly parser instance.
118 class AsmParser : public MCAsmParser {
119 friend class GenericAsmParser;
121 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
122 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
127 const MCAsmInfo &MAI;
129 SourceMgr::DiagHandlerTy SavedDiagHandler;
130 void *SavedDiagContext;
131 MCAsmParserExtension *GenericParser;
132 MCAsmParserExtension *PlatformParser;
134 /// This is the current buffer index we're lexing from as managed by the
135 /// SourceMgr object.
138 AsmCond TheCondState;
139 std::vector<AsmCond> TheCondStack;
141 /// DirectiveMap - This is a table handlers for directives. Each handler is
142 /// invoked after the directive identifier is read and is responsible for
143 /// parsing and validating the rest of the directive. The handler is passed
144 /// in the directive name and the location of the directive keyword.
145 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
147 /// MacroMap - Map of currently defined macros.
148 StringMap<Macro*> MacroMap;
150 /// ActiveMacros - Stack of active macro instantiations.
151 std::vector<MacroInstantiation*> ActiveMacros;
153 /// Boolean tracking whether macro substitution is enabled.
154 unsigned MacrosEnabled : 1;
156 /// Flag tracking whether any errors have been encountered.
157 unsigned HadError : 1;
159 /// The values from the last parsed cpp hash file line comment if any.
160 StringRef CppHashFilename;
161 int64_t CppHashLineNumber;
165 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
166 unsigned AssemblerDialect;
168 /// IsDarwin - is Darwin compatibility enabled?
171 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
172 bool ParsingInlineAsm;
175 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
176 const MCAsmInfo &MAI);
177 virtual ~AsmParser();
179 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
181 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
183 DirectiveHandler Handler) {
184 DirectiveMap[Directive] = std::make_pair(Object, Handler);
188 /// @name MCAsmParser Interface
191 virtual SourceMgr &getSourceManager() { return SrcMgr; }
192 virtual MCAsmLexer &getLexer() { return Lexer; }
193 virtual MCContext &getContext() { return Ctx; }
194 virtual MCStreamer &getStreamer() { return Out; }
195 virtual unsigned getAssemblerDialect() {
196 if (AssemblerDialect == ~0U)
197 return MAI.getAssemblerDialect();
199 return AssemblerDialect;
201 virtual void setAssemblerDialect(unsigned i) {
202 AssemblerDialect = i;
205 virtual bool Warning(SMLoc L, const Twine &Msg,
206 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
207 virtual bool Error(SMLoc L, const Twine &Msg,
208 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
210 virtual const AsmToken &Lex();
212 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
213 bool isParsingInlineAsm() { return ParsingInlineAsm; }
215 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
216 unsigned &NumOutputs, unsigned &NumInputs,
217 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
218 SmallVectorImpl<std::string> &Constraints,
219 SmallVectorImpl<std::string> &Clobbers,
220 const MCInstrInfo *MII,
221 const MCInstPrinter *IP,
222 MCAsmParserSemaCallback &SI);
224 bool ParseExpression(const MCExpr *&Res);
225 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
226 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
227 virtual bool ParseAbsoluteExpression(int64_t &Res);
232 void CheckForValidSection();
234 bool ParseStatement(ParseStatementInfo &Info);
235 void EatToEndOfLine();
236 bool ParseCppHashLineFilenameComment(const SMLoc &L);
238 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
239 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
240 const MacroParameters &Parameters,
241 const MacroArguments &A,
243 void HandleMacroExit();
245 void PrintMacroInstantiations();
246 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
247 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
248 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
250 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
252 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
253 bool EnterIncludeFile(const std::string &Filename);
254 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
255 /// This returns true on failure.
256 bool ProcessIncbinFile(const std::string &Filename);
258 /// \brief Reset the current lexer position to that given by \p Loc. The
259 /// current token is not set; clients should ensure Lex() is called
262 /// \param InBuffer If not -1, should be the known buffer id that contains the
264 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
266 virtual void EatToEndOfStatement();
268 bool ParseMacroArgument(MacroArgument &MA,
269 AsmToken::TokenKind &ArgumentDelimiter);
270 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
272 /// \brief Parse up to the end of statement and a return the contents from the
273 /// current token until the end of the statement; the current token on exit
274 /// will be either the EndOfStatement or EOF.
275 virtual StringRef ParseStringToEndOfStatement();
277 /// \brief Parse until the end of a statement or a comma is encountered,
278 /// return the contents from the current token up to the end or comma.
279 StringRef ParseStringToComma();
281 bool ParseAssignment(StringRef Name, bool allow_redef,
282 bool NoDeadStrip = false);
284 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
285 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
286 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
287 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
289 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
290 /// and set \p Res to the identifier contents.
291 virtual bool ParseIdentifier(StringRef &Res);
293 // Directive Parsing.
296 DK_NO_DIRECTIVE, // Placeholder
297 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
298 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
299 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
300 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL,
301 DK_SPACE, DK_SKIP, DK_ENDR,
302 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
303 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
304 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
305 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
306 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
307 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
308 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
309 DK_ELSEIF, DK_ELSE, DK_ENDIF
312 StringMap<DirectiveKind> DirectiveKindMapping;
314 // ".ascii", ".asciz", ".string"
315 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
316 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
317 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
318 bool ParseDirectiveFill(); // ".fill"
319 bool ParseDirectiveSpace(); // ".space"
320 bool ParseDirectiveZero(); // ".zero"
321 // ".set", ".equ", ".equiv"
322 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
323 bool ParseDirectiveOrg(); // ".org"
324 // ".align{,32}", ".p2align{,w,l}"
325 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
327 // ".bundle_align_mode"
328 bool ParseDirectiveBundleAlignMode();
330 bool ParseDirectiveBundleLock();
332 bool ParseDirectiveBundleUnlock();
334 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
335 /// accepts a single symbol (which should be a label or an external).
336 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
338 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
340 bool ParseDirectiveAbort(); // ".abort"
341 bool ParseDirectiveInclude(); // ".include"
342 bool ParseDirectiveIncbin(); // ".incbin"
344 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
345 // ".ifb" or ".ifnb", depending on ExpectBlank.
346 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
347 // ".ifc" or ".ifnc", depending on ExpectEqual.
348 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
349 // ".ifdef" or ".ifndef", depending on expect_defined
350 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
351 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
352 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
353 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
355 /// ParseEscapedString - Parse the current token as a string which may include
356 /// escaped characters and return the string contents.
357 bool ParseEscapedString(std::string &Data);
359 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
360 MCSymbolRefExpr::VariantKind Variant);
362 // Macro-like directives
363 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
364 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
365 raw_svector_ostream &OS);
366 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
367 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
368 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
369 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
372 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
374 void initializeDirectiveKindMapping();
377 /// \brief Generic implementation of directive handling, etc. which is shared
378 /// (or the default, at least) for all assembler parsers.
379 class GenericAsmParser : public MCAsmParserExtension {
380 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
381 void AddDirectiveHandler(StringRef Directive) {
382 getParser().AddDirectiveHandler(this, Directive,
383 HandleDirective<GenericAsmParser, Handler>);
386 GenericAsmParser() {}
388 AsmParser &getParser() {
389 return (AsmParser&) this->MCAsmParserExtension::getParser();
392 virtual void Initialize(MCAsmParser &Parser) {
393 // Call the base implementation.
394 this->MCAsmParserExtension::Initialize(Parser);
396 // Debugging directives.
397 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
398 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
399 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
400 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
403 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
405 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
407 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
409 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
411 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
412 ".cfi_def_cfa_offset");
413 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
414 ".cfi_adjust_cfa_offset");
415 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
416 ".cfi_def_cfa_register");
417 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
419 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
422 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
424 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
426 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
428 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
430 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
432 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
434 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
436 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
438 &GenericAsmParser::ParseDirectiveCFIUndefined>(".cfi_undefined");
440 &GenericAsmParser::ParseDirectiveCFIRegister>(".cfi_register");
443 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
445 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
447 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
448 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
449 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
450 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
452 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
453 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
456 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
458 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
459 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
460 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
461 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
462 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
463 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
464 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
465 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
466 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
467 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
468 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
469 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
470 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
471 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
472 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
473 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
474 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
475 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
476 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
477 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
478 bool ParseDirectiveCFIUndefined(StringRef, SMLoc DirectiveLoc);
479 bool ParseDirectiveCFIRegister(StringRef, SMLoc DirectiveLoc);
481 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
482 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
483 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
484 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
486 bool ParseDirectiveLEB128(StringRef, SMLoc);
493 extern MCAsmParserExtension *createDarwinAsmParser();
494 extern MCAsmParserExtension *createELFAsmParser();
495 extern MCAsmParserExtension *createCOFFAsmParser();
499 enum { DEFAULT_ADDRSPACE = 0 };
501 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
502 MCStreamer &_Out, const MCAsmInfo &_MAI)
503 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
504 GenericParser(new GenericAsmParser), PlatformParser(0),
505 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
506 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
507 // Save the old handler.
508 SavedDiagHandler = SrcMgr.getDiagHandler();
509 SavedDiagContext = SrcMgr.getDiagContext();
510 // Set our own handler which calls the saved handler.
511 SrcMgr.setDiagHandler(DiagHandler, this);
512 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
514 // Initialize the generic parser.
515 GenericParser->Initialize(*this);
517 // Initialize the platform / file format parser.
519 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
521 if (_MAI.hasMicrosoftFastStdCallMangling()) {
522 PlatformParser = createCOFFAsmParser();
523 PlatformParser->Initialize(*this);
524 } else if (_MAI.hasSubsectionsViaSymbols()) {
525 PlatformParser = createDarwinAsmParser();
526 PlatformParser->Initialize(*this);
529 PlatformParser = createELFAsmParser();
530 PlatformParser->Initialize(*this);
533 initializeDirectiveKindMapping();
536 AsmParser::~AsmParser() {
537 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
539 // Destroy any macros.
540 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
541 ie = MacroMap.end(); it != ie; ++it)
542 delete it->getValue();
544 delete PlatformParser;
545 delete GenericParser;
548 void AsmParser::PrintMacroInstantiations() {
549 // Print the active macro instantiation stack.
550 for (std::vector<MacroInstantiation*>::const_reverse_iterator
551 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
552 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
553 "while in macro instantiation");
556 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
557 if (FatalAssemblerWarnings)
558 return Error(L, Msg, Ranges);
559 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
560 PrintMacroInstantiations();
564 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
566 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
567 PrintMacroInstantiations();
571 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
572 std::string IncludedFile;
573 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
579 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
584 /// Process the specified .incbin file by seaching for it in the include paths
585 /// then just emitting the byte contents of the file to the streamer. This
586 /// returns true on failure.
587 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
588 std::string IncludedFile;
589 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
593 // Pick up the bytes from the file and emit them.
594 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
599 void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
600 if (InBuffer != -1) {
601 CurBuffer = InBuffer;
603 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
605 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
608 const AsmToken &AsmParser::Lex() {
609 const AsmToken *tok = &Lexer.Lex();
611 if (tok->is(AsmToken::Eof)) {
612 // If this is the end of an included file, pop the parent file off the
614 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
615 if (ParentIncludeLoc != SMLoc()) {
616 JumpToLoc(ParentIncludeLoc);
621 if (tok->is(AsmToken::Error))
622 Error(Lexer.getErrLoc(), Lexer.getErr());
627 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
628 // Create the initial section, if requested.
629 if (!NoInitialTextSection)
636 AsmCond StartingCondState = TheCondState;
638 // If we are generating dwarf for assembly source files save the initial text
639 // section and generate a .file directive.
640 if (getContext().getGenDwarfForAssembly()) {
641 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
642 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
643 getStreamer().EmitLabel(SectionStartSym);
644 getContext().setGenDwarfSectionStartSym(SectionStartSym);
645 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
647 getContext().getMainFileName());
650 // While we have input, parse each statement.
651 while (Lexer.isNot(AsmToken::Eof)) {
652 ParseStatementInfo Info;
653 if (!ParseStatement(Info)) continue;
655 // We had an error, validate that one was emitted and recover by skipping to
657 assert(HadError && "Parse statement returned an error, but none emitted!");
658 EatToEndOfStatement();
661 if (TheCondState.TheCond != StartingCondState.TheCond ||
662 TheCondState.Ignore != StartingCondState.Ignore)
663 return TokError("unmatched .ifs or .elses");
665 // Check to see there are no empty DwarfFile slots.
666 const std::vector<MCDwarfFile *> &MCDwarfFiles =
667 getContext().getMCDwarfFiles();
668 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
669 if (!MCDwarfFiles[i])
670 TokError("unassigned file number: " + Twine(i) + " for .file directives");
673 // Check to see that all assembler local symbols were actually defined.
674 // Targets that don't do subsections via symbols may not want this, though,
675 // so conservatively exclude them. Only do this if we're finalizing, though,
676 // as otherwise we won't necessarilly have seen everything yet.
677 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
678 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
679 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
682 MCSymbol *Sym = i->getValue();
683 // Variable symbols may not be marked as defined, so check those
684 // explicitly. If we know it's a variable, we have a definition for
685 // the purposes of this check.
686 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
687 // FIXME: We would really like to refer back to where the symbol was
688 // first referenced for a source location. We need to add something
689 // to track that. Currently, we just point to the end of the file.
690 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
691 "assembler local symbol '" + Sym->getName() +
697 // Finalize the output stream if there are no errors and if the client wants
699 if (!HadError && !NoFinalize)
705 void AsmParser::CheckForValidSection() {
706 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
707 TokError("expected section directive before assembly directive");
708 Out.SwitchSection(Ctx.getMachOSection(
710 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
711 0, SectionKind::getText()));
715 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
716 void AsmParser::EatToEndOfStatement() {
717 while (Lexer.isNot(AsmToken::EndOfStatement) &&
718 Lexer.isNot(AsmToken::Eof))
722 if (Lexer.is(AsmToken::EndOfStatement))
726 StringRef AsmParser::ParseStringToEndOfStatement() {
727 const char *Start = getTok().getLoc().getPointer();
729 while (Lexer.isNot(AsmToken::EndOfStatement) &&
730 Lexer.isNot(AsmToken::Eof))
733 const char *End = getTok().getLoc().getPointer();
734 return StringRef(Start, End - Start);
737 StringRef AsmParser::ParseStringToComma() {
738 const char *Start = getTok().getLoc().getPointer();
740 while (Lexer.isNot(AsmToken::EndOfStatement) &&
741 Lexer.isNot(AsmToken::Comma) &&
742 Lexer.isNot(AsmToken::Eof))
745 const char *End = getTok().getLoc().getPointer();
746 return StringRef(Start, End - Start);
749 /// ParseParenExpr - Parse a paren expression and return it.
750 /// NOTE: This assumes the leading '(' has already been consumed.
752 /// parenexpr ::= expr)
754 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
755 if (ParseExpression(Res)) return true;
756 if (Lexer.isNot(AsmToken::RParen))
757 return TokError("expected ')' in parentheses expression");
758 EndLoc = Lexer.getTok().getEndLoc();
763 /// ParseBracketExpr - Parse a bracket expression and return it.
764 /// NOTE: This assumes the leading '[' has already been consumed.
766 /// bracketexpr ::= expr]
768 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
769 if (ParseExpression(Res)) return true;
770 if (Lexer.isNot(AsmToken::RBrac))
771 return TokError("expected ']' in brackets expression");
772 EndLoc = Lexer.getTok().getEndLoc();
777 /// ParsePrimaryExpr - Parse a primary expression and return it.
778 /// primaryexpr ::= (parenexpr
779 /// primaryexpr ::= symbol
780 /// primaryexpr ::= number
781 /// primaryexpr ::= '.'
782 /// primaryexpr ::= ~,+,- primaryexpr
783 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
784 switch (Lexer.getKind()) {
786 return TokError("unknown token in expression");
787 // If we have an error assume that we've already handled it.
788 case AsmToken::Error:
790 case AsmToken::Exclaim:
791 Lex(); // Eat the operator.
792 if (ParsePrimaryExpr(Res, EndLoc))
794 Res = MCUnaryExpr::CreateLNot(Res, getContext());
796 case AsmToken::Dollar:
797 case AsmToken::String:
798 case AsmToken::Identifier: {
799 StringRef Identifier;
800 if (ParseIdentifier(Identifier))
803 EndLoc = SMLoc::getFromPointer(Identifier.end());
805 // This is a symbol reference.
806 std::pair<StringRef, StringRef> Split = Identifier.split('@');
807 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
809 // Lookup the symbol variant if used.
810 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
811 if (Split.first.size() != Identifier.size()) {
812 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
813 if (Variant == MCSymbolRefExpr::VK_Invalid) {
814 Variant = MCSymbolRefExpr::VK_None;
815 return TokError("invalid variant '" + Split.second + "'");
819 // If this is an absolute variable reference, substitute it now to preserve
820 // semantics in the face of reassignment.
821 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
823 return Error(EndLoc, "unexpected modifier on variable reference");
825 Res = Sym->getVariableValue();
829 // Otherwise create a symbol ref.
830 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
833 case AsmToken::Integer: {
834 SMLoc Loc = getTok().getLoc();
835 int64_t IntVal = getTok().getIntVal();
836 Res = MCConstantExpr::Create(IntVal, getContext());
837 EndLoc = Lexer.getTok().getEndLoc();
839 // Look for 'b' or 'f' following an Integer as a directional label
840 if (Lexer.getKind() == AsmToken::Identifier) {
841 StringRef IDVal = getTok().getString();
842 if (IDVal == "f" || IDVal == "b"){
843 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
844 IDVal == "f" ? 1 : 0);
845 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
847 if (IDVal == "b" && Sym->isUndefined())
848 return Error(Loc, "invalid reference to undefined symbol");
849 EndLoc = Lexer.getTok().getEndLoc();
850 Lex(); // Eat identifier.
855 case AsmToken::Real: {
856 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
857 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
858 Res = MCConstantExpr::Create(IntVal, getContext());
859 EndLoc = Lexer.getTok().getEndLoc();
863 case AsmToken::Dot: {
864 // This is a '.' reference, which references the current PC. Emit a
865 // temporary label to the streamer and refer to it.
866 MCSymbol *Sym = Ctx.CreateTempSymbol();
868 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
869 EndLoc = Lexer.getTok().getEndLoc();
870 Lex(); // Eat identifier.
873 case AsmToken::LParen:
874 Lex(); // Eat the '('.
875 return ParseParenExpr(Res, EndLoc);
876 case AsmToken::LBrac:
877 if (!PlatformParser->HasBracketExpressions())
878 return TokError("brackets expression not supported on this target");
879 Lex(); // Eat the '['.
880 return ParseBracketExpr(Res, EndLoc);
881 case AsmToken::Minus:
882 Lex(); // Eat the operator.
883 if (ParsePrimaryExpr(Res, EndLoc))
885 Res = MCUnaryExpr::CreateMinus(Res, getContext());
888 Lex(); // Eat the operator.
889 if (ParsePrimaryExpr(Res, EndLoc))
891 Res = MCUnaryExpr::CreatePlus(Res, getContext());
893 case AsmToken::Tilde:
894 Lex(); // Eat the operator.
895 if (ParsePrimaryExpr(Res, EndLoc))
897 Res = MCUnaryExpr::CreateNot(Res, getContext());
902 bool AsmParser::ParseExpression(const MCExpr *&Res) {
904 return ParseExpression(Res, EndLoc);
908 AsmParser::ApplyModifierToExpr(const MCExpr *E,
909 MCSymbolRefExpr::VariantKind Variant) {
910 // Recurse over the given expression, rebuilding it to apply the given variant
911 // if there is exactly one symbol.
912 switch (E->getKind()) {
914 case MCExpr::Constant:
917 case MCExpr::SymbolRef: {
918 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
920 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
921 TokError("invalid variant on expression '" +
922 getTok().getIdentifier() + "' (already modified)");
926 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
929 case MCExpr::Unary: {
930 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
931 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
934 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
937 case MCExpr::Binary: {
938 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
939 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
940 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
945 if (!LHS) LHS = BE->getLHS();
946 if (!RHS) RHS = BE->getRHS();
948 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
952 llvm_unreachable("Invalid expression kind!");
955 /// ParseExpression - Parse an expression and return it.
957 /// expr ::= expr &&,|| expr -> lowest.
958 /// expr ::= expr |,^,&,! expr
959 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
960 /// expr ::= expr <<,>> expr
961 /// expr ::= expr +,- expr
962 /// expr ::= expr *,/,% expr -> highest.
963 /// expr ::= primaryexpr
965 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
966 // Parse the expression.
968 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
971 // As a special case, we support 'a op b @ modifier' by rewriting the
972 // expression to include the modifier. This is inefficient, but in general we
973 // expect users to use 'a@modifier op b'.
974 if (Lexer.getKind() == AsmToken::At) {
977 if (Lexer.isNot(AsmToken::Identifier))
978 return TokError("unexpected symbol modifier following '@'");
980 MCSymbolRefExpr::VariantKind Variant =
981 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
982 if (Variant == MCSymbolRefExpr::VK_Invalid)
983 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
985 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
987 return TokError("invalid modifier '" + getTok().getIdentifier() +
988 "' (no symbols present)");
995 // Try to constant fold it up front, if possible.
997 if (Res->EvaluateAsAbsolute(Value))
998 Res = MCConstantExpr::Create(Value, getContext());
1003 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1005 return ParseParenExpr(Res, EndLoc) ||
1006 ParseBinOpRHS(1, Res, EndLoc);
1009 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
1012 SMLoc StartLoc = Lexer.getLoc();
1013 if (ParseExpression(Expr))
1016 if (!Expr->EvaluateAsAbsolute(Res))
1017 return Error(StartLoc, "expected absolute expression");
1022 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1023 MCBinaryExpr::Opcode &Kind) {
1026 return 0; // not a binop.
1028 // Lowest Precedence: &&, ||
1029 case AsmToken::AmpAmp:
1030 Kind = MCBinaryExpr::LAnd;
1032 case AsmToken::PipePipe:
1033 Kind = MCBinaryExpr::LOr;
1037 // Low Precedence: |, &, ^
1039 // FIXME: gas seems to support '!' as an infix operator?
1040 case AsmToken::Pipe:
1041 Kind = MCBinaryExpr::Or;
1043 case AsmToken::Caret:
1044 Kind = MCBinaryExpr::Xor;
1047 Kind = MCBinaryExpr::And;
1050 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1051 case AsmToken::EqualEqual:
1052 Kind = MCBinaryExpr::EQ;
1054 case AsmToken::ExclaimEqual:
1055 case AsmToken::LessGreater:
1056 Kind = MCBinaryExpr::NE;
1058 case AsmToken::Less:
1059 Kind = MCBinaryExpr::LT;
1061 case AsmToken::LessEqual:
1062 Kind = MCBinaryExpr::LTE;
1064 case AsmToken::Greater:
1065 Kind = MCBinaryExpr::GT;
1067 case AsmToken::GreaterEqual:
1068 Kind = MCBinaryExpr::GTE;
1071 // Intermediate Precedence: <<, >>
1072 case AsmToken::LessLess:
1073 Kind = MCBinaryExpr::Shl;
1075 case AsmToken::GreaterGreater:
1076 Kind = MCBinaryExpr::Shr;
1079 // High Intermediate Precedence: +, -
1080 case AsmToken::Plus:
1081 Kind = MCBinaryExpr::Add;
1083 case AsmToken::Minus:
1084 Kind = MCBinaryExpr::Sub;
1087 // Highest Precedence: *, /, %
1088 case AsmToken::Star:
1089 Kind = MCBinaryExpr::Mul;
1091 case AsmToken::Slash:
1092 Kind = MCBinaryExpr::Div;
1094 case AsmToken::Percent:
1095 Kind = MCBinaryExpr::Mod;
1101 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1102 /// Res contains the LHS of the expression on input.
1103 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1106 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1107 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1109 // If the next token is lower precedence than we are allowed to eat, return
1110 // successfully with what we ate already.
1111 if (TokPrec < Precedence)
1116 // Eat the next primary expression.
1118 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1120 // If BinOp binds less tightly with RHS than the operator after RHS, let
1121 // the pending operator take RHS as its LHS.
1122 MCBinaryExpr::Opcode Dummy;
1123 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1124 if (TokPrec < NextTokPrec) {
1125 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1128 // Merge LHS and RHS according to operator.
1129 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1134 /// ::= EndOfStatement
1135 /// ::= Label* Directive ...Operands... EndOfStatement
1136 /// ::= Label* Identifier OperandList* EndOfStatement
1137 bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
1138 if (Lexer.is(AsmToken::EndOfStatement)) {
1144 // Statements always start with an identifier or are a full line comment.
1145 AsmToken ID = getTok();
1146 SMLoc IDLoc = ID.getLoc();
1148 int64_t LocalLabelVal = -1;
1149 // A full line comment is a '#' as the first token.
1150 if (Lexer.is(AsmToken::Hash))
1151 return ParseCppHashLineFilenameComment(IDLoc);
1153 // Allow an integer followed by a ':' as a directional local label.
1154 if (Lexer.is(AsmToken::Integer)) {
1155 LocalLabelVal = getTok().getIntVal();
1156 if (LocalLabelVal < 0) {
1157 if (!TheCondState.Ignore)
1158 return TokError("unexpected token at start of statement");
1162 IDVal = getTok().getString();
1163 Lex(); // Consume the integer token to be used as an identifier token.
1164 if (Lexer.getKind() != AsmToken::Colon) {
1165 if (!TheCondState.Ignore)
1166 return TokError("unexpected token at start of statement");
1170 } else if (Lexer.is(AsmToken::Dot)) {
1171 // Treat '.' as a valid identifier in this context.
1175 } else if (ParseIdentifier(IDVal)) {
1176 if (!TheCondState.Ignore)
1177 return TokError("unexpected token at start of statement");
1181 // Handle conditional assembly here before checking for skipping. We
1182 // have to do this so that .endif isn't skipped in a ".if 0" block for
1184 StringMap<DirectiveKind>::const_iterator DirKindIt =
1185 DirectiveKindMapping.find(IDVal);
1186 DirectiveKind DirKind =
1187 (DirKindIt == DirectiveKindMapping.end()) ? DK_NO_DIRECTIVE :
1188 DirKindIt->getValue();
1193 return ParseDirectiveIf(IDLoc);
1195 return ParseDirectiveIfb(IDLoc, true);
1197 return ParseDirectiveIfb(IDLoc, false);
1199 return ParseDirectiveIfc(IDLoc, true);
1201 return ParseDirectiveIfc(IDLoc, false);
1203 return ParseDirectiveIfdef(IDLoc, true);
1206 return ParseDirectiveIfdef(IDLoc, false);
1208 return ParseDirectiveElseIf(IDLoc);
1210 return ParseDirectiveElse(IDLoc);
1212 return ParseDirectiveEndIf(IDLoc);
1215 // If we are in a ".if 0" block, ignore this statement.
1216 if (TheCondState.Ignore) {
1217 EatToEndOfStatement();
1221 // FIXME: Recurse on local labels?
1223 // See what kind of statement we have.
1224 switch (Lexer.getKind()) {
1225 case AsmToken::Colon: {
1226 CheckForValidSection();
1228 // identifier ':' -> Label.
1231 // Diagnose attempt to use '.' as a label.
1233 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1235 // Diagnose attempt to use a variable as a label.
1237 // FIXME: Diagnostics. Note the location of the definition as a label.
1238 // FIXME: This doesn't diagnose assignment to a symbol which has been
1239 // implicitly marked as external.
1241 if (LocalLabelVal == -1)
1242 Sym = getContext().GetOrCreateSymbol(IDVal);
1244 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1245 if (!Sym->isUndefined() || Sym->isVariable())
1246 return Error(IDLoc, "invalid symbol redefinition");
1249 if (!ParsingInlineAsm)
1252 // If we are generating dwarf for assembly source files then gather the
1253 // info to make a dwarf label entry for this label if needed.
1254 if (getContext().getGenDwarfForAssembly())
1255 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1258 // Consume any end of statement token, if present, to avoid spurious
1259 // AddBlankLine calls().
1260 if (Lexer.is(AsmToken::EndOfStatement)) {
1262 if (Lexer.is(AsmToken::Eof))
1269 case AsmToken::Equal:
1270 // identifier '=' ... -> assignment statement
1273 return ParseAssignment(IDVal, true);
1275 default: // Normal instruction or directive.
1279 // If macros are enabled, check to see if this is a macro instantiation.
1281 if (const Macro *M = MacroMap.lookup(IDVal))
1282 return HandleMacroEntry(IDVal, IDLoc, M);
1284 // Otherwise, we have a normal instruction or directive.
1285 if (IDVal[0] == '.' && IDVal != ".") {
1287 // Target hook for parsing target specific directives.
1288 if (!getTargetParser().ParseDirective(ID))
1296 return ParseDirectiveSet(IDVal, true);
1298 return ParseDirectiveSet(IDVal, false);
1300 return ParseDirectiveAscii(IDVal, false);
1303 return ParseDirectiveAscii(IDVal, true);
1305 return ParseDirectiveValue(1);
1309 return ParseDirectiveValue(2);
1313 return ParseDirectiveValue(4);
1316 return ParseDirectiveValue(8);
1319 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1321 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1323 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1324 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1327 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1328 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1331 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1333 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1335 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1337 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1339 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1341 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1343 return ParseDirectiveOrg();
1345 return ParseDirectiveFill();
1348 return ParseDirectiveSpace();
1350 return ParseDirectiveZero();
1352 EatToEndOfStatement(); // .extern is the default, ignore it.
1356 return ParseDirectiveSymbolAttribute(MCSA_Global);
1357 case DK_INDIRECT_SYMBOL:
1358 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1359 case DK_LAZY_REFERENCE:
1360 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1361 case DK_NO_DEAD_STRIP:
1362 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1363 case DK_SYMBOL_RESOLVER:
1364 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1365 case DK_PRIVATE_EXTERN:
1366 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1368 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1369 case DK_WEAK_DEFINITION:
1370 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1371 case DK_WEAK_REFERENCE:
1372 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1373 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1374 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1377 return ParseDirectiveComm(/*IsLocal=*/false);
1379 return ParseDirectiveComm(/*IsLocal=*/true);
1381 return ParseDirectiveAbort();
1383 return ParseDirectiveInclude();
1385 return ParseDirectiveIncbin();
1388 return TokError(Twine(IDVal) + " not supported yet");
1390 return ParseDirectiveRept(IDLoc);
1392 return ParseDirectiveIrp(IDLoc);
1394 return ParseDirectiveIrpc(IDLoc);
1396 return ParseDirectiveEndr(IDLoc);
1397 case DK_BUNDLE_ALIGN_MODE:
1398 return ParseDirectiveBundleAlignMode();
1399 case DK_BUNDLE_LOCK:
1400 return ParseDirectiveBundleLock();
1401 case DK_BUNDLE_UNLOCK:
1402 return ParseDirectiveBundleUnlock();
1405 // Look up the handler in the extension handler table.
1406 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1407 DirectiveMap.lookup(IDVal);
1409 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1411 return Error(IDLoc, "unknown directive");
1415 if (ParsingInlineAsm && IDVal == "_emit")
1416 return ParseDirectiveEmit(IDLoc, Info);
1418 CheckForValidSection();
1420 // Canonicalize the opcode to lower case.
1421 SmallString<128> OpcodeStr;
1422 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1423 OpcodeStr.push_back(tolower(IDVal[i]));
1425 ParseInstructionInfo IInfo(Info.AsmRewrites);
1426 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1427 IDLoc,Info.ParsedOperands);
1428 Info.ParseError = HadError;
1430 // Dump the parsed representation, if requested.
1431 if (getShowParsedOperands()) {
1432 SmallString<256> Str;
1433 raw_svector_ostream OS(Str);
1434 OS << "parsed instruction: [";
1435 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1438 Info.ParsedOperands[i]->print(OS);
1442 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1445 // If we are generating dwarf for assembly source files and the current
1446 // section is the initial text section then generate a .loc directive for
1448 if (!HadError && getContext().getGenDwarfForAssembly() &&
1449 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
1451 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1453 // If we previously parsed a cpp hash file line comment then make sure the
1454 // current Dwarf File is for the CppHashFilename if not then emit the
1455 // Dwarf File table for it and adjust the line number for the .loc.
1456 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1457 getContext().getMCDwarfFiles();
1458 if (CppHashFilename.size() != 0) {
1459 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1461 getStreamer().EmitDwarfFileDirective(
1462 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1464 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
1465 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1468 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1469 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1470 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1474 // If parsing succeeded, match the instruction.
1477 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1478 Info.ParsedOperands,
1483 // Don't skip the rest of the line, the instruction parser is responsible for
1488 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1489 /// since they may not be able to be tokenized to get to the end of line token.
1490 void AsmParser::EatToEndOfLine() {
1491 if (!Lexer.is(AsmToken::EndOfStatement))
1492 Lexer.LexUntilEndOfLine();
1497 /// ParseCppHashLineFilenameComment as this:
1498 /// ::= # number "filename"
1499 /// or just as a full line comment if it doesn't have a number and a string.
1500 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1501 Lex(); // Eat the hash token.
1503 if (getLexer().isNot(AsmToken::Integer)) {
1504 // Consume the line since in cases it is not a well-formed line directive,
1505 // as if were simply a full line comment.
1510 int64_t LineNumber = getTok().getIntVal();
1513 if (getLexer().isNot(AsmToken::String)) {
1518 StringRef Filename = getTok().getString();
1519 // Get rid of the enclosing quotes.
1520 Filename = Filename.substr(1, Filename.size()-2);
1522 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1524 CppHashFilename = Filename;
1525 CppHashLineNumber = LineNumber;
1526 CppHashBuf = CurBuffer;
1528 // Ignore any trailing characters, they're just comment.
1533 /// DiagHandler - will use the last parsed cpp hash line filename comment
1534 /// for the Filename and LineNo if any in the diagnostic.
1535 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1536 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1537 raw_ostream &OS = errs();
1539 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1540 const SMLoc &DiagLoc = Diag.getLoc();
1541 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1542 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1544 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1545 // before printing the message.
1546 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1547 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1548 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1549 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1552 // If we have not parsed a cpp hash line filename comment or the source
1553 // manager changed or buffer changed (like in a nested include) then just
1554 // print the normal diagnostic using its Filename and LineNo.
1555 if (!Parser->CppHashLineNumber ||
1556 &DiagSrcMgr != &Parser->SrcMgr ||
1557 DiagBuf != CppHashBuf) {
1558 if (Parser->SavedDiagHandler)
1559 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1565 // Use the CppHashFilename and calculate a line number based on the
1566 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1568 const std::string Filename = Parser->CppHashFilename;
1570 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1571 int CppHashLocLineNo =
1572 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1573 int LineNo = Parser->CppHashLineNumber - 1 +
1574 (DiagLocLineNo - CppHashLocLineNo);
1576 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1577 Filename, LineNo, Diag.getColumnNo(),
1578 Diag.getKind(), Diag.getMessage(),
1579 Diag.getLineContents(), Diag.getRanges());
1581 if (Parser->SavedDiagHandler)
1582 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1584 NewDiag.print(0, OS);
1587 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1588 // difference being that that function accepts '@' as part of identifiers and
1589 // we can't do that. AsmLexer.cpp should probably be changed to handle
1590 // '@' as a special case when needed.
1591 static bool isIdentifierChar(char c) {
1592 return isalnum(c) || c == '_' || c == '$' || c == '.';
1595 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1596 const MacroParameters &Parameters,
1597 const MacroArguments &A,
1599 unsigned NParameters = Parameters.size();
1600 if (NParameters != 0 && NParameters != A.size())
1601 return Error(L, "Wrong number of arguments");
1603 // A macro without parameters is handled differently on Darwin:
1604 // gas accepts no arguments and does no substitutions
1605 while (!Body.empty()) {
1606 // Scan for the next substitution.
1607 std::size_t End = Body.size(), Pos = 0;
1608 for (; Pos != End; ++Pos) {
1609 // Check for a substitution or escape.
1611 // This macro has no parameters, look for $0, $1, etc.
1612 if (Body[Pos] != '$' || Pos + 1 == End)
1615 char Next = Body[Pos + 1];
1616 if (Next == '$' || Next == 'n' || isdigit(Next))
1619 // This macro has parameters, look for \foo, \bar, etc.
1620 if (Body[Pos] == '\\' && Pos + 1 != End)
1626 OS << Body.slice(0, Pos);
1628 // Check if we reached the end.
1633 switch (Body[Pos+1]) {
1639 // $n => number of arguments
1644 // $[0-9] => argument
1646 // Missing arguments are ignored.
1647 unsigned Index = Body[Pos+1] - '0';
1648 if (Index >= A.size())
1651 // Otherwise substitute with the token values, with spaces eliminated.
1652 for (MacroArgument::const_iterator it = A[Index].begin(),
1653 ie = A[Index].end(); it != ie; ++it)
1654 OS << it->getString();
1660 unsigned I = Pos + 1;
1661 while (isIdentifierChar(Body[I]) && I + 1 != End)
1664 const char *Begin = Body.data() + Pos +1;
1665 StringRef Argument(Begin, I - (Pos +1));
1667 for (; Index < NParameters; ++Index)
1668 if (Parameters[Index].first == Argument)
1671 if (Index == NParameters) {
1672 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1675 OS << '\\' << Argument;
1679 for (MacroArgument::const_iterator it = A[Index].begin(),
1680 ie = A[Index].end(); it != ie; ++it)
1681 if (it->getKind() == AsmToken::String)
1682 OS << it->getStringContents();
1684 OS << it->getString();
1686 Pos += 1 + Argument.size();
1689 // Update the scan point.
1690 Body = Body.substr(Pos);
1696 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL,
1699 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1704 static bool IsOperator(AsmToken::TokenKind kind)
1710 case AsmToken::Plus:
1711 case AsmToken::Minus:
1712 case AsmToken::Tilde:
1713 case AsmToken::Slash:
1714 case AsmToken::Star:
1716 case AsmToken::Equal:
1717 case AsmToken::EqualEqual:
1718 case AsmToken::Pipe:
1719 case AsmToken::PipePipe:
1720 case AsmToken::Caret:
1722 case AsmToken::AmpAmp:
1723 case AsmToken::Exclaim:
1724 case AsmToken::ExclaimEqual:
1725 case AsmToken::Percent:
1726 case AsmToken::Less:
1727 case AsmToken::LessEqual:
1728 case AsmToken::LessLess:
1729 case AsmToken::LessGreater:
1730 case AsmToken::Greater:
1731 case AsmToken::GreaterEqual:
1732 case AsmToken::GreaterGreater:
1737 /// ParseMacroArgument - Extract AsmTokens for a macro argument.
1738 /// This is used for both default macro parameter values and the
1739 /// arguments in macro invocations
1740 bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1741 AsmToken::TokenKind &ArgumentDelimiter) {
1742 unsigned ParenLevel = 0;
1743 unsigned AddTokens = 0;
1745 // gas accepts arguments separated by whitespace, except on Darwin
1747 Lexer.setSkipSpace(false);
1750 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1751 Lexer.setSkipSpace(true);
1752 return TokError("unexpected token in macro instantiation");
1755 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1756 // Spaces and commas cannot be mixed to delimit parameters
1757 if (ArgumentDelimiter == AsmToken::Eof)
1758 ArgumentDelimiter = AsmToken::Comma;
1759 else if (ArgumentDelimiter != AsmToken::Comma) {
1760 Lexer.setSkipSpace(true);
1761 return TokError("expected ' ' for macro argument separator");
1766 if (Lexer.is(AsmToken::Space)) {
1767 Lex(); // Eat spaces
1769 // Spaces can delimit parameters, but could also be part an expression.
1770 // If the token after a space is an operator, add the token and the next
1771 // one into this argument
1772 if (ArgumentDelimiter == AsmToken::Space ||
1773 ArgumentDelimiter == AsmToken::Eof) {
1774 if (IsOperator(Lexer.getKind())) {
1775 // Check to see whether the token is used as an operator,
1776 // or part of an identifier
1777 const char *NextChar = getTok().getEndLoc().getPointer();
1778 if (*NextChar == ' ')
1782 if (!AddTokens && ParenLevel == 0) {
1783 if (ArgumentDelimiter == AsmToken::Eof &&
1784 !IsOperator(Lexer.getKind()))
1785 ArgumentDelimiter = AsmToken::Space;
1791 // HandleMacroEntry relies on not advancing the lexer here
1792 // to be able to fill in the remaining default parameter values
1793 if (Lexer.is(AsmToken::EndOfStatement))
1796 // Adjust the current parentheses level.
1797 if (Lexer.is(AsmToken::LParen))
1799 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1802 // Append the token to the current argument list.
1803 MA.push_back(getTok());
1809 Lexer.setSkipSpace(true);
1810 if (ParenLevel != 0)
1811 return TokError("unbalanced parentheses in macro argument");
1815 // Parse the macro instantiation arguments.
1816 bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
1817 const unsigned NParameters = M ? M->Parameters.size() : 0;
1818 // Argument delimiter is initially unknown. It will be set by
1819 // ParseMacroArgument()
1820 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1822 // Parse two kinds of macro invocations:
1823 // - macros defined without any parameters accept an arbitrary number of them
1824 // - macros defined with parameters accept at most that many of them
1825 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1829 if (ParseMacroArgument(MA, ArgumentDelimiter))
1832 if (!MA.empty() || !NParameters)
1834 else if (NParameters) {
1835 if (!M->Parameters[Parameter].second.empty())
1836 A.push_back(M->Parameters[Parameter].second);
1839 // At the end of the statement, fill in remaining arguments that have
1840 // default values. If there aren't any, then the next argument is
1841 // required but missing
1842 if (Lexer.is(AsmToken::EndOfStatement)) {
1843 if (NParameters && Parameter < NParameters - 1) {
1844 if (M->Parameters[Parameter + 1].second.empty())
1845 return TokError("macro argument '" +
1846 Twine(M->Parameters[Parameter + 1].first) +
1854 if (Lexer.is(AsmToken::Comma))
1857 return TokError("Too many arguments");
1860 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1862 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1863 // this, although we should protect against infinite loops.
1864 if (ActiveMacros.size() == 20)
1865 return TokError("macros cannot be nested more than 20 levels deep");
1868 if (ParseMacroArguments(M, A))
1871 // Remove any trailing empty arguments. Do this after-the-fact as we have
1872 // to keep empty arguments in the middle of the list or positionality
1873 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1874 while (!A.empty() && A.back().empty())
1877 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1878 // to hold the macro body with substitutions.
1879 SmallString<256> Buf;
1880 StringRef Body = M->Body;
1881 raw_svector_ostream OS(Buf);
1883 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1886 // We include the .endmacro in the buffer as our queue to exit the macro
1888 OS << ".endmacro\n";
1890 MemoryBuffer *Instantiation =
1891 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1893 // Create the macro instantiation object and add to the current macro
1894 // instantiation stack.
1895 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1899 ActiveMacros.push_back(MI);
1901 // Jump to the macro instantiation and prime the lexer.
1902 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1903 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1909 void AsmParser::HandleMacroExit() {
1910 // Jump to the EndOfStatement we should return to, and consume it.
1911 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
1914 // Pop the instantiation entry.
1915 delete ActiveMacros.back();
1916 ActiveMacros.pop_back();
1919 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1920 switch (Value->getKind()) {
1921 case MCExpr::Binary: {
1922 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1923 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1926 case MCExpr::Target:
1927 case MCExpr::Constant:
1929 case MCExpr::SymbolRef: {
1930 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1932 return IsUsedIn(Sym, S.getVariableValue());
1936 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1939 llvm_unreachable("Unknown expr kind!");
1942 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1944 // FIXME: Use better location, we should use proper tokens.
1945 SMLoc EqualLoc = Lexer.getLoc();
1947 const MCExpr *Value;
1948 if (ParseExpression(Value))
1951 // Note: we don't count b as used in "a = b". This is to allow
1955 if (Lexer.isNot(AsmToken::EndOfStatement))
1956 return TokError("unexpected token in assignment");
1958 // Error on assignment to '.'.
1960 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1961 "(use '.space' or '.org').)"));
1964 // Eat the end of statement marker.
1967 // Validate that the LHS is allowed to be a variable (either it has not been
1968 // used as a symbol, or it is an absolute symbol).
1969 MCSymbol *Sym = getContext().LookupSymbol(Name);
1971 // Diagnose assignment to a label.
1973 // FIXME: Diagnostics. Note the location of the definition as a label.
1974 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1975 if (IsUsedIn(Sym, Value))
1976 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1977 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1978 ; // Allow redefinitions of undefined symbols only used in directives.
1979 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1980 ; // Allow redefinitions of variables that haven't yet been used.
1981 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1982 return Error(EqualLoc, "redefinition of '" + Name + "'");
1983 else if (!Sym->isVariable())
1984 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1985 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1986 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1989 // Don't count these checks as uses.
1990 Sym->setUsed(false);
1992 Sym = getContext().GetOrCreateSymbol(Name);
1994 // FIXME: Handle '.'.
1996 // Do the assignment.
1997 Out.EmitAssignment(Sym, Value);
1999 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2005 /// ParseIdentifier:
2008 bool AsmParser::ParseIdentifier(StringRef &Res) {
2009 // The assembler has relaxed rules for accepting identifiers, in particular we
2010 // allow things like '.globl $foo', which would normally be separate
2011 // tokens. At this level, we have already lexed so we cannot (currently)
2012 // handle this as a context dependent token, instead we detect adjacent tokens
2013 // and return the combined identifier.
2014 if (Lexer.is(AsmToken::Dollar)) {
2015 SMLoc DollarLoc = getLexer().getLoc();
2017 // Consume the dollar sign, and check for a following identifier.
2019 if (Lexer.isNot(AsmToken::Identifier))
2022 // We have a '$' followed by an identifier, make sure they are adjacent.
2023 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2026 // Construct the joined identifier and consume the token.
2027 Res = StringRef(DollarLoc.getPointer(),
2028 getTok().getIdentifier().size() + 1);
2033 if (Lexer.isNot(AsmToken::Identifier) &&
2034 Lexer.isNot(AsmToken::String))
2037 Res = getTok().getIdentifier();
2039 Lex(); // Consume the identifier token.
2044 /// ParseDirectiveSet:
2045 /// ::= .equ identifier ',' expression
2046 /// ::= .equiv identifier ',' expression
2047 /// ::= .set identifier ',' expression
2048 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
2051 if (ParseIdentifier(Name))
2052 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2054 if (getLexer().isNot(AsmToken::Comma))
2055 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2058 return ParseAssignment(Name, allow_redef, true);
2061 bool AsmParser::ParseEscapedString(std::string &Data) {
2062 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2065 StringRef Str = getTok().getStringContents();
2066 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2067 if (Str[i] != '\\') {
2072 // Recognize escaped characters. Note that this escape semantics currently
2073 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2076 return TokError("unexpected backslash at end of string");
2078 // Recognize octal sequences.
2079 if ((unsigned) (Str[i] - '0') <= 7) {
2080 // Consume up to three octal characters.
2081 unsigned Value = Str[i] - '0';
2083 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2085 Value = Value * 8 + (Str[i] - '0');
2087 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2089 Value = Value * 8 + (Str[i] - '0');
2094 return TokError("invalid octal escape sequence (out of range)");
2096 Data += (unsigned char) Value;
2100 // Otherwise recognize individual escapes.
2103 // Just reject invalid escape sequences for now.
2104 return TokError("invalid escape sequence (unrecognized character)");
2106 case 'b': Data += '\b'; break;
2107 case 'f': Data += '\f'; break;
2108 case 'n': Data += '\n'; break;
2109 case 'r': Data += '\r'; break;
2110 case 't': Data += '\t'; break;
2111 case '"': Data += '"'; break;
2112 case '\\': Data += '\\'; break;
2119 /// ParseDirectiveAscii:
2120 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2121 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2122 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2123 CheckForValidSection();
2126 if (getLexer().isNot(AsmToken::String))
2127 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2130 if (ParseEscapedString(Data))
2133 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2135 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2139 if (getLexer().is(AsmToken::EndOfStatement))
2142 if (getLexer().isNot(AsmToken::Comma))
2143 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2152 /// ParseDirectiveValue
2153 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2154 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2155 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2156 CheckForValidSection();
2159 const MCExpr *Value;
2160 SMLoc ExprLoc = getLexer().getLoc();
2161 if (ParseExpression(Value))
2164 // Special case constant expressions to match code generator.
2165 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2166 assert(Size <= 8 && "Invalid size");
2167 uint64_t IntValue = MCE->getValue();
2168 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2169 return Error(ExprLoc, "literal value out of range for directive");
2170 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2172 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2174 if (getLexer().is(AsmToken::EndOfStatement))
2177 // FIXME: Improve diagnostic.
2178 if (getLexer().isNot(AsmToken::Comma))
2179 return TokError("unexpected token in directive");
2188 /// ParseDirectiveRealValue
2189 /// ::= (.single | .double) [ expression (, expression)* ]
2190 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2191 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2192 CheckForValidSection();
2195 // We don't truly support arithmetic on floating point expressions, so we
2196 // have to manually parse unary prefixes.
2198 if (getLexer().is(AsmToken::Minus)) {
2201 } else if (getLexer().is(AsmToken::Plus))
2204 if (getLexer().isNot(AsmToken::Integer) &&
2205 getLexer().isNot(AsmToken::Real) &&
2206 getLexer().isNot(AsmToken::Identifier))
2207 return TokError("unexpected token in directive");
2209 // Convert to an APFloat.
2210 APFloat Value(Semantics);
2211 StringRef IDVal = getTok().getString();
2212 if (getLexer().is(AsmToken::Identifier)) {
2213 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2214 Value = APFloat::getInf(Semantics);
2215 else if (!IDVal.compare_lower("nan"))
2216 Value = APFloat::getNaN(Semantics, false, ~0);
2218 return TokError("invalid floating point literal");
2219 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2220 APFloat::opInvalidOp)
2221 return TokError("invalid floating point literal");
2225 // Consume the numeric token.
2228 // Emit the value as an integer.
2229 APInt AsInt = Value.bitcastToAPInt();
2230 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2231 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2233 if (getLexer().is(AsmToken::EndOfStatement))
2236 if (getLexer().isNot(AsmToken::Comma))
2237 return TokError("unexpected token in directive");
2246 /// ParseDirectiveSpace
2247 /// ::= .space expression [ , expression ]
2248 bool AsmParser::ParseDirectiveSpace() {
2249 CheckForValidSection();
2252 if (ParseAbsoluteExpression(NumBytes))
2255 int64_t FillExpr = 0;
2256 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2257 if (getLexer().isNot(AsmToken::Comma))
2258 return TokError("unexpected token in '.space' directive");
2261 if (ParseAbsoluteExpression(FillExpr))
2264 if (getLexer().isNot(AsmToken::EndOfStatement))
2265 return TokError("unexpected token in '.space' directive");
2271 return TokError("invalid number of bytes in '.space' directive");
2273 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
2274 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
2279 /// ParseDirectiveZero
2280 /// ::= .zero expression
2281 bool AsmParser::ParseDirectiveZero() {
2282 CheckForValidSection();
2285 if (ParseAbsoluteExpression(NumBytes))
2289 if (getLexer().is(AsmToken::Comma)) {
2291 if (ParseAbsoluteExpression(Val))
2295 if (getLexer().isNot(AsmToken::EndOfStatement))
2296 return TokError("unexpected token in '.zero' directive");
2300 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2305 /// ParseDirectiveFill
2306 /// ::= .fill expression , expression , expression
2307 bool AsmParser::ParseDirectiveFill() {
2308 CheckForValidSection();
2311 if (ParseAbsoluteExpression(NumValues))
2314 if (getLexer().isNot(AsmToken::Comma))
2315 return TokError("unexpected token in '.fill' directive");
2319 if (ParseAbsoluteExpression(FillSize))
2322 if (getLexer().isNot(AsmToken::Comma))
2323 return TokError("unexpected token in '.fill' directive");
2327 if (ParseAbsoluteExpression(FillExpr))
2330 if (getLexer().isNot(AsmToken::EndOfStatement))
2331 return TokError("unexpected token in '.fill' directive");
2335 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2336 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2338 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2339 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2344 /// ParseDirectiveOrg
2345 /// ::= .org expression [ , expression ]
2346 bool AsmParser::ParseDirectiveOrg() {
2347 CheckForValidSection();
2349 const MCExpr *Offset;
2350 SMLoc Loc = getTok().getLoc();
2351 if (ParseExpression(Offset))
2354 // Parse optional fill expression.
2355 int64_t FillExpr = 0;
2356 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2357 if (getLexer().isNot(AsmToken::Comma))
2358 return TokError("unexpected token in '.org' directive");
2361 if (ParseAbsoluteExpression(FillExpr))
2364 if (getLexer().isNot(AsmToken::EndOfStatement))
2365 return TokError("unexpected token in '.org' directive");
2370 // Only limited forms of relocatable expressions are accepted here, it
2371 // has to be relative to the current section. The streamer will return
2372 // 'true' if the expression wasn't evaluatable.
2373 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2374 return Error(Loc, "expected assembly-time absolute expression");
2379 /// ParseDirectiveAlign
2380 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2381 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2382 CheckForValidSection();
2384 SMLoc AlignmentLoc = getLexer().getLoc();
2386 if (ParseAbsoluteExpression(Alignment))
2390 bool HasFillExpr = false;
2391 int64_t FillExpr = 0;
2392 int64_t MaxBytesToFill = 0;
2393 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2394 if (getLexer().isNot(AsmToken::Comma))
2395 return TokError("unexpected token in directive");
2398 // The fill expression can be omitted while specifying a maximum number of
2399 // alignment bytes, e.g:
2401 if (getLexer().isNot(AsmToken::Comma)) {
2403 if (ParseAbsoluteExpression(FillExpr))
2407 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2408 if (getLexer().isNot(AsmToken::Comma))
2409 return TokError("unexpected token in directive");
2412 MaxBytesLoc = getLexer().getLoc();
2413 if (ParseAbsoluteExpression(MaxBytesToFill))
2416 if (getLexer().isNot(AsmToken::EndOfStatement))
2417 return TokError("unexpected token in directive");
2426 // Compute alignment in bytes.
2428 // FIXME: Diagnose overflow.
2429 if (Alignment >= 32) {
2430 Error(AlignmentLoc, "invalid alignment value");
2434 Alignment = 1ULL << Alignment;
2437 // Diagnose non-sensical max bytes to align.
2438 if (MaxBytesLoc.isValid()) {
2439 if (MaxBytesToFill < 1) {
2440 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2441 "many bytes, ignoring maximum bytes expression");
2445 if (MaxBytesToFill >= Alignment) {
2446 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2452 // Check whether we should use optimal code alignment for this .align
2454 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2455 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2456 ValueSize == 1 && UseCodeAlign) {
2457 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2459 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2460 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2468 /// ParseDirectiveBundleAlignMode
2469 /// ::= {.bundle_align_mode} expression
2470 bool AsmParser::ParseDirectiveBundleAlignMode() {
2471 CheckForValidSection();
2473 // Expect a single argument: an expression that evaluates to a constant
2474 // in the inclusive range 0-30.
2475 SMLoc ExprLoc = getLexer().getLoc();
2476 int64_t AlignSizePow2;
2477 if (ParseAbsoluteExpression(AlignSizePow2))
2479 else if (getLexer().isNot(AsmToken::EndOfStatement))
2480 return TokError("unexpected token after expression in"
2481 " '.bundle_align_mode' directive");
2482 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
2483 return Error(ExprLoc,
2484 "invalid bundle alignment size (expected between 0 and 30)");
2488 // Because of AlignSizePow2's verified range we can safely truncate it to
2490 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
2494 /// ParseDirectiveBundleLock
2495 /// ::= {.bundle_lock} [align_to_end]
2496 bool AsmParser::ParseDirectiveBundleLock() {
2497 CheckForValidSection();
2498 bool AlignToEnd = false;
2500 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2502 SMLoc Loc = getTok().getLoc();
2503 const char *kInvalidOptionError =
2504 "invalid option for '.bundle_lock' directive";
2506 if (ParseIdentifier(Option))
2507 return Error(Loc, kInvalidOptionError);
2509 if (Option != "align_to_end")
2510 return Error(Loc, kInvalidOptionError);
2511 else if (getLexer().isNot(AsmToken::EndOfStatement))
2513 "unexpected token after '.bundle_lock' directive option");
2519 getStreamer().EmitBundleLock(AlignToEnd);
2523 /// ParseDirectiveBundleLock
2524 /// ::= {.bundle_lock}
2525 bool AsmParser::ParseDirectiveBundleUnlock() {
2526 CheckForValidSection();
2528 if (getLexer().isNot(AsmToken::EndOfStatement))
2529 return TokError("unexpected token in '.bundle_unlock' directive");
2532 getStreamer().EmitBundleUnlock();
2536 /// ParseDirectiveSymbolAttribute
2537 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2538 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2539 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2542 SMLoc Loc = getTok().getLoc();
2544 if (ParseIdentifier(Name))
2545 return Error(Loc, "expected identifier in directive");
2547 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2549 // Assembler local symbols don't make any sense here. Complain loudly.
2550 if (Sym->isTemporary())
2551 return Error(Loc, "non-local symbol required in directive");
2553 getStreamer().EmitSymbolAttribute(Sym, Attr);
2555 if (getLexer().is(AsmToken::EndOfStatement))
2558 if (getLexer().isNot(AsmToken::Comma))
2559 return TokError("unexpected token in directive");
2568 /// ParseDirectiveComm
2569 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2570 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2571 CheckForValidSection();
2573 SMLoc IDLoc = getLexer().getLoc();
2575 if (ParseIdentifier(Name))
2576 return TokError("expected identifier in directive");
2578 // Handle the identifier as the key symbol.
2579 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2581 if (getLexer().isNot(AsmToken::Comma))
2582 return TokError("unexpected token in directive");
2586 SMLoc SizeLoc = getLexer().getLoc();
2587 if (ParseAbsoluteExpression(Size))
2590 int64_t Pow2Alignment = 0;
2591 SMLoc Pow2AlignmentLoc;
2592 if (getLexer().is(AsmToken::Comma)) {
2594 Pow2AlignmentLoc = getLexer().getLoc();
2595 if (ParseAbsoluteExpression(Pow2Alignment))
2598 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2599 if (IsLocal && LCOMM == LCOMM::NoAlignment)
2600 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2602 // If this target takes alignments in bytes (not log) validate and convert.
2603 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2604 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
2605 if (!isPowerOf2_64(Pow2Alignment))
2606 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2607 Pow2Alignment = Log2_64(Pow2Alignment);
2611 if (getLexer().isNot(AsmToken::EndOfStatement))
2612 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2616 // NOTE: a size of zero for a .comm should create a undefined symbol
2617 // but a size of .lcomm creates a bss symbol of size zero.
2619 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2620 "be less than zero");
2622 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2623 // may internally end up wanting an alignment in bytes.
2624 // FIXME: Diagnose overflow.
2625 if (Pow2Alignment < 0)
2626 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2627 "alignment, can't be less than zero");
2629 if (!Sym->isUndefined())
2630 return Error(IDLoc, "invalid symbol redefinition");
2632 // Create the Symbol as a common or local common with Size and Pow2Alignment
2634 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2638 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2642 /// ParseDirectiveAbort
2643 /// ::= .abort [... message ...]
2644 bool AsmParser::ParseDirectiveAbort() {
2645 // FIXME: Use loc from directive.
2646 SMLoc Loc = getLexer().getLoc();
2648 StringRef Str = ParseStringToEndOfStatement();
2649 if (getLexer().isNot(AsmToken::EndOfStatement))
2650 return TokError("unexpected token in '.abort' directive");
2655 Error(Loc, ".abort detected. Assembly stopping.");
2657 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2658 // FIXME: Actually abort assembly here.
2663 /// ParseDirectiveInclude
2664 /// ::= .include "filename"
2665 bool AsmParser::ParseDirectiveInclude() {
2666 if (getLexer().isNot(AsmToken::String))
2667 return TokError("expected string in '.include' directive");
2669 std::string Filename = getTok().getString();
2670 SMLoc IncludeLoc = getLexer().getLoc();
2673 if (getLexer().isNot(AsmToken::EndOfStatement))
2674 return TokError("unexpected token in '.include' directive");
2676 // Strip the quotes.
2677 Filename = Filename.substr(1, Filename.size()-2);
2679 // Attempt to switch the lexer to the included file before consuming the end
2680 // of statement to avoid losing it when we switch.
2681 if (EnterIncludeFile(Filename)) {
2682 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2689 /// ParseDirectiveIncbin
2690 /// ::= .incbin "filename"
2691 bool AsmParser::ParseDirectiveIncbin() {
2692 if (getLexer().isNot(AsmToken::String))
2693 return TokError("expected string in '.incbin' directive");
2695 std::string Filename = getTok().getString();
2696 SMLoc IncbinLoc = getLexer().getLoc();
2699 if (getLexer().isNot(AsmToken::EndOfStatement))
2700 return TokError("unexpected token in '.incbin' directive");
2702 // Strip the quotes.
2703 Filename = Filename.substr(1, Filename.size()-2);
2705 // Attempt to process the included file.
2706 if (ProcessIncbinFile(Filename)) {
2707 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2714 /// ParseDirectiveIf
2715 /// ::= .if expression
2716 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2717 TheCondStack.push_back(TheCondState);
2718 TheCondState.TheCond = AsmCond::IfCond;
2719 if (TheCondState.Ignore) {
2720 EatToEndOfStatement();
2723 if (ParseAbsoluteExpression(ExprValue))
2726 if (getLexer().isNot(AsmToken::EndOfStatement))
2727 return TokError("unexpected token in '.if' directive");
2731 TheCondState.CondMet = ExprValue;
2732 TheCondState.Ignore = !TheCondState.CondMet;
2738 /// ParseDirectiveIfb
2740 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2741 TheCondStack.push_back(TheCondState);
2742 TheCondState.TheCond = AsmCond::IfCond;
2744 if (TheCondState.Ignore) {
2745 EatToEndOfStatement();
2747 StringRef Str = ParseStringToEndOfStatement();
2749 if (getLexer().isNot(AsmToken::EndOfStatement))
2750 return TokError("unexpected token in '.ifb' directive");
2754 TheCondState.CondMet = ExpectBlank == Str.empty();
2755 TheCondState.Ignore = !TheCondState.CondMet;
2761 /// ParseDirectiveIfc
2762 /// ::= .ifc string1, string2
2763 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2764 TheCondStack.push_back(TheCondState);
2765 TheCondState.TheCond = AsmCond::IfCond;
2767 if (TheCondState.Ignore) {
2768 EatToEndOfStatement();
2770 StringRef Str1 = ParseStringToComma();
2772 if (getLexer().isNot(AsmToken::Comma))
2773 return TokError("unexpected token in '.ifc' directive");
2777 StringRef Str2 = ParseStringToEndOfStatement();
2779 if (getLexer().isNot(AsmToken::EndOfStatement))
2780 return TokError("unexpected token in '.ifc' directive");
2784 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2785 TheCondState.Ignore = !TheCondState.CondMet;
2791 /// ParseDirectiveIfdef
2792 /// ::= .ifdef symbol
2793 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2795 TheCondStack.push_back(TheCondState);
2796 TheCondState.TheCond = AsmCond::IfCond;
2798 if (TheCondState.Ignore) {
2799 EatToEndOfStatement();
2801 if (ParseIdentifier(Name))
2802 return TokError("expected identifier after '.ifdef'");
2806 MCSymbol *Sym = getContext().LookupSymbol(Name);
2809 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2811 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2812 TheCondState.Ignore = !TheCondState.CondMet;
2818 /// ParseDirectiveElseIf
2819 /// ::= .elseif expression
2820 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2821 if (TheCondState.TheCond != AsmCond::IfCond &&
2822 TheCondState.TheCond != AsmCond::ElseIfCond)
2823 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2825 TheCondState.TheCond = AsmCond::ElseIfCond;
2827 bool LastIgnoreState = false;
2828 if (!TheCondStack.empty())
2829 LastIgnoreState = TheCondStack.back().Ignore;
2830 if (LastIgnoreState || TheCondState.CondMet) {
2831 TheCondState.Ignore = true;
2832 EatToEndOfStatement();
2836 if (ParseAbsoluteExpression(ExprValue))
2839 if (getLexer().isNot(AsmToken::EndOfStatement))
2840 return TokError("unexpected token in '.elseif' directive");
2843 TheCondState.CondMet = ExprValue;
2844 TheCondState.Ignore = !TheCondState.CondMet;
2850 /// ParseDirectiveElse
2852 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2853 if (getLexer().isNot(AsmToken::EndOfStatement))
2854 return TokError("unexpected token in '.else' directive");
2858 if (TheCondState.TheCond != AsmCond::IfCond &&
2859 TheCondState.TheCond != AsmCond::ElseIfCond)
2860 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2862 TheCondState.TheCond = AsmCond::ElseCond;
2863 bool LastIgnoreState = false;
2864 if (!TheCondStack.empty())
2865 LastIgnoreState = TheCondStack.back().Ignore;
2866 if (LastIgnoreState || TheCondState.CondMet)
2867 TheCondState.Ignore = true;
2869 TheCondState.Ignore = false;
2874 /// ParseDirectiveEndIf
2876 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2877 if (getLexer().isNot(AsmToken::EndOfStatement))
2878 return TokError("unexpected token in '.endif' directive");
2882 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2883 TheCondStack.empty())
2884 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2886 if (!TheCondStack.empty()) {
2887 TheCondState = TheCondStack.back();
2888 TheCondStack.pop_back();
2894 void AsmParser::initializeDirectiveKindMapping() {
2895 DirectiveKindMapping[".set"] = DK_SET;
2896 DirectiveKindMapping[".equ"] = DK_EQU;
2897 DirectiveKindMapping[".equiv"] = DK_EQUIV;
2898 DirectiveKindMapping[".ascii"] = DK_ASCII;
2899 DirectiveKindMapping[".asciz"] = DK_ASCIZ;
2900 DirectiveKindMapping[".string"] = DK_STRING;
2901 DirectiveKindMapping[".byte"] = DK_BYTE;
2902 DirectiveKindMapping[".short"] = DK_SHORT;
2903 DirectiveKindMapping[".value"] = DK_VALUE;
2904 DirectiveKindMapping[".2byte"] = DK_2BYTE;
2905 DirectiveKindMapping[".long"] = DK_LONG;
2906 DirectiveKindMapping[".int"] = DK_INT;
2907 DirectiveKindMapping[".4byte"] = DK_4BYTE;
2908 DirectiveKindMapping[".quad"] = DK_QUAD;
2909 DirectiveKindMapping[".8byte"] = DK_8BYTE;
2910 DirectiveKindMapping[".single"] = DK_SINGLE;
2911 DirectiveKindMapping[".float"] = DK_FLOAT;
2912 DirectiveKindMapping[".double"] = DK_DOUBLE;
2913 DirectiveKindMapping[".align"] = DK_ALIGN;
2914 DirectiveKindMapping[".align32"] = DK_ALIGN32;
2915 DirectiveKindMapping[".balign"] = DK_BALIGN;
2916 DirectiveKindMapping[".balignw"] = DK_BALIGNW;
2917 DirectiveKindMapping[".balignl"] = DK_BALIGNL;
2918 DirectiveKindMapping[".p2align"] = DK_P2ALIGN;
2919 DirectiveKindMapping[".p2alignw"] = DK_P2ALIGNW;
2920 DirectiveKindMapping[".p2alignl"] = DK_P2ALIGNL;
2921 DirectiveKindMapping[".org"] = DK_ORG;
2922 DirectiveKindMapping[".fill"] = DK_FILL;
2923 DirectiveKindMapping[".space"] = DK_SPACE;
2924 DirectiveKindMapping[".skip"] = DK_SKIP;
2925 DirectiveKindMapping[".zero"] = DK_ZERO;
2926 DirectiveKindMapping[".extern"] = DK_EXTERN;
2927 DirectiveKindMapping[".globl"] = DK_GLOBL;
2928 DirectiveKindMapping[".global"] = DK_GLOBAL;
2929 DirectiveKindMapping[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
2930 DirectiveKindMapping[".lazy_reference"] = DK_LAZY_REFERENCE;
2931 DirectiveKindMapping[".no_dead_strip"] = DK_NO_DEAD_STRIP;
2932 DirectiveKindMapping[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
2933 DirectiveKindMapping[".private_extern"] = DK_PRIVATE_EXTERN;
2934 DirectiveKindMapping[".reference"] = DK_REFERENCE;
2935 DirectiveKindMapping[".weak_definition"] = DK_WEAK_DEFINITION;
2936 DirectiveKindMapping[".weak_reference"] = DK_WEAK_REFERENCE;
2937 DirectiveKindMapping[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
2938 DirectiveKindMapping[".comm"] = DK_COMM;
2939 DirectiveKindMapping[".common"] = DK_COMMON;
2940 DirectiveKindMapping[".lcomm"] = DK_LCOMM;
2941 DirectiveKindMapping[".abort"] = DK_ABORT;
2942 DirectiveKindMapping[".include"] = DK_INCLUDE;
2943 DirectiveKindMapping[".incbin"] = DK_INCBIN;
2944 DirectiveKindMapping[".code16"] = DK_CODE16;
2945 DirectiveKindMapping[".code16gcc"] = DK_CODE16GCC;
2946 DirectiveKindMapping[".rept"] = DK_REPT;
2947 DirectiveKindMapping[".irp"] = DK_IRP;
2948 DirectiveKindMapping[".irpc"] = DK_IRPC;
2949 DirectiveKindMapping[".endr"] = DK_ENDR;
2950 DirectiveKindMapping[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
2951 DirectiveKindMapping[".bundle_lock"] = DK_BUNDLE_LOCK;
2952 DirectiveKindMapping[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
2953 DirectiveKindMapping[".if"] = DK_IF;
2954 DirectiveKindMapping[".ifb"] = DK_IFB;
2955 DirectiveKindMapping[".ifnb"] = DK_IFNB;
2956 DirectiveKindMapping[".ifc"] = DK_IFC;
2957 DirectiveKindMapping[".ifnc"] = DK_IFNC;
2958 DirectiveKindMapping[".ifdef"] = DK_IFDEF;
2959 DirectiveKindMapping[".ifndef"] = DK_IFNDEF;
2960 DirectiveKindMapping[".ifnotdef"] = DK_IFNOTDEF;
2961 DirectiveKindMapping[".elseif"] = DK_ELSEIF;
2962 DirectiveKindMapping[".else"] = DK_ELSE;
2963 DirectiveKindMapping[".endif"] = DK_ENDIF;
2966 /// ParseDirectiveFile
2967 /// ::= .file [number] filename
2968 /// ::= .file number directory filename
2969 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2970 // FIXME: I'm not sure what this is.
2971 int64_t FileNumber = -1;
2972 SMLoc FileNumberLoc = getLexer().getLoc();
2973 if (getLexer().is(AsmToken::Integer)) {
2974 FileNumber = getTok().getIntVal();
2978 return TokError("file number less than one");
2981 if (getLexer().isNot(AsmToken::String))
2982 return TokError("unexpected token in '.file' directive");
2984 // Usually the directory and filename together, otherwise just the directory.
2985 StringRef Path = getTok().getString();
2986 Path = Path.substr(1, Path.size()-2);
2989 StringRef Directory;
2991 if (getLexer().is(AsmToken::String)) {
2992 if (FileNumber == -1)
2993 return TokError("explicit path specified, but no file number");
2994 Filename = getTok().getString();
2995 Filename = Filename.substr(1, Filename.size()-2);
3002 if (getLexer().isNot(AsmToken::EndOfStatement))
3003 return TokError("unexpected token in '.file' directive");
3005 if (FileNumber == -1)
3006 getStreamer().EmitFileDirective(Filename);
3008 if (getContext().getGenDwarfForAssembly() == true)
3009 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
3010 "used to generate dwarf debug info for assembly code");
3012 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
3013 Error(FileNumberLoc, "file number already allocated");
3019 /// ParseDirectiveLine
3020 /// ::= .line [number]
3021 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
3022 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3023 if (getLexer().isNot(AsmToken::Integer))
3024 return TokError("unexpected token in '.line' directive");
3026 int64_t LineNumber = getTok().getIntVal();
3030 // FIXME: Do something with the .line.
3033 if (getLexer().isNot(AsmToken::EndOfStatement))
3034 return TokError("unexpected token in '.line' directive");
3040 /// ParseDirectiveLoc
3041 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3042 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3043 /// The first number is a file number, must have been previously assigned with
3044 /// a .file directive, the second number is the line number and optionally the
3045 /// third number is a column position (zero if not specified). The remaining
3046 /// optional items are .loc sub-directives.
3047 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
3049 if (getLexer().isNot(AsmToken::Integer))
3050 return TokError("unexpected token in '.loc' directive");
3051 int64_t FileNumber = getTok().getIntVal();
3053 return TokError("file number less than one in '.loc' directive");
3054 if (!getContext().isValidDwarfFileNumber(FileNumber))
3055 return TokError("unassigned file number in '.loc' directive");
3058 int64_t LineNumber = 0;
3059 if (getLexer().is(AsmToken::Integer)) {
3060 LineNumber = getTok().getIntVal();
3062 return TokError("line number less than one in '.loc' directive");
3066 int64_t ColumnPos = 0;
3067 if (getLexer().is(AsmToken::Integer)) {
3068 ColumnPos = getTok().getIntVal();
3070 return TokError("column position less than zero in '.loc' directive");
3074 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3076 int64_t Discriminator = 0;
3077 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3079 if (getLexer().is(AsmToken::EndOfStatement))
3083 SMLoc Loc = getTok().getLoc();
3084 if (getParser().ParseIdentifier(Name))
3085 return TokError("unexpected token in '.loc' directive");
3087 if (Name == "basic_block")
3088 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3089 else if (Name == "prologue_end")
3090 Flags |= DWARF2_FLAG_PROLOGUE_END;
3091 else if (Name == "epilogue_begin")
3092 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3093 else if (Name == "is_stmt") {
3094 Loc = getTok().getLoc();
3095 const MCExpr *Value;
3096 if (getParser().ParseExpression(Value))
3098 // The expression must be the constant 0 or 1.
3099 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3100 int Value = MCE->getValue();
3102 Flags &= ~DWARF2_FLAG_IS_STMT;
3103 else if (Value == 1)
3104 Flags |= DWARF2_FLAG_IS_STMT;
3106 return Error(Loc, "is_stmt value not 0 or 1");
3109 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3112 else if (Name == "isa") {
3113 Loc = getTok().getLoc();
3114 const MCExpr *Value;
3115 if (getParser().ParseExpression(Value))
3117 // The expression must be a constant greater or equal to 0.
3118 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3119 int Value = MCE->getValue();
3121 return Error(Loc, "isa number less than zero");
3125 return Error(Loc, "isa number not a constant value");
3128 else if (Name == "discriminator") {
3129 if (getParser().ParseAbsoluteExpression(Discriminator))
3133 return Error(Loc, "unknown sub-directive in '.loc' directive");
3136 if (getLexer().is(AsmToken::EndOfStatement))
3141 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3142 Isa, Discriminator, StringRef());
3147 /// ParseDirectiveStabs
3148 /// ::= .stabs string, number, number, number
3149 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
3150 SMLoc DirectiveLoc) {
3151 return TokError("unsupported directive '" + Directive + "'");
3154 /// ParseDirectiveCFISections
3155 /// ::= .cfi_sections section [, section]
3156 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
3157 SMLoc DirectiveLoc) {
3162 if (getParser().ParseIdentifier(Name))
3163 return TokError("Expected an identifier");
3165 if (Name == ".eh_frame")
3167 else if (Name == ".debug_frame")
3170 if (getLexer().is(AsmToken::Comma)) {
3173 if (getParser().ParseIdentifier(Name))
3174 return TokError("Expected an identifier");
3176 if (Name == ".eh_frame")
3178 else if (Name == ".debug_frame")
3182 getStreamer().EmitCFISections(EH, Debug);
3187 /// ParseDirectiveCFIStartProc
3188 /// ::= .cfi_startproc
3189 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
3190 SMLoc DirectiveLoc) {
3191 getStreamer().EmitCFIStartProc();
3195 /// ParseDirectiveCFIEndProc
3196 /// ::= .cfi_endproc
3197 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
3198 getStreamer().EmitCFIEndProc();
3202 /// ParseRegisterOrRegisterNumber - parse register name or number.
3203 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3204 SMLoc DirectiveLoc) {
3207 if (getLexer().isNot(AsmToken::Integer)) {
3208 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3211 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
3213 return getParser().ParseAbsoluteExpression(Register);
3218 /// ParseDirectiveCFIDefCfa
3219 /// ::= .cfi_def_cfa register, offset
3220 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3221 SMLoc DirectiveLoc) {
3222 int64_t Register = 0;
3223 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3226 if (getLexer().isNot(AsmToken::Comma))
3227 return TokError("unexpected token in directive");
3231 if (getParser().ParseAbsoluteExpression(Offset))
3234 getStreamer().EmitCFIDefCfa(Register, Offset);
3238 /// ParseDirectiveCFIDefCfaOffset
3239 /// ::= .cfi_def_cfa_offset offset
3240 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3241 SMLoc DirectiveLoc) {
3243 if (getParser().ParseAbsoluteExpression(Offset))
3246 getStreamer().EmitCFIDefCfaOffset(Offset);
3250 /// ParseDirectiveCFIAdjustCfaOffset
3251 /// ::= .cfi_adjust_cfa_offset adjustment
3252 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3253 SMLoc DirectiveLoc) {
3254 int64_t Adjustment = 0;
3255 if (getParser().ParseAbsoluteExpression(Adjustment))
3258 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3262 /// ParseDirectiveCFIDefCfaRegister
3263 /// ::= .cfi_def_cfa_register register
3264 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3265 SMLoc DirectiveLoc) {
3266 int64_t Register = 0;
3267 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3270 getStreamer().EmitCFIDefCfaRegister(Register);
3274 /// ParseDirectiveCFIOffset
3275 /// ::= .cfi_offset register, offset
3276 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3277 int64_t Register = 0;
3280 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3283 if (getLexer().isNot(AsmToken::Comma))
3284 return TokError("unexpected token in directive");
3287 if (getParser().ParseAbsoluteExpression(Offset))
3290 getStreamer().EmitCFIOffset(Register, Offset);
3294 /// ParseDirectiveCFIRelOffset
3295 /// ::= .cfi_rel_offset register, offset
3296 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3297 SMLoc DirectiveLoc) {
3298 int64_t Register = 0;
3300 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3303 if (getLexer().isNot(AsmToken::Comma))
3304 return TokError("unexpected token in directive");
3308 if (getParser().ParseAbsoluteExpression(Offset))
3311 getStreamer().EmitCFIRelOffset(Register, Offset);
3315 static bool isValidEncoding(int64_t Encoding) {
3316 if (Encoding & ~0xff)
3319 if (Encoding == dwarf::DW_EH_PE_omit)
3322 const unsigned Format = Encoding & 0xf;
3323 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3324 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3325 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3326 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3329 const unsigned Application = Encoding & 0x70;
3330 if (Application != dwarf::DW_EH_PE_absptr &&
3331 Application != dwarf::DW_EH_PE_pcrel)
3337 /// ParseDirectiveCFIPersonalityOrLsda
3338 /// ::= .cfi_personality encoding, [symbol_name]
3339 /// ::= .cfi_lsda encoding, [symbol_name]
3340 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
3341 SMLoc DirectiveLoc) {
3342 int64_t Encoding = 0;
3343 if (getParser().ParseAbsoluteExpression(Encoding))
3345 if (Encoding == dwarf::DW_EH_PE_omit)
3348 if (!isValidEncoding(Encoding))
3349 return TokError("unsupported encoding.");
3351 if (getLexer().isNot(AsmToken::Comma))
3352 return TokError("unexpected token in directive");
3356 if (getParser().ParseIdentifier(Name))
3357 return TokError("expected identifier in directive");
3359 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3361 if (IDVal == ".cfi_personality")
3362 getStreamer().EmitCFIPersonality(Sym, Encoding);
3364 assert(IDVal == ".cfi_lsda");
3365 getStreamer().EmitCFILsda(Sym, Encoding);
3370 /// ParseDirectiveCFIRememberState
3371 /// ::= .cfi_remember_state
3372 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3373 SMLoc DirectiveLoc) {
3374 getStreamer().EmitCFIRememberState();
3378 /// ParseDirectiveCFIRestoreState
3379 /// ::= .cfi_remember_state
3380 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3381 SMLoc DirectiveLoc) {
3382 getStreamer().EmitCFIRestoreState();
3386 /// ParseDirectiveCFISameValue
3387 /// ::= .cfi_same_value register
3388 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3389 SMLoc DirectiveLoc) {
3390 int64_t Register = 0;
3392 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3395 getStreamer().EmitCFISameValue(Register);
3400 /// ParseDirectiveCFIRestore
3401 /// ::= .cfi_restore register
3402 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
3403 SMLoc DirectiveLoc) {
3404 int64_t Register = 0;
3405 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3408 getStreamer().EmitCFIRestore(Register);
3413 /// ParseDirectiveCFIEscape
3414 /// ::= .cfi_escape expression[,...]
3415 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3416 SMLoc DirectiveLoc) {
3419 if (getParser().ParseAbsoluteExpression(CurrValue))
3422 Values.push_back((uint8_t)CurrValue);
3424 while (getLexer().is(AsmToken::Comma)) {
3427 if (getParser().ParseAbsoluteExpression(CurrValue))
3430 Values.push_back((uint8_t)CurrValue);
3433 getStreamer().EmitCFIEscape(Values);
3437 /// ParseDirectiveCFISignalFrame
3438 /// ::= .cfi_signal_frame
3439 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3440 SMLoc DirectiveLoc) {
3441 if (getLexer().isNot(AsmToken::EndOfStatement))
3442 return Error(getLexer().getLoc(),
3443 "unexpected token in '" + Directive + "' directive");
3445 getStreamer().EmitCFISignalFrame();
3450 /// ParseDirectiveCFIUndefined
3451 /// ::= .cfi_undefined register
3452 bool GenericAsmParser::ParseDirectiveCFIUndefined(StringRef Directive,
3453 SMLoc DirectiveLoc) {
3454 int64_t Register = 0;
3456 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3459 getStreamer().EmitCFIUndefined(Register);
3464 /// ParseDirectiveCFIRegister
3465 /// ::= .cfi_register register, register
3466 bool GenericAsmParser::ParseDirectiveCFIRegister(StringRef Directive,
3467 SMLoc DirectiveLoc) {
3468 int64_t Register1 = 0;
3470 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3473 if (getLexer().isNot(AsmToken::Comma))
3474 return TokError("unexpected token in directive");
3477 int64_t Register2 = 0;
3479 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3482 getStreamer().EmitCFIRegister(Register1, Register2);
3487 /// ParseDirectiveMacrosOnOff
3490 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3491 SMLoc DirectiveLoc) {
3492 if (getLexer().isNot(AsmToken::EndOfStatement))
3493 return Error(getLexer().getLoc(),
3494 "unexpected token in '" + Directive + "' directive");
3496 getParser().MacrosEnabled = Directive == ".macros_on";
3501 /// ParseDirectiveMacro
3502 /// ::= .macro name [parameters]
3503 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3504 SMLoc DirectiveLoc) {
3506 if (getParser().ParseIdentifier(Name))
3507 return TokError("expected identifier in '.macro' directive");
3509 MacroParameters Parameters;
3510 // Argument delimiter is initially unknown. It will be set by
3511 // ParseMacroArgument()
3512 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3513 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3515 MacroParameter Parameter;
3516 if (getParser().ParseIdentifier(Parameter.first))
3517 return TokError("expected identifier in '.macro' directive");
3519 if (getLexer().is(AsmToken::Equal)) {
3521 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3525 Parameters.push_back(Parameter);
3527 if (getLexer().is(AsmToken::Comma))
3529 else if (getLexer().is(AsmToken::EndOfStatement))
3534 // Eat the end of statement.
3537 AsmToken EndToken, StartToken = getTok();
3539 // Lex the macro definition.
3541 // Check whether we have reached the end of the file.
3542 if (getLexer().is(AsmToken::Eof))
3543 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3545 // Otherwise, check whether we have reach the .endmacro.
3546 if (getLexer().is(AsmToken::Identifier) &&
3547 (getTok().getIdentifier() == ".endm" ||
3548 getTok().getIdentifier() == ".endmacro")) {
3549 EndToken = getTok();
3551 if (getLexer().isNot(AsmToken::EndOfStatement))
3552 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3557 // Otherwise, scan til the end of the statement.
3558 getParser().EatToEndOfStatement();
3561 if (getParser().MacroMap.lookup(Name)) {
3562 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3565 const char *BodyStart = StartToken.getLoc().getPointer();
3566 const char *BodyEnd = EndToken.getLoc().getPointer();
3567 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3568 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3572 /// ParseDirectiveEndMacro
3575 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3576 SMLoc DirectiveLoc) {
3577 if (getLexer().isNot(AsmToken::EndOfStatement))
3578 return TokError("unexpected token in '" + Directive + "' directive");
3580 // If we are inside a macro instantiation, terminate the current
3582 if (!getParser().ActiveMacros.empty()) {
3583 getParser().HandleMacroExit();
3587 // Otherwise, this .endmacro is a stray entry in the file; well formed
3588 // .endmacro directives are handled during the macro definition parsing.
3589 return TokError("unexpected '" + Directive + "' in file, "
3590 "no current macro definition");
3593 /// ParseDirectivePurgeMacro
3595 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3596 SMLoc DirectiveLoc) {
3598 if (getParser().ParseIdentifier(Name))
3599 return TokError("expected identifier in '.purgem' directive");
3601 if (getLexer().isNot(AsmToken::EndOfStatement))
3602 return TokError("unexpected token in '.purgem' directive");
3604 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3605 if (I == getParser().MacroMap.end())
3606 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3608 // Undefine the macro.
3609 delete I->getValue();
3610 getParser().MacroMap.erase(I);
3614 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3615 getParser().CheckForValidSection();
3617 const MCExpr *Value;
3619 if (getParser().ParseExpression(Value))
3622 if (getLexer().isNot(AsmToken::EndOfStatement))
3623 return TokError("unexpected token in directive");
3625 if (DirName[1] == 's')
3626 getStreamer().EmitSLEB128Value(Value);
3628 getStreamer().EmitULEB128Value(Value);
3633 Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3634 AsmToken EndToken, StartToken = getTok();
3636 unsigned NestLevel = 0;
3638 // Check whether we have reached the end of the file.
3639 if (getLexer().is(AsmToken::Eof)) {
3640 Error(DirectiveLoc, "no matching '.endr' in definition");
3644 if (Lexer.is(AsmToken::Identifier) &&
3645 (getTok().getIdentifier() == ".rept")) {
3649 // Otherwise, check whether we have reached the .endr.
3650 if (Lexer.is(AsmToken::Identifier) &&
3651 getTok().getIdentifier() == ".endr") {
3652 if (NestLevel == 0) {
3653 EndToken = getTok();
3655 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3656 TokError("unexpected token in '.endr' directive");
3664 // Otherwise, scan till the end of the statement.
3665 EatToEndOfStatement();
3668 const char *BodyStart = StartToken.getLoc().getPointer();
3669 const char *BodyEnd = EndToken.getLoc().getPointer();
3670 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3672 // We Are Anonymous.
3674 MacroParameters Parameters;
3675 return new Macro(Name, Body, Parameters);
3678 void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3679 raw_svector_ostream &OS) {
3682 MemoryBuffer *Instantiation =
3683 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3685 // Create the macro instantiation object and add to the current macro
3686 // instantiation stack.
3687 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3691 ActiveMacros.push_back(MI);
3693 // Jump to the macro instantiation and prime the lexer.
3694 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3695 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3699 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3701 if (ParseAbsoluteExpression(Count))
3702 return TokError("unexpected token in '.rept' directive");
3705 return TokError("Count is negative");
3707 if (Lexer.isNot(AsmToken::EndOfStatement))
3708 return TokError("unexpected token in '.rept' directive");
3710 // Eat the end of statement.
3713 // Lex the rept definition.
3714 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3718 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3719 // to hold the macro body with substitutions.
3720 SmallString<256> Buf;
3721 MacroParameters Parameters;
3723 raw_svector_ostream OS(Buf);
3725 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3728 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3733 /// ParseDirectiveIrp
3734 /// ::= .irp symbol,values
3735 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3736 MacroParameters Parameters;
3737 MacroParameter Parameter;
3739 if (ParseIdentifier(Parameter.first))
3740 return TokError("expected identifier in '.irp' directive");
3742 Parameters.push_back(Parameter);
3744 if (Lexer.isNot(AsmToken::Comma))
3745 return TokError("expected comma in '.irp' directive");
3750 if (ParseMacroArguments(0, A))
3753 // Eat the end of statement.
3756 // Lex the irp definition.
3757 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3761 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3762 // to hold the macro body with substitutions.
3763 SmallString<256> Buf;
3764 raw_svector_ostream OS(Buf);
3766 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3767 MacroArguments Args;
3770 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3774 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3779 /// ParseDirectiveIrpc
3780 /// ::= .irpc symbol,values
3781 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3782 MacroParameters Parameters;
3783 MacroParameter Parameter;
3785 if (ParseIdentifier(Parameter.first))
3786 return TokError("expected identifier in '.irpc' directive");
3788 Parameters.push_back(Parameter);
3790 if (Lexer.isNot(AsmToken::Comma))
3791 return TokError("expected comma in '.irpc' directive");
3796 if (ParseMacroArguments(0, A))
3799 if (A.size() != 1 || A.front().size() != 1)
3800 return TokError("unexpected token in '.irpc' directive");
3802 // Eat the end of statement.
3805 // Lex the irpc definition.
3806 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3810 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3811 // to hold the macro body with substitutions.
3812 SmallString<256> Buf;
3813 raw_svector_ostream OS(Buf);
3815 StringRef Values = A.front().front().getString();
3816 std::size_t I, End = Values.size();
3817 for (I = 0; I < End; ++I) {
3819 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3821 MacroArguments Args;
3822 Args.push_back(Arg);
3824 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3828 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3833 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3834 if (ActiveMacros.empty())
3835 return TokError("unmatched '.endr' directive");
3837 // The only .repl that should get here are the ones created by
3838 // InstantiateMacroLikeBody.
3839 assert(getLexer().is(AsmToken::EndOfStatement));
3845 bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3846 const MCExpr *Value;
3847 SMLoc ExprLoc = getLexer().getLoc();
3848 if (ParseExpression(Value))
3850 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3852 return Error(ExprLoc, "unexpected expression in _emit");
3853 uint64_t IntValue = MCE->getValue();
3854 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3855 return Error(ExprLoc, "literal value out of range for directive");
3857 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3861 bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3862 unsigned &NumOutputs, unsigned &NumInputs,
3863 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
3864 SmallVectorImpl<std::string> &Constraints,
3865 SmallVectorImpl<std::string> &Clobbers,
3866 const MCInstrInfo *MII,
3867 const MCInstPrinter *IP,
3868 MCAsmParserSemaCallback &SI) {
3869 SmallVector<void *, 4> InputDecls;
3870 SmallVector<void *, 4> OutputDecls;
3871 SmallVector<bool, 4> InputDeclsAddressOf;
3872 SmallVector<bool, 4> OutputDeclsAddressOf;
3873 SmallVector<std::string, 4> InputConstraints;
3874 SmallVector<std::string, 4> OutputConstraints;
3875 std::set<std::string> ClobberRegs;
3877 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
3882 // While we have input, parse each statement.
3883 unsigned InputIdx = 0;
3884 unsigned OutputIdx = 0;
3885 while (getLexer().isNot(AsmToken::Eof)) {
3886 ParseStatementInfo Info(&AsmStrRewrites);
3887 if (ParseStatement(Info))
3890 if (Info.ParseError)
3893 if (Info.Opcode != ~0U) {
3894 const MCInstrDesc &Desc = MII->get(Info.Opcode);
3896 // Build the list of clobbers, outputs and inputs.
3897 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3898 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
3901 if (Operand->isImm()) {
3902 if (Operand->needAsmRewrite())
3903 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3904 Operand->getStartLoc()));
3908 // Register operand.
3909 if (Operand->isReg() && !Operand->needAddressOf()) {
3910 unsigned NumDefs = Desc.getNumDefs();
3912 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3914 raw_string_ostream OS(Reg);
3915 IP->printRegName(OS, Operand->getReg());
3916 ClobberRegs.insert(StringRef(OS.str()));
3921 // Expr/Input or Output.
3924 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3927 bool isOutput = (i == 1) && Desc.mayStore();
3928 if (Operand->isMem() && Operand->needSizeDirective())
3929 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
3930 Operand->getStartLoc(),
3932 Operand->getMemSize()));
3934 std::string Constraint = "=";
3936 OutputDecls.push_back(OpDecl);
3937 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
3938 Constraint += Operand->getConstraint().str();
3939 OutputConstraints.push_back(Constraint);
3940 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
3941 Operand->getStartLoc(),
3942 Operand->getNameLen()));
3944 InputDecls.push_back(OpDecl);
3945 InputDeclsAddressOf.push_back(Operand->needAddressOf());
3946 InputConstraints.push_back(Operand->getConstraint().str());
3947 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
3948 Operand->getStartLoc(),
3949 Operand->getNameLen()));
3956 // Set the number of Outputs and Inputs.
3957 NumOutputs = OutputDecls.size();
3958 NumInputs = InputDecls.size();
3960 // Set the unique clobbers.
3961 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3962 E = ClobberRegs.end(); I != E; ++I)
3963 Clobbers.push_back(*I);
3965 // Merge the various outputs and inputs. Output are expected first.
3966 if (NumOutputs || NumInputs) {
3967 unsigned NumExprs = NumOutputs + NumInputs;
3968 OpDecls.resize(NumExprs);
3969 Constraints.resize(NumExprs);
3970 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3971 // constraint for addressof. This needs to be cleaned up!
3972 for (unsigned i = 0; i < NumOutputs; ++i) {
3973 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
3974 Constraints[i] = OutputDeclsAddressOf[i] ? "=r" : OutputConstraints[i];
3976 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
3977 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
3978 Constraints[j] = InputDeclsAddressOf[i] ? "r" : InputConstraints[i];
3982 // Build the IR assembly string.
3983 std::string AsmStringIR;
3984 AsmRewriteKind PrevKind = AOK_Imm;
3985 raw_string_ostream OS(AsmStringIR);
3986 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
3987 for (SmallVectorImpl<struct AsmRewrite>::iterator
3988 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3989 const char *Loc = (*I).Loc.getPointer();
3991 AsmRewriteKind Kind = (*I).Kind;
3993 // Emit everything up to the immediate/expression. If the previous rewrite
3994 // was a size directive, then this has already been done.
3995 if (PrevKind != AOK_SizeDirective)
3996 OS << StringRef(Start, Loc - Start);
3999 // Skip the original expression.
4000 if (Kind == AOK_Skip) {
4001 Start = Loc + (*I).Len;
4005 // Rewrite expressions in $N notation.
4023 case AOK_SizeDirective:
4026 case 8: OS << "byte ptr "; break;
4027 case 16: OS << "word ptr "; break;
4028 case 32: OS << "dword ptr "; break;
4029 case 64: OS << "qword ptr "; break;
4030 case 80: OS << "xword ptr "; break;
4031 case 128: OS << "xmmword ptr "; break;
4032 case 256: OS << "ymmword ptr "; break;
4038 case AOK_DotOperator:
4043 // Skip the original expression.
4044 if (Kind != AOK_SizeDirective)
4045 Start = Loc + (*I).Len;
4048 // Emit the remainder of the asm string.
4049 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4050 if (Start != AsmEnd)
4051 OS << StringRef(Start, AsmEnd - Start);
4053 AsmString = OS.str();
4057 /// \brief Create an MCAsmParser instance.
4058 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
4059 MCContext &C, MCStreamer &Out,
4060 const MCAsmInfo &MAI) {
4061 return new AsmParser(SM, C, Out, MAI);