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 MacrosEnabledFlag : 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);
229 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
230 /// and set \p Res to the identifier contents.
231 virtual bool ParseIdentifier(StringRef &Res);
232 virtual void EatToEndOfStatement();
234 virtual bool MacrosEnabled() {return MacrosEnabledFlag;}
235 virtual void SetMacrosEnabled(bool flag) {MacrosEnabledFlag = flag;}
240 void CheckForValidSection();
242 bool ParseStatement(ParseStatementInfo &Info);
243 void EatToEndOfLine();
244 bool ParseCppHashLineFilenameComment(const SMLoc &L);
246 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
247 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
248 const MacroParameters &Parameters,
249 const MacroArguments &A,
251 void HandleMacroExit();
253 void PrintMacroInstantiations();
254 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
255 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
256 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
258 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
260 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
261 bool EnterIncludeFile(const std::string &Filename);
262 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
263 /// This returns true on failure.
264 bool ProcessIncbinFile(const std::string &Filename);
266 /// \brief Reset the current lexer position to that given by \p Loc. The
267 /// current token is not set; clients should ensure Lex() is called
270 /// \param InBuffer If not -1, should be the known buffer id that contains the
272 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
274 bool ParseMacroArgument(MacroArgument &MA,
275 AsmToken::TokenKind &ArgumentDelimiter);
276 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
278 /// \brief Parse up to the end of statement and a return the contents from the
279 /// current token until the end of the statement; the current token on exit
280 /// will be either the EndOfStatement or EOF.
281 virtual StringRef ParseStringToEndOfStatement();
283 /// \brief Parse until the end of a statement or a comma is encountered,
284 /// return the contents from the current token up to the end or comma.
285 StringRef ParseStringToComma();
287 bool ParseAssignment(StringRef Name, bool allow_redef,
288 bool NoDeadStrip = false);
290 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
291 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
292 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
293 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
295 // Directive Parsing.
298 DK_NO_DIRECTIVE, // Placeholder
299 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
300 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
301 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
302 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
303 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
304 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
305 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
306 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
307 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
308 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
309 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
310 DK_ELSEIF, DK_ELSE, DK_ENDIF
313 StringMap<DirectiveKind> DirectiveKindMapping;
315 // ".ascii", ".asciz", ".string"
316 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
317 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
318 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
319 bool ParseDirectiveFill(); // ".fill"
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");
402 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveSpace>(".space");
403 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveSpace>(".skip");
406 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
408 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
410 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
412 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
414 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
415 ".cfi_def_cfa_offset");
416 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
417 ".cfi_adjust_cfa_offset");
418 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
419 ".cfi_def_cfa_register");
420 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
422 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
425 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
427 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
429 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
431 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
433 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
435 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
437 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
439 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
441 &GenericAsmParser::ParseDirectiveCFIUndefined>(".cfi_undefined");
443 &GenericAsmParser::ParseDirectiveCFIRegister>(".cfi_register");
446 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
448 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
450 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
451 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
452 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
453 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
455 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
456 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
459 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
461 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
462 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
463 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
464 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
465 bool ParseDirectiveSpace(StringRef, SMLoc DirectiveLoc);
466 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
467 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
468 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
469 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
470 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
471 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
472 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
473 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
474 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
475 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
476 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
477 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
478 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
479 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
480 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
481 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
482 bool ParseDirectiveCFIUndefined(StringRef, SMLoc DirectiveLoc);
483 bool ParseDirectiveCFIRegister(StringRef, SMLoc DirectiveLoc);
485 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
486 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
487 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
488 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
490 bool ParseDirectiveLEB128(StringRef, SMLoc);
497 extern MCAsmParserExtension *createDarwinAsmParser();
498 extern MCAsmParserExtension *createELFAsmParser();
499 extern MCAsmParserExtension *createCOFFAsmParser();
503 enum { DEFAULT_ADDRSPACE = 0 };
505 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
506 MCStreamer &_Out, const MCAsmInfo &_MAI)
507 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
508 GenericParser(new GenericAsmParser), PlatformParser(0),
509 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
510 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
511 // Save the old handler.
512 SavedDiagHandler = SrcMgr.getDiagHandler();
513 SavedDiagContext = SrcMgr.getDiagContext();
514 // Set our own handler which calls the saved handler.
515 SrcMgr.setDiagHandler(DiagHandler, this);
516 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
518 // Initialize the generic parser.
519 GenericParser->Initialize(*this);
521 // Initialize the platform / file format parser.
523 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
525 if (_MAI.hasMicrosoftFastStdCallMangling()) {
526 PlatformParser = createCOFFAsmParser();
527 PlatformParser->Initialize(*this);
528 } else if (_MAI.hasSubsectionsViaSymbols()) {
529 PlatformParser = createDarwinAsmParser();
530 PlatformParser->Initialize(*this);
533 PlatformParser = createELFAsmParser();
534 PlatformParser->Initialize(*this);
537 initializeDirectiveKindMapping();
540 AsmParser::~AsmParser() {
541 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
543 // Destroy any macros.
544 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
545 ie = MacroMap.end(); it != ie; ++it)
546 delete it->getValue();
548 delete PlatformParser;
549 delete GenericParser;
552 void AsmParser::PrintMacroInstantiations() {
553 // Print the active macro instantiation stack.
554 for (std::vector<MacroInstantiation*>::const_reverse_iterator
555 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
556 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
557 "while in macro instantiation");
560 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
561 if (FatalAssemblerWarnings)
562 return Error(L, Msg, Ranges);
563 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
564 PrintMacroInstantiations();
568 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
570 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
571 PrintMacroInstantiations();
575 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
576 std::string IncludedFile;
577 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
583 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
588 /// Process the specified .incbin file by seaching for it in the include paths
589 /// then just emitting the byte contents of the file to the streamer. This
590 /// returns true on failure.
591 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
592 std::string IncludedFile;
593 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
597 // Pick up the bytes from the file and emit them.
598 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
603 void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
604 if (InBuffer != -1) {
605 CurBuffer = InBuffer;
607 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
609 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
612 const AsmToken &AsmParser::Lex() {
613 const AsmToken *tok = &Lexer.Lex();
615 if (tok->is(AsmToken::Eof)) {
616 // If this is the end of an included file, pop the parent file off the
618 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
619 if (ParentIncludeLoc != SMLoc()) {
620 JumpToLoc(ParentIncludeLoc);
625 if (tok->is(AsmToken::Error))
626 Error(Lexer.getErrLoc(), Lexer.getErr());
631 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
632 // Create the initial section, if requested.
633 if (!NoInitialTextSection)
640 AsmCond StartingCondState = TheCondState;
642 // If we are generating dwarf for assembly source files save the initial text
643 // section and generate a .file directive.
644 if (getContext().getGenDwarfForAssembly()) {
645 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
646 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
647 getStreamer().EmitLabel(SectionStartSym);
648 getContext().setGenDwarfSectionStartSym(SectionStartSym);
649 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
651 getContext().getMainFileName());
654 // While we have input, parse each statement.
655 while (Lexer.isNot(AsmToken::Eof)) {
656 ParseStatementInfo Info;
657 if (!ParseStatement(Info)) continue;
659 // We had an error, validate that one was emitted and recover by skipping to
661 assert(HadError && "Parse statement returned an error, but none emitted!");
662 EatToEndOfStatement();
665 if (TheCondState.TheCond != StartingCondState.TheCond ||
666 TheCondState.Ignore != StartingCondState.Ignore)
667 return TokError("unmatched .ifs or .elses");
669 // Check to see there are no empty DwarfFile slots.
670 const std::vector<MCDwarfFile *> &MCDwarfFiles =
671 getContext().getMCDwarfFiles();
672 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
673 if (!MCDwarfFiles[i])
674 TokError("unassigned file number: " + Twine(i) + " for .file directives");
677 // Check to see that all assembler local symbols were actually defined.
678 // Targets that don't do subsections via symbols may not want this, though,
679 // so conservatively exclude them. Only do this if we're finalizing, though,
680 // as otherwise we won't necessarilly have seen everything yet.
681 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
682 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
683 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
686 MCSymbol *Sym = i->getValue();
687 // Variable symbols may not be marked as defined, so check those
688 // explicitly. If we know it's a variable, we have a definition for
689 // the purposes of this check.
690 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
691 // FIXME: We would really like to refer back to where the symbol was
692 // first referenced for a source location. We need to add something
693 // to track that. Currently, we just point to the end of the file.
694 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
695 "assembler local symbol '" + Sym->getName() +
701 // Finalize the output stream if there are no errors and if the client wants
703 if (!HadError && !NoFinalize)
709 void AsmParser::CheckForValidSection() {
710 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
711 TokError("expected section directive before assembly directive");
712 Out.SwitchSection(Ctx.getMachOSection(
714 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
715 0, SectionKind::getText()));
719 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
720 void AsmParser::EatToEndOfStatement() {
721 while (Lexer.isNot(AsmToken::EndOfStatement) &&
722 Lexer.isNot(AsmToken::Eof))
726 if (Lexer.is(AsmToken::EndOfStatement))
730 StringRef AsmParser::ParseStringToEndOfStatement() {
731 const char *Start = getTok().getLoc().getPointer();
733 while (Lexer.isNot(AsmToken::EndOfStatement) &&
734 Lexer.isNot(AsmToken::Eof))
737 const char *End = getTok().getLoc().getPointer();
738 return StringRef(Start, End - Start);
741 StringRef AsmParser::ParseStringToComma() {
742 const char *Start = getTok().getLoc().getPointer();
744 while (Lexer.isNot(AsmToken::EndOfStatement) &&
745 Lexer.isNot(AsmToken::Comma) &&
746 Lexer.isNot(AsmToken::Eof))
749 const char *End = getTok().getLoc().getPointer();
750 return StringRef(Start, End - Start);
753 /// ParseParenExpr - Parse a paren expression and return it.
754 /// NOTE: This assumes the leading '(' has already been consumed.
756 /// parenexpr ::= expr)
758 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
759 if (ParseExpression(Res)) return true;
760 if (Lexer.isNot(AsmToken::RParen))
761 return TokError("expected ')' in parentheses expression");
762 EndLoc = Lexer.getTok().getEndLoc();
767 /// ParseBracketExpr - Parse a bracket expression and return it.
768 /// NOTE: This assumes the leading '[' has already been consumed.
770 /// bracketexpr ::= expr]
772 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
773 if (ParseExpression(Res)) return true;
774 if (Lexer.isNot(AsmToken::RBrac))
775 return TokError("expected ']' in brackets expression");
776 EndLoc = Lexer.getTok().getEndLoc();
781 /// ParsePrimaryExpr - Parse a primary expression and return it.
782 /// primaryexpr ::= (parenexpr
783 /// primaryexpr ::= symbol
784 /// primaryexpr ::= number
785 /// primaryexpr ::= '.'
786 /// primaryexpr ::= ~,+,- primaryexpr
787 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
788 switch (Lexer.getKind()) {
790 return TokError("unknown token in expression");
791 // If we have an error assume that we've already handled it.
792 case AsmToken::Error:
794 case AsmToken::Exclaim:
795 Lex(); // Eat the operator.
796 if (ParsePrimaryExpr(Res, EndLoc))
798 Res = MCUnaryExpr::CreateLNot(Res, getContext());
800 case AsmToken::Dollar:
801 case AsmToken::String:
802 case AsmToken::Identifier: {
803 StringRef Identifier;
804 if (ParseIdentifier(Identifier))
807 EndLoc = SMLoc::getFromPointer(Identifier.end());
809 // This is a symbol reference.
810 std::pair<StringRef, StringRef> Split = Identifier.split('@');
811 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
813 // Lookup the symbol variant if used.
814 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
815 if (Split.first.size() != Identifier.size()) {
816 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
817 if (Variant == MCSymbolRefExpr::VK_Invalid) {
818 Variant = MCSymbolRefExpr::VK_None;
819 return TokError("invalid variant '" + Split.second + "'");
823 // If this is an absolute variable reference, substitute it now to preserve
824 // semantics in the face of reassignment.
825 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
827 return Error(EndLoc, "unexpected modifier on variable reference");
829 Res = Sym->getVariableValue();
833 // Otherwise create a symbol ref.
834 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
837 case AsmToken::Integer: {
838 SMLoc Loc = getTok().getLoc();
839 int64_t IntVal = getTok().getIntVal();
840 Res = MCConstantExpr::Create(IntVal, getContext());
841 EndLoc = Lexer.getTok().getEndLoc();
843 // Look for 'b' or 'f' following an Integer as a directional label
844 if (Lexer.getKind() == AsmToken::Identifier) {
845 StringRef IDVal = getTok().getString();
846 if (IDVal == "f" || IDVal == "b"){
847 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
848 IDVal == "f" ? 1 : 0);
849 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
851 if (IDVal == "b" && Sym->isUndefined())
852 return Error(Loc, "invalid reference to undefined symbol");
853 EndLoc = Lexer.getTok().getEndLoc();
854 Lex(); // Eat identifier.
859 case AsmToken::Real: {
860 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
861 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
862 Res = MCConstantExpr::Create(IntVal, getContext());
863 EndLoc = Lexer.getTok().getEndLoc();
867 case AsmToken::Dot: {
868 // This is a '.' reference, which references the current PC. Emit a
869 // temporary label to the streamer and refer to it.
870 MCSymbol *Sym = Ctx.CreateTempSymbol();
872 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
873 EndLoc = Lexer.getTok().getEndLoc();
874 Lex(); // Eat identifier.
877 case AsmToken::LParen:
878 Lex(); // Eat the '('.
879 return ParseParenExpr(Res, EndLoc);
880 case AsmToken::LBrac:
881 if (!PlatformParser->HasBracketExpressions())
882 return TokError("brackets expression not supported on this target");
883 Lex(); // Eat the '['.
884 return ParseBracketExpr(Res, EndLoc);
885 case AsmToken::Minus:
886 Lex(); // Eat the operator.
887 if (ParsePrimaryExpr(Res, EndLoc))
889 Res = MCUnaryExpr::CreateMinus(Res, getContext());
892 Lex(); // Eat the operator.
893 if (ParsePrimaryExpr(Res, EndLoc))
895 Res = MCUnaryExpr::CreatePlus(Res, getContext());
897 case AsmToken::Tilde:
898 Lex(); // Eat the operator.
899 if (ParsePrimaryExpr(Res, EndLoc))
901 Res = MCUnaryExpr::CreateNot(Res, getContext());
906 bool AsmParser::ParseExpression(const MCExpr *&Res) {
908 return ParseExpression(Res, EndLoc);
912 AsmParser::ApplyModifierToExpr(const MCExpr *E,
913 MCSymbolRefExpr::VariantKind Variant) {
914 // Recurse over the given expression, rebuilding it to apply the given variant
915 // if there is exactly one symbol.
916 switch (E->getKind()) {
918 case MCExpr::Constant:
921 case MCExpr::SymbolRef: {
922 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
924 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
925 TokError("invalid variant on expression '" +
926 getTok().getIdentifier() + "' (already modified)");
930 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
933 case MCExpr::Unary: {
934 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
935 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
938 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
941 case MCExpr::Binary: {
942 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
943 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
944 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
949 if (!LHS) LHS = BE->getLHS();
950 if (!RHS) RHS = BE->getRHS();
952 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
956 llvm_unreachable("Invalid expression kind!");
959 /// ParseExpression - Parse an expression and return it.
961 /// expr ::= expr &&,|| expr -> lowest.
962 /// expr ::= expr |,^,&,! expr
963 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
964 /// expr ::= expr <<,>> expr
965 /// expr ::= expr +,- expr
966 /// expr ::= expr *,/,% expr -> highest.
967 /// expr ::= primaryexpr
969 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
970 // Parse the expression.
972 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
975 // As a special case, we support 'a op b @ modifier' by rewriting the
976 // expression to include the modifier. This is inefficient, but in general we
977 // expect users to use 'a@modifier op b'.
978 if (Lexer.getKind() == AsmToken::At) {
981 if (Lexer.isNot(AsmToken::Identifier))
982 return TokError("unexpected symbol modifier following '@'");
984 MCSymbolRefExpr::VariantKind Variant =
985 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
986 if (Variant == MCSymbolRefExpr::VK_Invalid)
987 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
989 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
991 return TokError("invalid modifier '" + getTok().getIdentifier() +
992 "' (no symbols present)");
999 // Try to constant fold it up front, if possible.
1001 if (Res->EvaluateAsAbsolute(Value))
1002 Res = MCConstantExpr::Create(Value, getContext());
1007 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1009 return ParseParenExpr(Res, EndLoc) ||
1010 ParseBinOpRHS(1, Res, EndLoc);
1013 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
1016 SMLoc StartLoc = Lexer.getLoc();
1017 if (ParseExpression(Expr))
1020 if (!Expr->EvaluateAsAbsolute(Res))
1021 return Error(StartLoc, "expected absolute expression");
1026 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1027 MCBinaryExpr::Opcode &Kind) {
1030 return 0; // not a binop.
1032 // Lowest Precedence: &&, ||
1033 case AsmToken::AmpAmp:
1034 Kind = MCBinaryExpr::LAnd;
1036 case AsmToken::PipePipe:
1037 Kind = MCBinaryExpr::LOr;
1041 // Low Precedence: |, &, ^
1043 // FIXME: gas seems to support '!' as an infix operator?
1044 case AsmToken::Pipe:
1045 Kind = MCBinaryExpr::Or;
1047 case AsmToken::Caret:
1048 Kind = MCBinaryExpr::Xor;
1051 Kind = MCBinaryExpr::And;
1054 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1055 case AsmToken::EqualEqual:
1056 Kind = MCBinaryExpr::EQ;
1058 case AsmToken::ExclaimEqual:
1059 case AsmToken::LessGreater:
1060 Kind = MCBinaryExpr::NE;
1062 case AsmToken::Less:
1063 Kind = MCBinaryExpr::LT;
1065 case AsmToken::LessEqual:
1066 Kind = MCBinaryExpr::LTE;
1068 case AsmToken::Greater:
1069 Kind = MCBinaryExpr::GT;
1071 case AsmToken::GreaterEqual:
1072 Kind = MCBinaryExpr::GTE;
1075 // Intermediate Precedence: <<, >>
1076 case AsmToken::LessLess:
1077 Kind = MCBinaryExpr::Shl;
1079 case AsmToken::GreaterGreater:
1080 Kind = MCBinaryExpr::Shr;
1083 // High Intermediate Precedence: +, -
1084 case AsmToken::Plus:
1085 Kind = MCBinaryExpr::Add;
1087 case AsmToken::Minus:
1088 Kind = MCBinaryExpr::Sub;
1091 // Highest Precedence: *, /, %
1092 case AsmToken::Star:
1093 Kind = MCBinaryExpr::Mul;
1095 case AsmToken::Slash:
1096 Kind = MCBinaryExpr::Div;
1098 case AsmToken::Percent:
1099 Kind = MCBinaryExpr::Mod;
1105 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1106 /// Res contains the LHS of the expression on input.
1107 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1110 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1111 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1113 // If the next token is lower precedence than we are allowed to eat, return
1114 // successfully with what we ate already.
1115 if (TokPrec < Precedence)
1120 // Eat the next primary expression.
1122 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1124 // If BinOp binds less tightly with RHS than the operator after RHS, let
1125 // the pending operator take RHS as its LHS.
1126 MCBinaryExpr::Opcode Dummy;
1127 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1128 if (TokPrec < NextTokPrec) {
1129 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1132 // Merge LHS and RHS according to operator.
1133 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1138 /// ::= EndOfStatement
1139 /// ::= Label* Directive ...Operands... EndOfStatement
1140 /// ::= Label* Identifier OperandList* EndOfStatement
1141 bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
1142 if (Lexer.is(AsmToken::EndOfStatement)) {
1148 // Statements always start with an identifier or are a full line comment.
1149 AsmToken ID = getTok();
1150 SMLoc IDLoc = ID.getLoc();
1152 int64_t LocalLabelVal = -1;
1153 // A full line comment is a '#' as the first token.
1154 if (Lexer.is(AsmToken::Hash))
1155 return ParseCppHashLineFilenameComment(IDLoc);
1157 // Allow an integer followed by a ':' as a directional local label.
1158 if (Lexer.is(AsmToken::Integer)) {
1159 LocalLabelVal = getTok().getIntVal();
1160 if (LocalLabelVal < 0) {
1161 if (!TheCondState.Ignore)
1162 return TokError("unexpected token at start of statement");
1166 IDVal = getTok().getString();
1167 Lex(); // Consume the integer token to be used as an identifier token.
1168 if (Lexer.getKind() != AsmToken::Colon) {
1169 if (!TheCondState.Ignore)
1170 return TokError("unexpected token at start of statement");
1174 } else if (Lexer.is(AsmToken::Dot)) {
1175 // Treat '.' as a valid identifier in this context.
1179 } else if (ParseIdentifier(IDVal)) {
1180 if (!TheCondState.Ignore)
1181 return TokError("unexpected token at start of statement");
1185 // Handle conditional assembly here before checking for skipping. We
1186 // have to do this so that .endif isn't skipped in a ".if 0" block for
1188 StringMap<DirectiveKind>::const_iterator DirKindIt =
1189 DirectiveKindMapping.find(IDVal);
1190 DirectiveKind DirKind =
1191 (DirKindIt == DirectiveKindMapping.end()) ? DK_NO_DIRECTIVE :
1192 DirKindIt->getValue();
1197 return ParseDirectiveIf(IDLoc);
1199 return ParseDirectiveIfb(IDLoc, true);
1201 return ParseDirectiveIfb(IDLoc, false);
1203 return ParseDirectiveIfc(IDLoc, true);
1205 return ParseDirectiveIfc(IDLoc, false);
1207 return ParseDirectiveIfdef(IDLoc, true);
1210 return ParseDirectiveIfdef(IDLoc, false);
1212 return ParseDirectiveElseIf(IDLoc);
1214 return ParseDirectiveElse(IDLoc);
1216 return ParseDirectiveEndIf(IDLoc);
1219 // If we are in a ".if 0" block, ignore this statement.
1220 if (TheCondState.Ignore) {
1221 EatToEndOfStatement();
1225 // FIXME: Recurse on local labels?
1227 // See what kind of statement we have.
1228 switch (Lexer.getKind()) {
1229 case AsmToken::Colon: {
1230 CheckForValidSection();
1232 // identifier ':' -> Label.
1235 // Diagnose attempt to use '.' as a label.
1237 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1239 // Diagnose attempt to use a variable as a label.
1241 // FIXME: Diagnostics. Note the location of the definition as a label.
1242 // FIXME: This doesn't diagnose assignment to a symbol which has been
1243 // implicitly marked as external.
1245 if (LocalLabelVal == -1)
1246 Sym = getContext().GetOrCreateSymbol(IDVal);
1248 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1249 if (!Sym->isUndefined() || Sym->isVariable())
1250 return Error(IDLoc, "invalid symbol redefinition");
1253 if (!ParsingInlineAsm)
1256 // If we are generating dwarf for assembly source files then gather the
1257 // info to make a dwarf label entry for this label if needed.
1258 if (getContext().getGenDwarfForAssembly())
1259 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1262 // Consume any end of statement token, if present, to avoid spurious
1263 // AddBlankLine calls().
1264 if (Lexer.is(AsmToken::EndOfStatement)) {
1266 if (Lexer.is(AsmToken::Eof))
1273 case AsmToken::Equal:
1274 // identifier '=' ... -> assignment statement
1277 return ParseAssignment(IDVal, true);
1279 default: // Normal instruction or directive.
1283 // If macros are enabled, check to see if this is a macro instantiation.
1284 if (MacrosEnabled())
1285 if (const Macro *M = MacroMap.lookup(IDVal))
1286 return HandleMacroEntry(IDVal, IDLoc, M);
1288 // Otherwise, we have a normal instruction or directive.
1289 if (IDVal[0] == '.' && IDVal != ".") {
1291 // Target hook for parsing target specific directives.
1292 if (!getTargetParser().ParseDirective(ID))
1300 return ParseDirectiveSet(IDVal, true);
1302 return ParseDirectiveSet(IDVal, false);
1304 return ParseDirectiveAscii(IDVal, false);
1307 return ParseDirectiveAscii(IDVal, true);
1309 return ParseDirectiveValue(1);
1313 return ParseDirectiveValue(2);
1317 return ParseDirectiveValue(4);
1320 return ParseDirectiveValue(8);
1323 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1325 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1327 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1328 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1331 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1332 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1335 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1337 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1339 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1341 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1343 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1345 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1347 return ParseDirectiveOrg();
1349 return ParseDirectiveFill();
1351 return ParseDirectiveZero();
1353 EatToEndOfStatement(); // .extern is the default, ignore it.
1357 return ParseDirectiveSymbolAttribute(MCSA_Global);
1358 case DK_INDIRECT_SYMBOL:
1359 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1360 case DK_LAZY_REFERENCE:
1361 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1362 case DK_NO_DEAD_STRIP:
1363 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1364 case DK_SYMBOL_RESOLVER:
1365 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1366 case DK_PRIVATE_EXTERN:
1367 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1369 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1370 case DK_WEAK_DEFINITION:
1371 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1372 case DK_WEAK_REFERENCE:
1373 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1374 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1375 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1378 return ParseDirectiveComm(/*IsLocal=*/false);
1380 return ParseDirectiveComm(/*IsLocal=*/true);
1382 return ParseDirectiveAbort();
1384 return ParseDirectiveInclude();
1386 return ParseDirectiveIncbin();
1389 return TokError(Twine(IDVal) + " not supported yet");
1391 return ParseDirectiveRept(IDLoc);
1393 return ParseDirectiveIrp(IDLoc);
1395 return ParseDirectiveIrpc(IDLoc);
1397 return ParseDirectiveEndr(IDLoc);
1398 case DK_BUNDLE_ALIGN_MODE:
1399 return ParseDirectiveBundleAlignMode();
1400 case DK_BUNDLE_LOCK:
1401 return ParseDirectiveBundleLock();
1402 case DK_BUNDLE_UNLOCK:
1403 return ParseDirectiveBundleUnlock();
1406 // Look up the handler in the extension handler table.
1407 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1408 DirectiveMap.lookup(IDVal);
1410 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1412 return Error(IDLoc, "unknown directive");
1416 if (ParsingInlineAsm && IDVal == "_emit")
1417 return ParseDirectiveEmit(IDLoc, Info);
1419 CheckForValidSection();
1421 // Canonicalize the opcode to lower case.
1422 SmallString<128> OpcodeStr;
1423 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1424 OpcodeStr.push_back(tolower(IDVal[i]));
1426 ParseInstructionInfo IInfo(Info.AsmRewrites);
1427 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1428 IDLoc,Info.ParsedOperands);
1429 Info.ParseError = HadError;
1431 // Dump the parsed representation, if requested.
1432 if (getShowParsedOperands()) {
1433 SmallString<256> Str;
1434 raw_svector_ostream OS(Str);
1435 OS << "parsed instruction: [";
1436 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1439 Info.ParsedOperands[i]->print(OS);
1443 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1446 // If we are generating dwarf for assembly source files and the current
1447 // section is the initial text section then generate a .loc directive for
1449 if (!HadError && getContext().getGenDwarfForAssembly() &&
1450 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
1452 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1454 // If we previously parsed a cpp hash file line comment then make sure the
1455 // current Dwarf File is for the CppHashFilename if not then emit the
1456 // Dwarf File table for it and adjust the line number for the .loc.
1457 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1458 getContext().getMCDwarfFiles();
1459 if (CppHashFilename.size() != 0) {
1460 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1462 getStreamer().EmitDwarfFileDirective(
1463 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1465 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
1466 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1469 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1470 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1471 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1475 // If parsing succeeded, match the instruction.
1478 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1479 Info.ParsedOperands,
1484 // Don't skip the rest of the line, the instruction parser is responsible for
1489 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1490 /// since they may not be able to be tokenized to get to the end of line token.
1491 void AsmParser::EatToEndOfLine() {
1492 if (!Lexer.is(AsmToken::EndOfStatement))
1493 Lexer.LexUntilEndOfLine();
1498 /// ParseCppHashLineFilenameComment as this:
1499 /// ::= # number "filename"
1500 /// or just as a full line comment if it doesn't have a number and a string.
1501 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1502 Lex(); // Eat the hash token.
1504 if (getLexer().isNot(AsmToken::Integer)) {
1505 // Consume the line since in cases it is not a well-formed line directive,
1506 // as if were simply a full line comment.
1511 int64_t LineNumber = getTok().getIntVal();
1514 if (getLexer().isNot(AsmToken::String)) {
1519 StringRef Filename = getTok().getString();
1520 // Get rid of the enclosing quotes.
1521 Filename = Filename.substr(1, Filename.size()-2);
1523 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1525 CppHashFilename = Filename;
1526 CppHashLineNumber = LineNumber;
1527 CppHashBuf = CurBuffer;
1529 // Ignore any trailing characters, they're just comment.
1534 /// DiagHandler - will use the last parsed cpp hash line filename comment
1535 /// for the Filename and LineNo if any in the diagnostic.
1536 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1537 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1538 raw_ostream &OS = errs();
1540 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1541 const SMLoc &DiagLoc = Diag.getLoc();
1542 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1543 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1545 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1546 // before printing the message.
1547 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1548 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1549 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1550 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1553 // If we have not parsed a cpp hash line filename comment or the source
1554 // manager changed or buffer changed (like in a nested include) then just
1555 // print the normal diagnostic using its Filename and LineNo.
1556 if (!Parser->CppHashLineNumber ||
1557 &DiagSrcMgr != &Parser->SrcMgr ||
1558 DiagBuf != CppHashBuf) {
1559 if (Parser->SavedDiagHandler)
1560 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1566 // Use the CppHashFilename and calculate a line number based on the
1567 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1569 const std::string Filename = Parser->CppHashFilename;
1571 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1572 int CppHashLocLineNo =
1573 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1574 int LineNo = Parser->CppHashLineNumber - 1 +
1575 (DiagLocLineNo - CppHashLocLineNo);
1577 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1578 Filename, LineNo, Diag.getColumnNo(),
1579 Diag.getKind(), Diag.getMessage(),
1580 Diag.getLineContents(), Diag.getRanges());
1582 if (Parser->SavedDiagHandler)
1583 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1585 NewDiag.print(0, OS);
1588 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1589 // difference being that that function accepts '@' as part of identifiers and
1590 // we can't do that. AsmLexer.cpp should probably be changed to handle
1591 // '@' as a special case when needed.
1592 static bool isIdentifierChar(char c) {
1593 return isalnum(c) || c == '_' || c == '$' || c == '.';
1596 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1597 const MacroParameters &Parameters,
1598 const MacroArguments &A,
1600 unsigned NParameters = Parameters.size();
1601 if (NParameters != 0 && NParameters != A.size())
1602 return Error(L, "Wrong number of arguments");
1604 // A macro without parameters is handled differently on Darwin:
1605 // gas accepts no arguments and does no substitutions
1606 while (!Body.empty()) {
1607 // Scan for the next substitution.
1608 std::size_t End = Body.size(), Pos = 0;
1609 for (; Pos != End; ++Pos) {
1610 // Check for a substitution or escape.
1612 // This macro has no parameters, look for $0, $1, etc.
1613 if (Body[Pos] != '$' || Pos + 1 == End)
1616 char Next = Body[Pos + 1];
1617 if (Next == '$' || Next == 'n' || isdigit(Next))
1620 // This macro has parameters, look for \foo, \bar, etc.
1621 if (Body[Pos] == '\\' && Pos + 1 != End)
1627 OS << Body.slice(0, Pos);
1629 // Check if we reached the end.
1634 switch (Body[Pos+1]) {
1640 // $n => number of arguments
1645 // $[0-9] => argument
1647 // Missing arguments are ignored.
1648 unsigned Index = Body[Pos+1] - '0';
1649 if (Index >= A.size())
1652 // Otherwise substitute with the token values, with spaces eliminated.
1653 for (MacroArgument::const_iterator it = A[Index].begin(),
1654 ie = A[Index].end(); it != ie; ++it)
1655 OS << it->getString();
1661 unsigned I = Pos + 1;
1662 while (isIdentifierChar(Body[I]) && I + 1 != End)
1665 const char *Begin = Body.data() + Pos +1;
1666 StringRef Argument(Begin, I - (Pos +1));
1668 for (; Index < NParameters; ++Index)
1669 if (Parameters[Index].first == Argument)
1672 if (Index == NParameters) {
1673 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1676 OS << '\\' << Argument;
1680 for (MacroArgument::const_iterator it = A[Index].begin(),
1681 ie = A[Index].end(); it != ie; ++it)
1682 if (it->getKind() == AsmToken::String)
1683 OS << it->getStringContents();
1685 OS << it->getString();
1687 Pos += 1 + Argument.size();
1690 // Update the scan point.
1691 Body = Body.substr(Pos);
1697 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL,
1700 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1705 static bool IsOperator(AsmToken::TokenKind kind)
1711 case AsmToken::Plus:
1712 case AsmToken::Minus:
1713 case AsmToken::Tilde:
1714 case AsmToken::Slash:
1715 case AsmToken::Star:
1717 case AsmToken::Equal:
1718 case AsmToken::EqualEqual:
1719 case AsmToken::Pipe:
1720 case AsmToken::PipePipe:
1721 case AsmToken::Caret:
1723 case AsmToken::AmpAmp:
1724 case AsmToken::Exclaim:
1725 case AsmToken::ExclaimEqual:
1726 case AsmToken::Percent:
1727 case AsmToken::Less:
1728 case AsmToken::LessEqual:
1729 case AsmToken::LessLess:
1730 case AsmToken::LessGreater:
1731 case AsmToken::Greater:
1732 case AsmToken::GreaterEqual:
1733 case AsmToken::GreaterGreater:
1738 /// ParseMacroArgument - Extract AsmTokens for a macro argument.
1739 /// This is used for both default macro parameter values and the
1740 /// arguments in macro invocations
1741 bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1742 AsmToken::TokenKind &ArgumentDelimiter) {
1743 unsigned ParenLevel = 0;
1744 unsigned AddTokens = 0;
1746 // gas accepts arguments separated by whitespace, except on Darwin
1748 Lexer.setSkipSpace(false);
1751 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1752 Lexer.setSkipSpace(true);
1753 return TokError("unexpected token in macro instantiation");
1756 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1757 // Spaces and commas cannot be mixed to delimit parameters
1758 if (ArgumentDelimiter == AsmToken::Eof)
1759 ArgumentDelimiter = AsmToken::Comma;
1760 else if (ArgumentDelimiter != AsmToken::Comma) {
1761 Lexer.setSkipSpace(true);
1762 return TokError("expected ' ' for macro argument separator");
1767 if (Lexer.is(AsmToken::Space)) {
1768 Lex(); // Eat spaces
1770 // Spaces can delimit parameters, but could also be part an expression.
1771 // If the token after a space is an operator, add the token and the next
1772 // one into this argument
1773 if (ArgumentDelimiter == AsmToken::Space ||
1774 ArgumentDelimiter == AsmToken::Eof) {
1775 if (IsOperator(Lexer.getKind())) {
1776 // Check to see whether the token is used as an operator,
1777 // or part of an identifier
1778 const char *NextChar = getTok().getEndLoc().getPointer();
1779 if (*NextChar == ' ')
1783 if (!AddTokens && ParenLevel == 0) {
1784 if (ArgumentDelimiter == AsmToken::Eof &&
1785 !IsOperator(Lexer.getKind()))
1786 ArgumentDelimiter = AsmToken::Space;
1792 // HandleMacroEntry relies on not advancing the lexer here
1793 // to be able to fill in the remaining default parameter values
1794 if (Lexer.is(AsmToken::EndOfStatement))
1797 // Adjust the current parentheses level.
1798 if (Lexer.is(AsmToken::LParen))
1800 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1803 // Append the token to the current argument list.
1804 MA.push_back(getTok());
1810 Lexer.setSkipSpace(true);
1811 if (ParenLevel != 0)
1812 return TokError("unbalanced parentheses in macro argument");
1816 // Parse the macro instantiation arguments.
1817 bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
1818 const unsigned NParameters = M ? M->Parameters.size() : 0;
1819 // Argument delimiter is initially unknown. It will be set by
1820 // ParseMacroArgument()
1821 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1823 // Parse two kinds of macro invocations:
1824 // - macros defined without any parameters accept an arbitrary number of them
1825 // - macros defined with parameters accept at most that many of them
1826 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1830 if (ParseMacroArgument(MA, ArgumentDelimiter))
1833 if (!MA.empty() || !NParameters)
1835 else if (NParameters) {
1836 if (!M->Parameters[Parameter].second.empty())
1837 A.push_back(M->Parameters[Parameter].second);
1840 // At the end of the statement, fill in remaining arguments that have
1841 // default values. If there aren't any, then the next argument is
1842 // required but missing
1843 if (Lexer.is(AsmToken::EndOfStatement)) {
1844 if (NParameters && Parameter < NParameters - 1) {
1845 if (M->Parameters[Parameter + 1].second.empty())
1846 return TokError("macro argument '" +
1847 Twine(M->Parameters[Parameter + 1].first) +
1855 if (Lexer.is(AsmToken::Comma))
1858 return TokError("Too many arguments");
1861 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1863 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1864 // this, although we should protect against infinite loops.
1865 if (ActiveMacros.size() == 20)
1866 return TokError("macros cannot be nested more than 20 levels deep");
1869 if (ParseMacroArguments(M, A))
1872 // Remove any trailing empty arguments. Do this after-the-fact as we have
1873 // to keep empty arguments in the middle of the list or positionality
1874 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1875 while (!A.empty() && A.back().empty())
1878 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1879 // to hold the macro body with substitutions.
1880 SmallString<256> Buf;
1881 StringRef Body = M->Body;
1882 raw_svector_ostream OS(Buf);
1884 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1887 // We include the .endmacro in the buffer as our queue to exit the macro
1889 OS << ".endmacro\n";
1891 MemoryBuffer *Instantiation =
1892 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1894 // Create the macro instantiation object and add to the current macro
1895 // instantiation stack.
1896 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1900 ActiveMacros.push_back(MI);
1902 // Jump to the macro instantiation and prime the lexer.
1903 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1904 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1910 void AsmParser::HandleMacroExit() {
1911 // Jump to the EndOfStatement we should return to, and consume it.
1912 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
1915 // Pop the instantiation entry.
1916 delete ActiveMacros.back();
1917 ActiveMacros.pop_back();
1920 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1921 switch (Value->getKind()) {
1922 case MCExpr::Binary: {
1923 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1924 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1927 case MCExpr::Target:
1928 case MCExpr::Constant:
1930 case MCExpr::SymbolRef: {
1931 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1933 return IsUsedIn(Sym, S.getVariableValue());
1937 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1940 llvm_unreachable("Unknown expr kind!");
1943 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1945 // FIXME: Use better location, we should use proper tokens.
1946 SMLoc EqualLoc = Lexer.getLoc();
1948 const MCExpr *Value;
1949 if (ParseExpression(Value))
1952 // Note: we don't count b as used in "a = b". This is to allow
1956 if (Lexer.isNot(AsmToken::EndOfStatement))
1957 return TokError("unexpected token in assignment");
1959 // Error on assignment to '.'.
1961 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1962 "(use '.space' or '.org').)"));
1965 // Eat the end of statement marker.
1968 // Validate that the LHS is allowed to be a variable (either it has not been
1969 // used as a symbol, or it is an absolute symbol).
1970 MCSymbol *Sym = getContext().LookupSymbol(Name);
1972 // Diagnose assignment to a label.
1974 // FIXME: Diagnostics. Note the location of the definition as a label.
1975 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1976 if (IsUsedIn(Sym, Value))
1977 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1978 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1979 ; // Allow redefinitions of undefined symbols only used in directives.
1980 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1981 ; // Allow redefinitions of variables that haven't yet been used.
1982 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1983 return Error(EqualLoc, "redefinition of '" + Name + "'");
1984 else if (!Sym->isVariable())
1985 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1986 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1987 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1990 // Don't count these checks as uses.
1991 Sym->setUsed(false);
1993 Sym = getContext().GetOrCreateSymbol(Name);
1995 // FIXME: Handle '.'.
1997 // Do the assignment.
1998 Out.EmitAssignment(Sym, Value);
2000 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2006 /// ParseIdentifier:
2009 bool AsmParser::ParseIdentifier(StringRef &Res) {
2010 // The assembler has relaxed rules for accepting identifiers, in particular we
2011 // allow things like '.globl $foo', which would normally be separate
2012 // tokens. At this level, we have already lexed so we cannot (currently)
2013 // handle this as a context dependent token, instead we detect adjacent tokens
2014 // and return the combined identifier.
2015 if (Lexer.is(AsmToken::Dollar)) {
2016 SMLoc DollarLoc = getLexer().getLoc();
2018 // Consume the dollar sign, and check for a following identifier.
2020 if (Lexer.isNot(AsmToken::Identifier))
2023 // We have a '$' followed by an identifier, make sure they are adjacent.
2024 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2027 // Construct the joined identifier and consume the token.
2028 Res = StringRef(DollarLoc.getPointer(),
2029 getTok().getIdentifier().size() + 1);
2034 if (Lexer.isNot(AsmToken::Identifier) &&
2035 Lexer.isNot(AsmToken::String))
2038 Res = getTok().getIdentifier();
2040 Lex(); // Consume the identifier token.
2045 /// ParseDirectiveSet:
2046 /// ::= .equ identifier ',' expression
2047 /// ::= .equiv identifier ',' expression
2048 /// ::= .set identifier ',' expression
2049 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
2052 if (ParseIdentifier(Name))
2053 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2055 if (getLexer().isNot(AsmToken::Comma))
2056 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2059 return ParseAssignment(Name, allow_redef, true);
2062 bool AsmParser::ParseEscapedString(std::string &Data) {
2063 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2066 StringRef Str = getTok().getStringContents();
2067 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2068 if (Str[i] != '\\') {
2073 // Recognize escaped characters. Note that this escape semantics currently
2074 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2077 return TokError("unexpected backslash at end of string");
2079 // Recognize octal sequences.
2080 if ((unsigned) (Str[i] - '0') <= 7) {
2081 // Consume up to three octal characters.
2082 unsigned Value = Str[i] - '0';
2084 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2086 Value = Value * 8 + (Str[i] - '0');
2088 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2090 Value = Value * 8 + (Str[i] - '0');
2095 return TokError("invalid octal escape sequence (out of range)");
2097 Data += (unsigned char) Value;
2101 // Otherwise recognize individual escapes.
2104 // Just reject invalid escape sequences for now.
2105 return TokError("invalid escape sequence (unrecognized character)");
2107 case 'b': Data += '\b'; break;
2108 case 'f': Data += '\f'; break;
2109 case 'n': Data += '\n'; break;
2110 case 'r': Data += '\r'; break;
2111 case 't': Data += '\t'; break;
2112 case '"': Data += '"'; break;
2113 case '\\': Data += '\\'; break;
2120 /// ParseDirectiveAscii:
2121 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2122 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2123 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2124 CheckForValidSection();
2127 if (getLexer().isNot(AsmToken::String))
2128 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2131 if (ParseEscapedString(Data))
2134 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2136 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2140 if (getLexer().is(AsmToken::EndOfStatement))
2143 if (getLexer().isNot(AsmToken::Comma))
2144 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2153 /// ParseDirectiveValue
2154 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2155 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2156 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2157 CheckForValidSection();
2160 const MCExpr *Value;
2161 SMLoc ExprLoc = getLexer().getLoc();
2162 if (ParseExpression(Value))
2165 // Special case constant expressions to match code generator.
2166 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2167 assert(Size <= 8 && "Invalid size");
2168 uint64_t IntValue = MCE->getValue();
2169 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2170 return Error(ExprLoc, "literal value out of range for directive");
2171 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2173 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2175 if (getLexer().is(AsmToken::EndOfStatement))
2178 // FIXME: Improve diagnostic.
2179 if (getLexer().isNot(AsmToken::Comma))
2180 return TokError("unexpected token in directive");
2189 /// ParseDirectiveRealValue
2190 /// ::= (.single | .double) [ expression (, expression)* ]
2191 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2192 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2193 CheckForValidSection();
2196 // We don't truly support arithmetic on floating point expressions, so we
2197 // have to manually parse unary prefixes.
2199 if (getLexer().is(AsmToken::Minus)) {
2202 } else if (getLexer().is(AsmToken::Plus))
2205 if (getLexer().isNot(AsmToken::Integer) &&
2206 getLexer().isNot(AsmToken::Real) &&
2207 getLexer().isNot(AsmToken::Identifier))
2208 return TokError("unexpected token in directive");
2210 // Convert to an APFloat.
2211 APFloat Value(Semantics);
2212 StringRef IDVal = getTok().getString();
2213 if (getLexer().is(AsmToken::Identifier)) {
2214 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2215 Value = APFloat::getInf(Semantics);
2216 else if (!IDVal.compare_lower("nan"))
2217 Value = APFloat::getNaN(Semantics, false, ~0);
2219 return TokError("invalid floating point literal");
2220 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2221 APFloat::opInvalidOp)
2222 return TokError("invalid floating point literal");
2226 // Consume the numeric token.
2229 // Emit the value as an integer.
2230 APInt AsInt = Value.bitcastToAPInt();
2231 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2232 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2234 if (getLexer().is(AsmToken::EndOfStatement))
2237 if (getLexer().isNot(AsmToken::Comma))
2238 return TokError("unexpected token in directive");
2247 /// ParseDirectiveZero
2248 /// ::= .zero expression
2249 bool AsmParser::ParseDirectiveZero() {
2250 CheckForValidSection();
2253 if (ParseAbsoluteExpression(NumBytes))
2257 if (getLexer().is(AsmToken::Comma)) {
2259 if (ParseAbsoluteExpression(Val))
2263 if (getLexer().isNot(AsmToken::EndOfStatement))
2264 return TokError("unexpected token in '.zero' directive");
2268 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2273 /// ParseDirectiveFill
2274 /// ::= .fill expression , expression , expression
2275 bool AsmParser::ParseDirectiveFill() {
2276 CheckForValidSection();
2279 if (ParseAbsoluteExpression(NumValues))
2282 if (getLexer().isNot(AsmToken::Comma))
2283 return TokError("unexpected token in '.fill' directive");
2287 if (ParseAbsoluteExpression(FillSize))
2290 if (getLexer().isNot(AsmToken::Comma))
2291 return TokError("unexpected token in '.fill' directive");
2295 if (ParseAbsoluteExpression(FillExpr))
2298 if (getLexer().isNot(AsmToken::EndOfStatement))
2299 return TokError("unexpected token in '.fill' directive");
2303 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2304 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2306 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2307 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2312 /// ParseDirectiveOrg
2313 /// ::= .org expression [ , expression ]
2314 bool AsmParser::ParseDirectiveOrg() {
2315 CheckForValidSection();
2317 const MCExpr *Offset;
2318 SMLoc Loc = getTok().getLoc();
2319 if (ParseExpression(Offset))
2322 // Parse optional fill expression.
2323 int64_t FillExpr = 0;
2324 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2325 if (getLexer().isNot(AsmToken::Comma))
2326 return TokError("unexpected token in '.org' directive");
2329 if (ParseAbsoluteExpression(FillExpr))
2332 if (getLexer().isNot(AsmToken::EndOfStatement))
2333 return TokError("unexpected token in '.org' directive");
2338 // Only limited forms of relocatable expressions are accepted here, it
2339 // has to be relative to the current section. The streamer will return
2340 // 'true' if the expression wasn't evaluatable.
2341 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2342 return Error(Loc, "expected assembly-time absolute expression");
2347 /// ParseDirectiveAlign
2348 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2349 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2350 CheckForValidSection();
2352 SMLoc AlignmentLoc = getLexer().getLoc();
2354 if (ParseAbsoluteExpression(Alignment))
2358 bool HasFillExpr = false;
2359 int64_t FillExpr = 0;
2360 int64_t MaxBytesToFill = 0;
2361 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2362 if (getLexer().isNot(AsmToken::Comma))
2363 return TokError("unexpected token in directive");
2366 // The fill expression can be omitted while specifying a maximum number of
2367 // alignment bytes, e.g:
2369 if (getLexer().isNot(AsmToken::Comma)) {
2371 if (ParseAbsoluteExpression(FillExpr))
2375 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2376 if (getLexer().isNot(AsmToken::Comma))
2377 return TokError("unexpected token in directive");
2380 MaxBytesLoc = getLexer().getLoc();
2381 if (ParseAbsoluteExpression(MaxBytesToFill))
2384 if (getLexer().isNot(AsmToken::EndOfStatement))
2385 return TokError("unexpected token in directive");
2394 // Compute alignment in bytes.
2396 // FIXME: Diagnose overflow.
2397 if (Alignment >= 32) {
2398 Error(AlignmentLoc, "invalid alignment value");
2402 Alignment = 1ULL << Alignment;
2405 // Diagnose non-sensical max bytes to align.
2406 if (MaxBytesLoc.isValid()) {
2407 if (MaxBytesToFill < 1) {
2408 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2409 "many bytes, ignoring maximum bytes expression");
2413 if (MaxBytesToFill >= Alignment) {
2414 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2420 // Check whether we should use optimal code alignment for this .align
2422 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2423 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2424 ValueSize == 1 && UseCodeAlign) {
2425 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2427 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2428 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2436 /// ParseDirectiveBundleAlignMode
2437 /// ::= {.bundle_align_mode} expression
2438 bool AsmParser::ParseDirectiveBundleAlignMode() {
2439 CheckForValidSection();
2441 // Expect a single argument: an expression that evaluates to a constant
2442 // in the inclusive range 0-30.
2443 SMLoc ExprLoc = getLexer().getLoc();
2444 int64_t AlignSizePow2;
2445 if (ParseAbsoluteExpression(AlignSizePow2))
2447 else if (getLexer().isNot(AsmToken::EndOfStatement))
2448 return TokError("unexpected token after expression in"
2449 " '.bundle_align_mode' directive");
2450 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
2451 return Error(ExprLoc,
2452 "invalid bundle alignment size (expected between 0 and 30)");
2456 // Because of AlignSizePow2's verified range we can safely truncate it to
2458 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
2462 /// ParseDirectiveBundleLock
2463 /// ::= {.bundle_lock} [align_to_end]
2464 bool AsmParser::ParseDirectiveBundleLock() {
2465 CheckForValidSection();
2466 bool AlignToEnd = false;
2468 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2470 SMLoc Loc = getTok().getLoc();
2471 const char *kInvalidOptionError =
2472 "invalid option for '.bundle_lock' directive";
2474 if (ParseIdentifier(Option))
2475 return Error(Loc, kInvalidOptionError);
2477 if (Option != "align_to_end")
2478 return Error(Loc, kInvalidOptionError);
2479 else if (getLexer().isNot(AsmToken::EndOfStatement))
2481 "unexpected token after '.bundle_lock' directive option");
2487 getStreamer().EmitBundleLock(AlignToEnd);
2491 /// ParseDirectiveBundleLock
2492 /// ::= {.bundle_lock}
2493 bool AsmParser::ParseDirectiveBundleUnlock() {
2494 CheckForValidSection();
2496 if (getLexer().isNot(AsmToken::EndOfStatement))
2497 return TokError("unexpected token in '.bundle_unlock' directive");
2500 getStreamer().EmitBundleUnlock();
2504 /// ParseDirectiveSymbolAttribute
2505 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2506 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2507 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2510 SMLoc Loc = getTok().getLoc();
2512 if (ParseIdentifier(Name))
2513 return Error(Loc, "expected identifier in directive");
2515 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2517 // Assembler local symbols don't make any sense here. Complain loudly.
2518 if (Sym->isTemporary())
2519 return Error(Loc, "non-local symbol required in directive");
2521 getStreamer().EmitSymbolAttribute(Sym, Attr);
2523 if (getLexer().is(AsmToken::EndOfStatement))
2526 if (getLexer().isNot(AsmToken::Comma))
2527 return TokError("unexpected token in directive");
2536 /// ParseDirectiveComm
2537 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2538 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2539 CheckForValidSection();
2541 SMLoc IDLoc = getLexer().getLoc();
2543 if (ParseIdentifier(Name))
2544 return TokError("expected identifier in directive");
2546 // Handle the identifier as the key symbol.
2547 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2549 if (getLexer().isNot(AsmToken::Comma))
2550 return TokError("unexpected token in directive");
2554 SMLoc SizeLoc = getLexer().getLoc();
2555 if (ParseAbsoluteExpression(Size))
2558 int64_t Pow2Alignment = 0;
2559 SMLoc Pow2AlignmentLoc;
2560 if (getLexer().is(AsmToken::Comma)) {
2562 Pow2AlignmentLoc = getLexer().getLoc();
2563 if (ParseAbsoluteExpression(Pow2Alignment))
2566 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2567 if (IsLocal && LCOMM == LCOMM::NoAlignment)
2568 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2570 // If this target takes alignments in bytes (not log) validate and convert.
2571 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2572 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
2573 if (!isPowerOf2_64(Pow2Alignment))
2574 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2575 Pow2Alignment = Log2_64(Pow2Alignment);
2579 if (getLexer().isNot(AsmToken::EndOfStatement))
2580 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2584 // NOTE: a size of zero for a .comm should create a undefined symbol
2585 // but a size of .lcomm creates a bss symbol of size zero.
2587 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2588 "be less than zero");
2590 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2591 // may internally end up wanting an alignment in bytes.
2592 // FIXME: Diagnose overflow.
2593 if (Pow2Alignment < 0)
2594 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2595 "alignment, can't be less than zero");
2597 if (!Sym->isUndefined())
2598 return Error(IDLoc, "invalid symbol redefinition");
2600 // Create the Symbol as a common or local common with Size and Pow2Alignment
2602 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2606 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2610 /// ParseDirectiveAbort
2611 /// ::= .abort [... message ...]
2612 bool AsmParser::ParseDirectiveAbort() {
2613 // FIXME: Use loc from directive.
2614 SMLoc Loc = getLexer().getLoc();
2616 StringRef Str = ParseStringToEndOfStatement();
2617 if (getLexer().isNot(AsmToken::EndOfStatement))
2618 return TokError("unexpected token in '.abort' directive");
2623 Error(Loc, ".abort detected. Assembly stopping.");
2625 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2626 // FIXME: Actually abort assembly here.
2631 /// ParseDirectiveInclude
2632 /// ::= .include "filename"
2633 bool AsmParser::ParseDirectiveInclude() {
2634 if (getLexer().isNot(AsmToken::String))
2635 return TokError("expected string in '.include' directive");
2637 std::string Filename = getTok().getString();
2638 SMLoc IncludeLoc = getLexer().getLoc();
2641 if (getLexer().isNot(AsmToken::EndOfStatement))
2642 return TokError("unexpected token in '.include' directive");
2644 // Strip the quotes.
2645 Filename = Filename.substr(1, Filename.size()-2);
2647 // Attempt to switch the lexer to the included file before consuming the end
2648 // of statement to avoid losing it when we switch.
2649 if (EnterIncludeFile(Filename)) {
2650 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2657 /// ParseDirectiveIncbin
2658 /// ::= .incbin "filename"
2659 bool AsmParser::ParseDirectiveIncbin() {
2660 if (getLexer().isNot(AsmToken::String))
2661 return TokError("expected string in '.incbin' directive");
2663 std::string Filename = getTok().getString();
2664 SMLoc IncbinLoc = getLexer().getLoc();
2667 if (getLexer().isNot(AsmToken::EndOfStatement))
2668 return TokError("unexpected token in '.incbin' directive");
2670 // Strip the quotes.
2671 Filename = Filename.substr(1, Filename.size()-2);
2673 // Attempt to process the included file.
2674 if (ProcessIncbinFile(Filename)) {
2675 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2682 /// ParseDirectiveIf
2683 /// ::= .if expression
2684 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2685 TheCondStack.push_back(TheCondState);
2686 TheCondState.TheCond = AsmCond::IfCond;
2687 if (TheCondState.Ignore) {
2688 EatToEndOfStatement();
2691 if (ParseAbsoluteExpression(ExprValue))
2694 if (getLexer().isNot(AsmToken::EndOfStatement))
2695 return TokError("unexpected token in '.if' directive");
2699 TheCondState.CondMet = ExprValue;
2700 TheCondState.Ignore = !TheCondState.CondMet;
2706 /// ParseDirectiveIfb
2708 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2709 TheCondStack.push_back(TheCondState);
2710 TheCondState.TheCond = AsmCond::IfCond;
2712 if (TheCondState.Ignore) {
2713 EatToEndOfStatement();
2715 StringRef Str = ParseStringToEndOfStatement();
2717 if (getLexer().isNot(AsmToken::EndOfStatement))
2718 return TokError("unexpected token in '.ifb' directive");
2722 TheCondState.CondMet = ExpectBlank == Str.empty();
2723 TheCondState.Ignore = !TheCondState.CondMet;
2729 /// ParseDirectiveIfc
2730 /// ::= .ifc string1, string2
2731 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2732 TheCondStack.push_back(TheCondState);
2733 TheCondState.TheCond = AsmCond::IfCond;
2735 if (TheCondState.Ignore) {
2736 EatToEndOfStatement();
2738 StringRef Str1 = ParseStringToComma();
2740 if (getLexer().isNot(AsmToken::Comma))
2741 return TokError("unexpected token in '.ifc' directive");
2745 StringRef Str2 = ParseStringToEndOfStatement();
2747 if (getLexer().isNot(AsmToken::EndOfStatement))
2748 return TokError("unexpected token in '.ifc' directive");
2752 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2753 TheCondState.Ignore = !TheCondState.CondMet;
2759 /// ParseDirectiveIfdef
2760 /// ::= .ifdef symbol
2761 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2763 TheCondStack.push_back(TheCondState);
2764 TheCondState.TheCond = AsmCond::IfCond;
2766 if (TheCondState.Ignore) {
2767 EatToEndOfStatement();
2769 if (ParseIdentifier(Name))
2770 return TokError("expected identifier after '.ifdef'");
2774 MCSymbol *Sym = getContext().LookupSymbol(Name);
2777 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2779 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2780 TheCondState.Ignore = !TheCondState.CondMet;
2786 /// ParseDirectiveElseIf
2787 /// ::= .elseif expression
2788 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2789 if (TheCondState.TheCond != AsmCond::IfCond &&
2790 TheCondState.TheCond != AsmCond::ElseIfCond)
2791 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2793 TheCondState.TheCond = AsmCond::ElseIfCond;
2795 bool LastIgnoreState = false;
2796 if (!TheCondStack.empty())
2797 LastIgnoreState = TheCondStack.back().Ignore;
2798 if (LastIgnoreState || TheCondState.CondMet) {
2799 TheCondState.Ignore = true;
2800 EatToEndOfStatement();
2804 if (ParseAbsoluteExpression(ExprValue))
2807 if (getLexer().isNot(AsmToken::EndOfStatement))
2808 return TokError("unexpected token in '.elseif' directive");
2811 TheCondState.CondMet = ExprValue;
2812 TheCondState.Ignore = !TheCondState.CondMet;
2818 /// ParseDirectiveElse
2820 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2821 if (getLexer().isNot(AsmToken::EndOfStatement))
2822 return TokError("unexpected token in '.else' directive");
2826 if (TheCondState.TheCond != AsmCond::IfCond &&
2827 TheCondState.TheCond != AsmCond::ElseIfCond)
2828 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2830 TheCondState.TheCond = AsmCond::ElseCond;
2831 bool LastIgnoreState = false;
2832 if (!TheCondStack.empty())
2833 LastIgnoreState = TheCondStack.back().Ignore;
2834 if (LastIgnoreState || TheCondState.CondMet)
2835 TheCondState.Ignore = true;
2837 TheCondState.Ignore = false;
2842 /// ParseDirectiveEndIf
2844 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2845 if (getLexer().isNot(AsmToken::EndOfStatement))
2846 return TokError("unexpected token in '.endif' directive");
2850 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2851 TheCondStack.empty())
2852 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2854 if (!TheCondStack.empty()) {
2855 TheCondState = TheCondStack.back();
2856 TheCondStack.pop_back();
2862 void AsmParser::initializeDirectiveKindMapping() {
2863 DirectiveKindMapping[".set"] = DK_SET;
2864 DirectiveKindMapping[".equ"] = DK_EQU;
2865 DirectiveKindMapping[".equiv"] = DK_EQUIV;
2866 DirectiveKindMapping[".ascii"] = DK_ASCII;
2867 DirectiveKindMapping[".asciz"] = DK_ASCIZ;
2868 DirectiveKindMapping[".string"] = DK_STRING;
2869 DirectiveKindMapping[".byte"] = DK_BYTE;
2870 DirectiveKindMapping[".short"] = DK_SHORT;
2871 DirectiveKindMapping[".value"] = DK_VALUE;
2872 DirectiveKindMapping[".2byte"] = DK_2BYTE;
2873 DirectiveKindMapping[".long"] = DK_LONG;
2874 DirectiveKindMapping[".int"] = DK_INT;
2875 DirectiveKindMapping[".4byte"] = DK_4BYTE;
2876 DirectiveKindMapping[".quad"] = DK_QUAD;
2877 DirectiveKindMapping[".8byte"] = DK_8BYTE;
2878 DirectiveKindMapping[".single"] = DK_SINGLE;
2879 DirectiveKindMapping[".float"] = DK_FLOAT;
2880 DirectiveKindMapping[".double"] = DK_DOUBLE;
2881 DirectiveKindMapping[".align"] = DK_ALIGN;
2882 DirectiveKindMapping[".align32"] = DK_ALIGN32;
2883 DirectiveKindMapping[".balign"] = DK_BALIGN;
2884 DirectiveKindMapping[".balignw"] = DK_BALIGNW;
2885 DirectiveKindMapping[".balignl"] = DK_BALIGNL;
2886 DirectiveKindMapping[".p2align"] = DK_P2ALIGN;
2887 DirectiveKindMapping[".p2alignw"] = DK_P2ALIGNW;
2888 DirectiveKindMapping[".p2alignl"] = DK_P2ALIGNL;
2889 DirectiveKindMapping[".org"] = DK_ORG;
2890 DirectiveKindMapping[".fill"] = DK_FILL;
2891 DirectiveKindMapping[".zero"] = DK_ZERO;
2892 DirectiveKindMapping[".extern"] = DK_EXTERN;
2893 DirectiveKindMapping[".globl"] = DK_GLOBL;
2894 DirectiveKindMapping[".global"] = DK_GLOBAL;
2895 DirectiveKindMapping[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
2896 DirectiveKindMapping[".lazy_reference"] = DK_LAZY_REFERENCE;
2897 DirectiveKindMapping[".no_dead_strip"] = DK_NO_DEAD_STRIP;
2898 DirectiveKindMapping[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
2899 DirectiveKindMapping[".private_extern"] = DK_PRIVATE_EXTERN;
2900 DirectiveKindMapping[".reference"] = DK_REFERENCE;
2901 DirectiveKindMapping[".weak_definition"] = DK_WEAK_DEFINITION;
2902 DirectiveKindMapping[".weak_reference"] = DK_WEAK_REFERENCE;
2903 DirectiveKindMapping[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
2904 DirectiveKindMapping[".comm"] = DK_COMM;
2905 DirectiveKindMapping[".common"] = DK_COMMON;
2906 DirectiveKindMapping[".lcomm"] = DK_LCOMM;
2907 DirectiveKindMapping[".abort"] = DK_ABORT;
2908 DirectiveKindMapping[".include"] = DK_INCLUDE;
2909 DirectiveKindMapping[".incbin"] = DK_INCBIN;
2910 DirectiveKindMapping[".code16"] = DK_CODE16;
2911 DirectiveKindMapping[".code16gcc"] = DK_CODE16GCC;
2912 DirectiveKindMapping[".rept"] = DK_REPT;
2913 DirectiveKindMapping[".irp"] = DK_IRP;
2914 DirectiveKindMapping[".irpc"] = DK_IRPC;
2915 DirectiveKindMapping[".endr"] = DK_ENDR;
2916 DirectiveKindMapping[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
2917 DirectiveKindMapping[".bundle_lock"] = DK_BUNDLE_LOCK;
2918 DirectiveKindMapping[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
2919 DirectiveKindMapping[".if"] = DK_IF;
2920 DirectiveKindMapping[".ifb"] = DK_IFB;
2921 DirectiveKindMapping[".ifnb"] = DK_IFNB;
2922 DirectiveKindMapping[".ifc"] = DK_IFC;
2923 DirectiveKindMapping[".ifnc"] = DK_IFNC;
2924 DirectiveKindMapping[".ifdef"] = DK_IFDEF;
2925 DirectiveKindMapping[".ifndef"] = DK_IFNDEF;
2926 DirectiveKindMapping[".ifnotdef"] = DK_IFNOTDEF;
2927 DirectiveKindMapping[".elseif"] = DK_ELSEIF;
2928 DirectiveKindMapping[".else"] = DK_ELSE;
2929 DirectiveKindMapping[".endif"] = DK_ENDIF;
2932 /// ParseDirectiveFile
2933 /// ::= .file [number] filename
2934 /// ::= .file number directory filename
2935 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2936 // FIXME: I'm not sure what this is.
2937 int64_t FileNumber = -1;
2938 SMLoc FileNumberLoc = getLexer().getLoc();
2939 if (getLexer().is(AsmToken::Integer)) {
2940 FileNumber = getTok().getIntVal();
2944 return TokError("file number less than one");
2947 if (getLexer().isNot(AsmToken::String))
2948 return TokError("unexpected token in '.file' directive");
2950 // Usually the directory and filename together, otherwise just the directory.
2951 StringRef Path = getTok().getString();
2952 Path = Path.substr(1, Path.size()-2);
2955 StringRef Directory;
2957 if (getLexer().is(AsmToken::String)) {
2958 if (FileNumber == -1)
2959 return TokError("explicit path specified, but no file number");
2960 Filename = getTok().getString();
2961 Filename = Filename.substr(1, Filename.size()-2);
2968 if (getLexer().isNot(AsmToken::EndOfStatement))
2969 return TokError("unexpected token in '.file' directive");
2971 if (FileNumber == -1)
2972 getStreamer().EmitFileDirective(Filename);
2974 if (getContext().getGenDwarfForAssembly() == true)
2975 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2976 "used to generate dwarf debug info for assembly code");
2978 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2979 Error(FileNumberLoc, "file number already allocated");
2985 /// ParseDirectiveLine
2986 /// ::= .line [number]
2987 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2988 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2989 if (getLexer().isNot(AsmToken::Integer))
2990 return TokError("unexpected token in '.line' directive");
2992 int64_t LineNumber = getTok().getIntVal();
2996 // FIXME: Do something with the .line.
2999 if (getLexer().isNot(AsmToken::EndOfStatement))
3000 return TokError("unexpected token in '.line' directive");
3006 /// ParseDirectiveLoc
3007 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3008 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3009 /// The first number is a file number, must have been previously assigned with
3010 /// a .file directive, the second number is the line number and optionally the
3011 /// third number is a column position (zero if not specified). The remaining
3012 /// optional items are .loc sub-directives.
3013 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
3015 if (getLexer().isNot(AsmToken::Integer))
3016 return TokError("unexpected token in '.loc' directive");
3017 int64_t FileNumber = getTok().getIntVal();
3019 return TokError("file number less than one in '.loc' directive");
3020 if (!getContext().isValidDwarfFileNumber(FileNumber))
3021 return TokError("unassigned file number in '.loc' directive");
3024 int64_t LineNumber = 0;
3025 if (getLexer().is(AsmToken::Integer)) {
3026 LineNumber = getTok().getIntVal();
3028 return TokError("line number less than one in '.loc' directive");
3032 int64_t ColumnPos = 0;
3033 if (getLexer().is(AsmToken::Integer)) {
3034 ColumnPos = getTok().getIntVal();
3036 return TokError("column position less than zero in '.loc' directive");
3040 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3042 int64_t Discriminator = 0;
3043 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3045 if (getLexer().is(AsmToken::EndOfStatement))
3049 SMLoc Loc = getTok().getLoc();
3050 if (getParser().ParseIdentifier(Name))
3051 return TokError("unexpected token in '.loc' directive");
3053 if (Name == "basic_block")
3054 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3055 else if (Name == "prologue_end")
3056 Flags |= DWARF2_FLAG_PROLOGUE_END;
3057 else if (Name == "epilogue_begin")
3058 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3059 else if (Name == "is_stmt") {
3060 Loc = getTok().getLoc();
3061 const MCExpr *Value;
3062 if (getParser().ParseExpression(Value))
3064 // The expression must be the constant 0 or 1.
3065 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3066 int Value = MCE->getValue();
3068 Flags &= ~DWARF2_FLAG_IS_STMT;
3069 else if (Value == 1)
3070 Flags |= DWARF2_FLAG_IS_STMT;
3072 return Error(Loc, "is_stmt value not 0 or 1");
3075 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3078 else if (Name == "isa") {
3079 Loc = getTok().getLoc();
3080 const MCExpr *Value;
3081 if (getParser().ParseExpression(Value))
3083 // The expression must be a constant greater or equal to 0.
3084 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3085 int Value = MCE->getValue();
3087 return Error(Loc, "isa number less than zero");
3091 return Error(Loc, "isa number not a constant value");
3094 else if (Name == "discriminator") {
3095 if (getParser().ParseAbsoluteExpression(Discriminator))
3099 return Error(Loc, "unknown sub-directive in '.loc' directive");
3102 if (getLexer().is(AsmToken::EndOfStatement))
3107 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3108 Isa, Discriminator, StringRef());
3113 /// ParseDirectiveStabs
3114 /// ::= .stabs string, number, number, number
3115 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
3116 SMLoc DirectiveLoc) {
3117 return TokError("unsupported directive '" + Directive + "'");
3120 /// ParseDirectiveSpace
3121 /// ::= .space expression [ , expression ]
3122 bool GenericAsmParser::ParseDirectiveSpace(StringRef, SMLoc DirectiveLoc) {
3123 getParser().CheckForValidSection();
3126 if (getParser().ParseAbsoluteExpression(NumBytes))
3129 int64_t FillExpr = 0;
3130 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3131 if (getLexer().isNot(AsmToken::Comma))
3132 return TokError("unexpected token in '.space' directive");
3135 if (getParser().ParseAbsoluteExpression(FillExpr))
3138 if (getLexer().isNot(AsmToken::EndOfStatement))
3139 return TokError("unexpected token in '.space' directive");
3145 return TokError("invalid number of bytes in '.space' directive");
3147 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3148 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3153 /// ParseDirectiveCFISections
3154 /// ::= .cfi_sections section [, section]
3155 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
3156 SMLoc DirectiveLoc) {
3161 if (getParser().ParseIdentifier(Name))
3162 return TokError("Expected an identifier");
3164 if (Name == ".eh_frame")
3166 else if (Name == ".debug_frame")
3169 if (getLexer().is(AsmToken::Comma)) {
3172 if (getParser().ParseIdentifier(Name))
3173 return TokError("Expected an identifier");
3175 if (Name == ".eh_frame")
3177 else if (Name == ".debug_frame")
3181 getStreamer().EmitCFISections(EH, Debug);
3186 /// ParseDirectiveCFIStartProc
3187 /// ::= .cfi_startproc
3188 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
3189 SMLoc DirectiveLoc) {
3190 getStreamer().EmitCFIStartProc();
3194 /// ParseDirectiveCFIEndProc
3195 /// ::= .cfi_endproc
3196 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
3197 getStreamer().EmitCFIEndProc();
3201 /// ParseRegisterOrRegisterNumber - parse register name or number.
3202 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3203 SMLoc DirectiveLoc) {
3206 if (getLexer().isNot(AsmToken::Integer)) {
3207 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3210 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
3212 return getParser().ParseAbsoluteExpression(Register);
3217 /// ParseDirectiveCFIDefCfa
3218 /// ::= .cfi_def_cfa register, offset
3219 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3220 SMLoc DirectiveLoc) {
3221 int64_t Register = 0;
3222 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3225 if (getLexer().isNot(AsmToken::Comma))
3226 return TokError("unexpected token in directive");
3230 if (getParser().ParseAbsoluteExpression(Offset))
3233 getStreamer().EmitCFIDefCfa(Register, Offset);
3237 /// ParseDirectiveCFIDefCfaOffset
3238 /// ::= .cfi_def_cfa_offset offset
3239 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3240 SMLoc DirectiveLoc) {
3242 if (getParser().ParseAbsoluteExpression(Offset))
3245 getStreamer().EmitCFIDefCfaOffset(Offset);
3249 /// ParseDirectiveCFIAdjustCfaOffset
3250 /// ::= .cfi_adjust_cfa_offset adjustment
3251 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3252 SMLoc DirectiveLoc) {
3253 int64_t Adjustment = 0;
3254 if (getParser().ParseAbsoluteExpression(Adjustment))
3257 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3261 /// ParseDirectiveCFIDefCfaRegister
3262 /// ::= .cfi_def_cfa_register register
3263 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3264 SMLoc DirectiveLoc) {
3265 int64_t Register = 0;
3266 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3269 getStreamer().EmitCFIDefCfaRegister(Register);
3273 /// ParseDirectiveCFIOffset
3274 /// ::= .cfi_offset register, offset
3275 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3276 int64_t Register = 0;
3279 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3282 if (getLexer().isNot(AsmToken::Comma))
3283 return TokError("unexpected token in directive");
3286 if (getParser().ParseAbsoluteExpression(Offset))
3289 getStreamer().EmitCFIOffset(Register, Offset);
3293 /// ParseDirectiveCFIRelOffset
3294 /// ::= .cfi_rel_offset register, offset
3295 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3296 SMLoc DirectiveLoc) {
3297 int64_t Register = 0;
3299 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3302 if (getLexer().isNot(AsmToken::Comma))
3303 return TokError("unexpected token in directive");
3307 if (getParser().ParseAbsoluteExpression(Offset))
3310 getStreamer().EmitCFIRelOffset(Register, Offset);
3314 static bool isValidEncoding(int64_t Encoding) {
3315 if (Encoding & ~0xff)
3318 if (Encoding == dwarf::DW_EH_PE_omit)
3321 const unsigned Format = Encoding & 0xf;
3322 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3323 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3324 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3325 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3328 const unsigned Application = Encoding & 0x70;
3329 if (Application != dwarf::DW_EH_PE_absptr &&
3330 Application != dwarf::DW_EH_PE_pcrel)
3336 /// ParseDirectiveCFIPersonalityOrLsda
3337 /// ::= .cfi_personality encoding, [symbol_name]
3338 /// ::= .cfi_lsda encoding, [symbol_name]
3339 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
3340 SMLoc DirectiveLoc) {
3341 int64_t Encoding = 0;
3342 if (getParser().ParseAbsoluteExpression(Encoding))
3344 if (Encoding == dwarf::DW_EH_PE_omit)
3347 if (!isValidEncoding(Encoding))
3348 return TokError("unsupported encoding.");
3350 if (getLexer().isNot(AsmToken::Comma))
3351 return TokError("unexpected token in directive");
3355 if (getParser().ParseIdentifier(Name))
3356 return TokError("expected identifier in directive");
3358 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3360 if (IDVal == ".cfi_personality")
3361 getStreamer().EmitCFIPersonality(Sym, Encoding);
3363 assert(IDVal == ".cfi_lsda");
3364 getStreamer().EmitCFILsda(Sym, Encoding);
3369 /// ParseDirectiveCFIRememberState
3370 /// ::= .cfi_remember_state
3371 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3372 SMLoc DirectiveLoc) {
3373 getStreamer().EmitCFIRememberState();
3377 /// ParseDirectiveCFIRestoreState
3378 /// ::= .cfi_remember_state
3379 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3380 SMLoc DirectiveLoc) {
3381 getStreamer().EmitCFIRestoreState();
3385 /// ParseDirectiveCFISameValue
3386 /// ::= .cfi_same_value register
3387 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3388 SMLoc DirectiveLoc) {
3389 int64_t Register = 0;
3391 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3394 getStreamer().EmitCFISameValue(Register);
3399 /// ParseDirectiveCFIRestore
3400 /// ::= .cfi_restore register
3401 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
3402 SMLoc DirectiveLoc) {
3403 int64_t Register = 0;
3404 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3407 getStreamer().EmitCFIRestore(Register);
3412 /// ParseDirectiveCFIEscape
3413 /// ::= .cfi_escape expression[,...]
3414 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3415 SMLoc DirectiveLoc) {
3418 if (getParser().ParseAbsoluteExpression(CurrValue))
3421 Values.push_back((uint8_t)CurrValue);
3423 while (getLexer().is(AsmToken::Comma)) {
3426 if (getParser().ParseAbsoluteExpression(CurrValue))
3429 Values.push_back((uint8_t)CurrValue);
3432 getStreamer().EmitCFIEscape(Values);
3436 /// ParseDirectiveCFISignalFrame
3437 /// ::= .cfi_signal_frame
3438 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3439 SMLoc DirectiveLoc) {
3440 if (getLexer().isNot(AsmToken::EndOfStatement))
3441 return Error(getLexer().getLoc(),
3442 "unexpected token in '" + Directive + "' directive");
3444 getStreamer().EmitCFISignalFrame();
3449 /// ParseDirectiveCFIUndefined
3450 /// ::= .cfi_undefined register
3451 bool GenericAsmParser::ParseDirectiveCFIUndefined(StringRef Directive,
3452 SMLoc DirectiveLoc) {
3453 int64_t Register = 0;
3455 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3458 getStreamer().EmitCFIUndefined(Register);
3463 /// ParseDirectiveCFIRegister
3464 /// ::= .cfi_register register, register
3465 bool GenericAsmParser::ParseDirectiveCFIRegister(StringRef Directive,
3466 SMLoc DirectiveLoc) {
3467 int64_t Register1 = 0;
3469 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3472 if (getLexer().isNot(AsmToken::Comma))
3473 return TokError("unexpected token in directive");
3476 int64_t Register2 = 0;
3478 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3481 getStreamer().EmitCFIRegister(Register1, Register2);
3486 /// ParseDirectiveMacrosOnOff
3489 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3490 SMLoc DirectiveLoc) {
3491 if (getLexer().isNot(AsmToken::EndOfStatement))
3492 return Error(getLexer().getLoc(),
3493 "unexpected token in '" + Directive + "' directive");
3495 getParser().SetMacrosEnabled(Directive == ".macros_on");
3500 /// ParseDirectiveMacro
3501 /// ::= .macro name [parameters]
3502 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3503 SMLoc DirectiveLoc) {
3505 if (getParser().ParseIdentifier(Name))
3506 return TokError("expected identifier in '.macro' directive");
3508 MacroParameters Parameters;
3509 // Argument delimiter is initially unknown. It will be set by
3510 // ParseMacroArgument()
3511 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3512 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3514 MacroParameter Parameter;
3515 if (getParser().ParseIdentifier(Parameter.first))
3516 return TokError("expected identifier in '.macro' directive");
3518 if (getLexer().is(AsmToken::Equal)) {
3520 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3524 Parameters.push_back(Parameter);
3526 if (getLexer().is(AsmToken::Comma))
3528 else if (getLexer().is(AsmToken::EndOfStatement))
3533 // Eat the end of statement.
3536 AsmToken EndToken, StartToken = getTok();
3538 // Lex the macro definition.
3540 // Check whether we have reached the end of the file.
3541 if (getLexer().is(AsmToken::Eof))
3542 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3544 // Otherwise, check whether we have reach the .endmacro.
3545 if (getLexer().is(AsmToken::Identifier) &&
3546 (getTok().getIdentifier() == ".endm" ||
3547 getTok().getIdentifier() == ".endmacro")) {
3548 EndToken = getTok();
3550 if (getLexer().isNot(AsmToken::EndOfStatement))
3551 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3556 // Otherwise, scan til the end of the statement.
3557 getParser().EatToEndOfStatement();
3560 if (getParser().MacroMap.lookup(Name)) {
3561 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3564 const char *BodyStart = StartToken.getLoc().getPointer();
3565 const char *BodyEnd = EndToken.getLoc().getPointer();
3566 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3567 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3571 /// ParseDirectiveEndMacro
3574 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3575 SMLoc DirectiveLoc) {
3576 if (getLexer().isNot(AsmToken::EndOfStatement))
3577 return TokError("unexpected token in '" + Directive + "' directive");
3579 // If we are inside a macro instantiation, terminate the current
3581 if (!getParser().ActiveMacros.empty()) {
3582 getParser().HandleMacroExit();
3586 // Otherwise, this .endmacro is a stray entry in the file; well formed
3587 // .endmacro directives are handled during the macro definition parsing.
3588 return TokError("unexpected '" + Directive + "' in file, "
3589 "no current macro definition");
3592 /// ParseDirectivePurgeMacro
3594 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3595 SMLoc DirectiveLoc) {
3597 if (getParser().ParseIdentifier(Name))
3598 return TokError("expected identifier in '.purgem' directive");
3600 if (getLexer().isNot(AsmToken::EndOfStatement))
3601 return TokError("unexpected token in '.purgem' directive");
3603 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3604 if (I == getParser().MacroMap.end())
3605 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3607 // Undefine the macro.
3608 delete I->getValue();
3609 getParser().MacroMap.erase(I);
3613 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3614 getParser().CheckForValidSection();
3616 const MCExpr *Value;
3618 if (getParser().ParseExpression(Value))
3621 if (getLexer().isNot(AsmToken::EndOfStatement))
3622 return TokError("unexpected token in directive");
3624 if (DirName[1] == 's')
3625 getStreamer().EmitSLEB128Value(Value);
3627 getStreamer().EmitULEB128Value(Value);
3632 Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3633 AsmToken EndToken, StartToken = getTok();
3635 unsigned NestLevel = 0;
3637 // Check whether we have reached the end of the file.
3638 if (getLexer().is(AsmToken::Eof)) {
3639 Error(DirectiveLoc, "no matching '.endr' in definition");
3643 if (Lexer.is(AsmToken::Identifier) &&
3644 (getTok().getIdentifier() == ".rept")) {
3648 // Otherwise, check whether we have reached the .endr.
3649 if (Lexer.is(AsmToken::Identifier) &&
3650 getTok().getIdentifier() == ".endr") {
3651 if (NestLevel == 0) {
3652 EndToken = getTok();
3654 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3655 TokError("unexpected token in '.endr' directive");
3663 // Otherwise, scan till the end of the statement.
3664 EatToEndOfStatement();
3667 const char *BodyStart = StartToken.getLoc().getPointer();
3668 const char *BodyEnd = EndToken.getLoc().getPointer();
3669 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3671 // We Are Anonymous.
3673 MacroParameters Parameters;
3674 return new Macro(Name, Body, Parameters);
3677 void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3678 raw_svector_ostream &OS) {
3681 MemoryBuffer *Instantiation =
3682 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3684 // Create the macro instantiation object and add to the current macro
3685 // instantiation stack.
3686 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3690 ActiveMacros.push_back(MI);
3692 // Jump to the macro instantiation and prime the lexer.
3693 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3694 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3698 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3700 if (ParseAbsoluteExpression(Count))
3701 return TokError("unexpected token in '.rept' directive");
3704 return TokError("Count is negative");
3706 if (Lexer.isNot(AsmToken::EndOfStatement))
3707 return TokError("unexpected token in '.rept' directive");
3709 // Eat the end of statement.
3712 // Lex the rept definition.
3713 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3717 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3718 // to hold the macro body with substitutions.
3719 SmallString<256> Buf;
3720 MacroParameters Parameters;
3722 raw_svector_ostream OS(Buf);
3724 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3727 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3732 /// ParseDirectiveIrp
3733 /// ::= .irp symbol,values
3734 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3735 MacroParameters Parameters;
3736 MacroParameter Parameter;
3738 if (ParseIdentifier(Parameter.first))
3739 return TokError("expected identifier in '.irp' directive");
3741 Parameters.push_back(Parameter);
3743 if (Lexer.isNot(AsmToken::Comma))
3744 return TokError("expected comma in '.irp' directive");
3749 if (ParseMacroArguments(0, A))
3752 // Eat the end of statement.
3755 // Lex the irp definition.
3756 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3760 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3761 // to hold the macro body with substitutions.
3762 SmallString<256> Buf;
3763 raw_svector_ostream OS(Buf);
3765 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3766 MacroArguments Args;
3769 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3773 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3778 /// ParseDirectiveIrpc
3779 /// ::= .irpc symbol,values
3780 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3781 MacroParameters Parameters;
3782 MacroParameter Parameter;
3784 if (ParseIdentifier(Parameter.first))
3785 return TokError("expected identifier in '.irpc' directive");
3787 Parameters.push_back(Parameter);
3789 if (Lexer.isNot(AsmToken::Comma))
3790 return TokError("expected comma in '.irpc' directive");
3795 if (ParseMacroArguments(0, A))
3798 if (A.size() != 1 || A.front().size() != 1)
3799 return TokError("unexpected token in '.irpc' directive");
3801 // Eat the end of statement.
3804 // Lex the irpc definition.
3805 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3809 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3810 // to hold the macro body with substitutions.
3811 SmallString<256> Buf;
3812 raw_svector_ostream OS(Buf);
3814 StringRef Values = A.front().front().getString();
3815 std::size_t I, End = Values.size();
3816 for (I = 0; I < End; ++I) {
3818 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3820 MacroArguments Args;
3821 Args.push_back(Arg);
3823 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3827 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3832 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3833 if (ActiveMacros.empty())
3834 return TokError("unmatched '.endr' directive");
3836 // The only .repl that should get here are the ones created by
3837 // InstantiateMacroLikeBody.
3838 assert(getLexer().is(AsmToken::EndOfStatement));
3844 bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3845 const MCExpr *Value;
3846 SMLoc ExprLoc = getLexer().getLoc();
3847 if (ParseExpression(Value))
3849 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3851 return Error(ExprLoc, "unexpected expression in _emit");
3852 uint64_t IntValue = MCE->getValue();
3853 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3854 return Error(ExprLoc, "literal value out of range for directive");
3856 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3860 bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3861 unsigned &NumOutputs, unsigned &NumInputs,
3862 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
3863 SmallVectorImpl<std::string> &Constraints,
3864 SmallVectorImpl<std::string> &Clobbers,
3865 const MCInstrInfo *MII,
3866 const MCInstPrinter *IP,
3867 MCAsmParserSemaCallback &SI) {
3868 SmallVector<void *, 4> InputDecls;
3869 SmallVector<void *, 4> OutputDecls;
3870 SmallVector<bool, 4> InputDeclsAddressOf;
3871 SmallVector<bool, 4> OutputDeclsAddressOf;
3872 SmallVector<std::string, 4> InputConstraints;
3873 SmallVector<std::string, 4> OutputConstraints;
3874 std::set<std::string> ClobberRegs;
3876 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
3881 // While we have input, parse each statement.
3882 unsigned InputIdx = 0;
3883 unsigned OutputIdx = 0;
3884 while (getLexer().isNot(AsmToken::Eof)) {
3885 ParseStatementInfo Info(&AsmStrRewrites);
3886 if (ParseStatement(Info))
3889 if (Info.ParseError)
3892 if (Info.Opcode != ~0U) {
3893 const MCInstrDesc &Desc = MII->get(Info.Opcode);
3895 // Build the list of clobbers, outputs and inputs.
3896 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3897 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
3900 if (Operand->isImm()) {
3901 if (Operand->needAsmRewrite())
3902 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3903 Operand->getStartLoc()));
3907 // Register operand.
3908 if (Operand->isReg() && !Operand->needAddressOf()) {
3909 unsigned NumDefs = Desc.getNumDefs();
3911 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3913 raw_string_ostream OS(Reg);
3914 IP->printRegName(OS, Operand->getReg());
3915 ClobberRegs.insert(StringRef(OS.str()));
3920 // Expr/Input or Output.
3923 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3926 bool isOutput = (i == 1) && Desc.mayStore();
3927 if (Operand->isMem() && Operand->needSizeDirective())
3928 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
3929 Operand->getStartLoc(),
3931 Operand->getMemSize()));
3933 std::string Constraint = "=";
3935 OutputDecls.push_back(OpDecl);
3936 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
3937 Constraint += Operand->getConstraint().str();
3938 OutputConstraints.push_back(Constraint);
3939 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
3940 Operand->getStartLoc(),
3941 Operand->getNameLen()));
3943 InputDecls.push_back(OpDecl);
3944 InputDeclsAddressOf.push_back(Operand->needAddressOf());
3945 InputConstraints.push_back(Operand->getConstraint().str());
3946 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
3947 Operand->getStartLoc(),
3948 Operand->getNameLen()));
3955 // Set the number of Outputs and Inputs.
3956 NumOutputs = OutputDecls.size();
3957 NumInputs = InputDecls.size();
3959 // Set the unique clobbers.
3960 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3961 E = ClobberRegs.end(); I != E; ++I)
3962 Clobbers.push_back(*I);
3964 // Merge the various outputs and inputs. Output are expected first.
3965 if (NumOutputs || NumInputs) {
3966 unsigned NumExprs = NumOutputs + NumInputs;
3967 OpDecls.resize(NumExprs);
3968 Constraints.resize(NumExprs);
3969 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3970 // constraint for addressof. This needs to be cleaned up!
3971 for (unsigned i = 0; i < NumOutputs; ++i) {
3972 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
3973 Constraints[i] = OutputDeclsAddressOf[i] ? "=r" : OutputConstraints[i];
3975 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
3976 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
3977 Constraints[j] = InputDeclsAddressOf[i] ? "r" : InputConstraints[i];
3981 // Build the IR assembly string.
3982 std::string AsmStringIR;
3983 AsmRewriteKind PrevKind = AOK_Imm;
3984 raw_string_ostream OS(AsmStringIR);
3985 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
3986 for (SmallVectorImpl<struct AsmRewrite>::iterator
3987 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3988 const char *Loc = (*I).Loc.getPointer();
3990 AsmRewriteKind Kind = (*I).Kind;
3992 // Emit everything up to the immediate/expression. If the previous rewrite
3993 // was a size directive, then this has already been done.
3994 if (PrevKind != AOK_SizeDirective)
3995 OS << StringRef(Start, Loc - Start);
3998 // Skip the original expression.
3999 if (Kind == AOK_Skip) {
4000 Start = Loc + (*I).Len;
4004 // Rewrite expressions in $N notation.
4022 case AOK_SizeDirective:
4025 case 8: OS << "byte ptr "; break;
4026 case 16: OS << "word ptr "; break;
4027 case 32: OS << "dword ptr "; break;
4028 case 64: OS << "qword ptr "; break;
4029 case 80: OS << "xword ptr "; break;
4030 case 128: OS << "xmmword ptr "; break;
4031 case 256: OS << "ymmword ptr "; break;
4037 case AOK_DotOperator:
4042 // Skip the original expression.
4043 if (Kind != AOK_SizeDirective)
4044 Start = Loc + (*I).Len;
4047 // Emit the remainder of the asm string.
4048 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4049 if (Start != AsmEnd)
4050 OS << StringRef(Start, AsmEnd - Start);
4052 AsmString = OS.str();
4056 /// \brief Create an MCAsmParser instance.
4057 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
4058 MCContext &C, MCStreamer &Out,
4059 const MCAsmInfo &MAI) {
4060 return new AsmParser(SM, C, Out, MAI);