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<MCAsmMacroArgument> MacroArguments;
55 typedef std::pair<StringRef, MCAsmMacroArgument> MacroParameter;
56 typedef std::vector<MacroParameter> MacroParameters;
61 MacroParameters Parameters;
64 Macro(StringRef N, StringRef B, const MacroParameters &P) :
65 Name(N), Body(B), Parameters(P) {}
68 /// \brief Helper class for storing information about an active macro
70 struct MacroInstantiation {
71 /// The macro being instantiated.
72 const Macro *TheMacro;
74 /// The macro instantiation with substitutions.
75 MemoryBuffer *Instantiation;
77 /// The location of the instantiation.
78 SMLoc InstantiationLoc;
80 /// The buffer where parsing should resume upon instantiation completion.
83 /// The location where parsing should resume upon instantiation completion.
87 MacroInstantiation(const Macro *M, SMLoc IL, int EB, SMLoc EL,
92 struct ParseStatementInfo {
93 /// ParsedOperands - The parsed operands from the last parsed statement.
94 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
96 /// Opcode - The opcode from the last parsed instruction.
99 /// Error - Was there an error parsing the inline assembly?
102 SmallVectorImpl<AsmRewrite> *AsmRewrites;
104 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
105 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
106 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
108 ~ParseStatementInfo() {
109 // Free any parsed operands.
110 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
111 delete ParsedOperands[i];
112 ParsedOperands.clear();
116 /// \brief The concrete assembly parser instance.
117 class AsmParser : public MCAsmParser {
118 friend class GenericAsmParser;
120 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
121 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
126 const MCAsmInfo &MAI;
128 SourceMgr::DiagHandlerTy SavedDiagHandler;
129 void *SavedDiagContext;
130 MCAsmParserExtension *GenericParser;
131 MCAsmParserExtension *PlatformParser;
133 /// This is the current buffer index we're lexing from as managed by the
134 /// SourceMgr object.
137 AsmCond TheCondState;
138 std::vector<AsmCond> TheCondStack;
140 /// DirectiveMap - This is a table handlers for directives. Each handler is
141 /// invoked after the directive identifier is read and is responsible for
142 /// parsing and validating the rest of the directive. The handler is passed
143 /// in the directive name and the location of the directive keyword.
144 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
146 /// MacroMap - Map of currently defined macros.
147 StringMap<Macro*> MacroMap;
149 /// ActiveMacros - Stack of active macro instantiations.
150 std::vector<MacroInstantiation*> ActiveMacros;
152 /// Boolean tracking whether macro substitution is enabled.
153 unsigned MacrosEnabledFlag : 1;
155 /// Flag tracking whether any errors have been encountered.
156 unsigned HadError : 1;
158 /// The values from the last parsed cpp hash file line comment if any.
159 StringRef CppHashFilename;
160 int64_t CppHashLineNumber;
164 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
165 unsigned AssemblerDialect;
167 /// IsDarwin - is Darwin compatibility enabled?
170 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
171 bool ParsingInlineAsm;
174 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
175 const MCAsmInfo &MAI);
176 virtual ~AsmParser();
178 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
180 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
182 DirectiveHandler Handler) {
183 DirectiveMap[Directive] = std::make_pair(Object, Handler);
187 /// @name MCAsmParser Interface
190 virtual SourceMgr &getSourceManager() { return SrcMgr; }
191 virtual MCAsmLexer &getLexer() { return Lexer; }
192 virtual MCContext &getContext() { return Ctx; }
193 virtual MCStreamer &getStreamer() { return Out; }
194 virtual unsigned getAssemblerDialect() {
195 if (AssemblerDialect == ~0U)
196 return MAI.getAssemblerDialect();
198 return AssemblerDialect;
200 virtual void setAssemblerDialect(unsigned i) {
201 AssemblerDialect = i;
204 virtual bool Warning(SMLoc L, const Twine &Msg,
205 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
206 virtual bool Error(SMLoc L, const Twine &Msg,
207 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
209 virtual const AsmToken &Lex();
211 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
212 bool isParsingInlineAsm() { return ParsingInlineAsm; }
214 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
215 unsigned &NumOutputs, unsigned &NumInputs,
216 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
217 SmallVectorImpl<std::string> &Constraints,
218 SmallVectorImpl<std::string> &Clobbers,
219 const MCInstrInfo *MII,
220 const MCInstPrinter *IP,
221 MCAsmParserSemaCallback &SI);
223 bool ParseExpression(const MCExpr *&Res);
224 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
225 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
226 virtual bool ParseAbsoluteExpression(int64_t &Res);
228 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
229 /// and set \p Res to the identifier contents.
230 virtual bool ParseIdentifier(StringRef &Res);
231 virtual void EatToEndOfStatement();
233 virtual bool MacrosEnabled() {return MacrosEnabledFlag;}
234 virtual void SetMacrosEnabled(bool flag) {MacrosEnabledFlag = flag;}
239 void CheckForValidSection();
241 bool ParseStatement(ParseStatementInfo &Info);
242 void EatToEndOfLine();
243 bool ParseCppHashLineFilenameComment(const SMLoc &L);
245 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
246 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
247 const MacroParameters &Parameters,
248 const MacroArguments &A,
250 void HandleMacroExit();
252 void PrintMacroInstantiations();
253 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
254 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
255 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
257 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
259 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
260 bool EnterIncludeFile(const std::string &Filename);
261 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
262 /// This returns true on failure.
263 bool ProcessIncbinFile(const std::string &Filename);
265 /// \brief Reset the current lexer position to that given by \p Loc. The
266 /// current token is not set; clients should ensure Lex() is called
269 /// \param InBuffer If not -1, should be the known buffer id that contains the
271 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
273 bool ParseMacroArgument(MCAsmMacroArgument &MA,
274 AsmToken::TokenKind &ArgumentDelimiter);
275 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
277 /// \brief Parse up to the end of statement and a return the contents from the
278 /// current token until the end of the statement; the current token on exit
279 /// will be either the EndOfStatement or EOF.
280 virtual StringRef ParseStringToEndOfStatement();
282 /// \brief Parse until the end of a statement or a comma is encountered,
283 /// return the contents from the current token up to the end or comma.
284 StringRef ParseStringToComma();
286 bool ParseAssignment(StringRef Name, bool allow_redef,
287 bool NoDeadStrip = false);
289 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
290 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
291 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
292 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
294 // Directive Parsing.
297 DK_NO_DIRECTIVE, // Placeholder
298 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
299 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
300 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
301 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
302 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
303 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
304 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
305 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
306 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
307 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
308 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
309 DK_ELSEIF, DK_ELSE, DK_ENDIF
312 StringMap<DirectiveKind> DirectiveKindMapping;
314 // ".ascii", ".asciz", ".string"
315 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
316 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
317 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
318 bool ParseDirectiveFill(); // ".fill"
319 bool ParseDirectiveZero(); // ".zero"
320 // ".set", ".equ", ".equiv"
321 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
322 bool ParseDirectiveOrg(); // ".org"
323 // ".align{,32}", ".p2align{,w,l}"
324 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
326 // ".bundle_align_mode"
327 bool ParseDirectiveBundleAlignMode();
329 bool ParseDirectiveBundleLock();
331 bool ParseDirectiveBundleUnlock();
333 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
334 /// accepts a single symbol (which should be a label or an external).
335 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
337 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
339 bool ParseDirectiveAbort(); // ".abort"
340 bool ParseDirectiveInclude(); // ".include"
341 bool ParseDirectiveIncbin(); // ".incbin"
343 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
344 // ".ifb" or ".ifnb", depending on ExpectBlank.
345 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
346 // ".ifc" or ".ifnc", depending on ExpectEqual.
347 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
348 // ".ifdef" or ".ifndef", depending on expect_defined
349 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
350 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
351 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
352 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
354 /// ParseEscapedString - Parse the current token as a string which may include
355 /// escaped characters and return the string contents.
356 bool ParseEscapedString(std::string &Data);
358 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
359 MCSymbolRefExpr::VariantKind Variant);
361 // Macro-like directives
362 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
363 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
364 raw_svector_ostream &OS);
365 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
366 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
367 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
368 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
371 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
373 void initializeDirectiveKindMapping();
376 /// \brief Generic implementation of directive handling, etc. which is shared
377 /// (or the default, at least) for all assembler parsers.
378 class GenericAsmParser : public MCAsmParserExtension {
379 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
380 void AddDirectiveHandler(StringRef Directive) {
381 getParser().AddDirectiveHandler(this, Directive,
382 HandleDirective<GenericAsmParser, Handler>);
385 GenericAsmParser() {}
387 AsmParser &getParser() {
388 return (AsmParser&) this->MCAsmParserExtension::getParser();
391 virtual void Initialize(MCAsmParser &Parser) {
392 // Call the base implementation.
393 this->MCAsmParserExtension::Initialize(Parser);
395 // Debugging directives.
396 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
397 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
398 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
399 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
401 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveSpace>(".space");
402 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveSpace>(".skip");
405 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
407 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
409 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
411 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
413 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
414 ".cfi_def_cfa_offset");
415 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
416 ".cfi_adjust_cfa_offset");
417 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
418 ".cfi_def_cfa_register");
419 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
421 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
424 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
426 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
428 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
430 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
432 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
434 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
436 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
438 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
440 &GenericAsmParser::ParseDirectiveCFIUndefined>(".cfi_undefined");
442 &GenericAsmParser::ParseDirectiveCFIRegister>(".cfi_register");
445 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
447 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
449 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
450 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
451 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
452 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
454 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
455 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
458 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
460 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
461 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
462 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
463 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
464 bool ParseDirectiveSpace(StringRef, SMLoc DirectiveLoc);
465 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
466 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
467 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
468 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
469 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
470 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
471 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
472 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
473 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
474 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
475 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
476 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
477 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
478 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
479 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
480 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
481 bool ParseDirectiveCFIUndefined(StringRef, SMLoc DirectiveLoc);
482 bool ParseDirectiveCFIRegister(StringRef, SMLoc DirectiveLoc);
484 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
485 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
486 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
487 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
489 bool ParseDirectiveLEB128(StringRef, SMLoc);
496 extern MCAsmParserExtension *createDarwinAsmParser();
497 extern MCAsmParserExtension *createELFAsmParser();
498 extern MCAsmParserExtension *createCOFFAsmParser();
502 enum { DEFAULT_ADDRSPACE = 0 };
504 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
505 MCStreamer &_Out, const MCAsmInfo &_MAI)
506 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
507 GenericParser(new GenericAsmParser), PlatformParser(0),
508 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
509 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
510 // Save the old handler.
511 SavedDiagHandler = SrcMgr.getDiagHandler();
512 SavedDiagContext = SrcMgr.getDiagContext();
513 // Set our own handler which calls the saved handler.
514 SrcMgr.setDiagHandler(DiagHandler, this);
515 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
517 // Initialize the generic parser.
518 GenericParser->Initialize(*this);
520 // Initialize the platform / file format parser.
522 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
524 if (_MAI.hasMicrosoftFastStdCallMangling()) {
525 PlatformParser = createCOFFAsmParser();
526 PlatformParser->Initialize(*this);
527 } else if (_MAI.hasSubsectionsViaSymbols()) {
528 PlatformParser = createDarwinAsmParser();
529 PlatformParser->Initialize(*this);
532 PlatformParser = createELFAsmParser();
533 PlatformParser->Initialize(*this);
536 initializeDirectiveKindMapping();
539 AsmParser::~AsmParser() {
540 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
542 // Destroy any macros.
543 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
544 ie = MacroMap.end(); it != ie; ++it)
545 delete it->getValue();
547 delete PlatformParser;
548 delete GenericParser;
551 void AsmParser::PrintMacroInstantiations() {
552 // Print the active macro instantiation stack.
553 for (std::vector<MacroInstantiation*>::const_reverse_iterator
554 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
555 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
556 "while in macro instantiation");
559 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
560 if (FatalAssemblerWarnings)
561 return Error(L, Msg, Ranges);
562 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
563 PrintMacroInstantiations();
567 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
569 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
570 PrintMacroInstantiations();
574 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
575 std::string IncludedFile;
576 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
582 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
587 /// Process the specified .incbin file by seaching for it in the include paths
588 /// then just emitting the byte contents of the file to the streamer. This
589 /// returns true on failure.
590 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
591 std::string IncludedFile;
592 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
596 // Pick up the bytes from the file and emit them.
597 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
602 void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
603 if (InBuffer != -1) {
604 CurBuffer = InBuffer;
606 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
608 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
611 const AsmToken &AsmParser::Lex() {
612 const AsmToken *tok = &Lexer.Lex();
614 if (tok->is(AsmToken::Eof)) {
615 // If this is the end of an included file, pop the parent file off the
617 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
618 if (ParentIncludeLoc != SMLoc()) {
619 JumpToLoc(ParentIncludeLoc);
624 if (tok->is(AsmToken::Error))
625 Error(Lexer.getErrLoc(), Lexer.getErr());
630 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
631 // Create the initial section, if requested.
632 if (!NoInitialTextSection)
639 AsmCond StartingCondState = TheCondState;
641 // If we are generating dwarf for assembly source files save the initial text
642 // section and generate a .file directive.
643 if (getContext().getGenDwarfForAssembly()) {
644 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
645 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
646 getStreamer().EmitLabel(SectionStartSym);
647 getContext().setGenDwarfSectionStartSym(SectionStartSym);
648 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
650 getContext().getMainFileName());
653 // While we have input, parse each statement.
654 while (Lexer.isNot(AsmToken::Eof)) {
655 ParseStatementInfo Info;
656 if (!ParseStatement(Info)) continue;
658 // We had an error, validate that one was emitted and recover by skipping to
660 assert(HadError && "Parse statement returned an error, but none emitted!");
661 EatToEndOfStatement();
664 if (TheCondState.TheCond != StartingCondState.TheCond ||
665 TheCondState.Ignore != StartingCondState.Ignore)
666 return TokError("unmatched .ifs or .elses");
668 // Check to see there are no empty DwarfFile slots.
669 const std::vector<MCDwarfFile *> &MCDwarfFiles =
670 getContext().getMCDwarfFiles();
671 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
672 if (!MCDwarfFiles[i])
673 TokError("unassigned file number: " + Twine(i) + " for .file directives");
676 // Check to see that all assembler local symbols were actually defined.
677 // Targets that don't do subsections via symbols may not want this, though,
678 // so conservatively exclude them. Only do this if we're finalizing, though,
679 // as otherwise we won't necessarilly have seen everything yet.
680 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
681 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
682 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
685 MCSymbol *Sym = i->getValue();
686 // Variable symbols may not be marked as defined, so check those
687 // explicitly. If we know it's a variable, we have a definition for
688 // the purposes of this check.
689 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
690 // FIXME: We would really like to refer back to where the symbol was
691 // first referenced for a source location. We need to add something
692 // to track that. Currently, we just point to the end of the file.
693 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
694 "assembler local symbol '" + Sym->getName() +
700 // Finalize the output stream if there are no errors and if the client wants
702 if (!HadError && !NoFinalize)
708 void AsmParser::CheckForValidSection() {
709 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
710 TokError("expected section directive before assembly directive");
711 Out.SwitchSection(Ctx.getMachOSection(
713 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
714 0, SectionKind::getText()));
718 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
719 void AsmParser::EatToEndOfStatement() {
720 while (Lexer.isNot(AsmToken::EndOfStatement) &&
721 Lexer.isNot(AsmToken::Eof))
725 if (Lexer.is(AsmToken::EndOfStatement))
729 StringRef AsmParser::ParseStringToEndOfStatement() {
730 const char *Start = getTok().getLoc().getPointer();
732 while (Lexer.isNot(AsmToken::EndOfStatement) &&
733 Lexer.isNot(AsmToken::Eof))
736 const char *End = getTok().getLoc().getPointer();
737 return StringRef(Start, End - Start);
740 StringRef AsmParser::ParseStringToComma() {
741 const char *Start = getTok().getLoc().getPointer();
743 while (Lexer.isNot(AsmToken::EndOfStatement) &&
744 Lexer.isNot(AsmToken::Comma) &&
745 Lexer.isNot(AsmToken::Eof))
748 const char *End = getTok().getLoc().getPointer();
749 return StringRef(Start, End - Start);
752 /// ParseParenExpr - Parse a paren expression and return it.
753 /// NOTE: This assumes the leading '(' has already been consumed.
755 /// parenexpr ::= expr)
757 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
758 if (ParseExpression(Res)) return true;
759 if (Lexer.isNot(AsmToken::RParen))
760 return TokError("expected ')' in parentheses expression");
761 EndLoc = Lexer.getTok().getEndLoc();
766 /// ParseBracketExpr - Parse a bracket expression and return it.
767 /// NOTE: This assumes the leading '[' has already been consumed.
769 /// bracketexpr ::= expr]
771 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
772 if (ParseExpression(Res)) return true;
773 if (Lexer.isNot(AsmToken::RBrac))
774 return TokError("expected ']' in brackets expression");
775 EndLoc = Lexer.getTok().getEndLoc();
780 /// ParsePrimaryExpr - Parse a primary expression and return it.
781 /// primaryexpr ::= (parenexpr
782 /// primaryexpr ::= symbol
783 /// primaryexpr ::= number
784 /// primaryexpr ::= '.'
785 /// primaryexpr ::= ~,+,- primaryexpr
786 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
787 switch (Lexer.getKind()) {
789 return TokError("unknown token in expression");
790 // If we have an error assume that we've already handled it.
791 case AsmToken::Error:
793 case AsmToken::Exclaim:
794 Lex(); // Eat the operator.
795 if (ParsePrimaryExpr(Res, EndLoc))
797 Res = MCUnaryExpr::CreateLNot(Res, getContext());
799 case AsmToken::Dollar:
800 case AsmToken::String:
801 case AsmToken::Identifier: {
802 StringRef Identifier;
803 if (ParseIdentifier(Identifier))
806 EndLoc = SMLoc::getFromPointer(Identifier.end());
808 // This is a symbol reference.
809 std::pair<StringRef, StringRef> Split = Identifier.split('@');
810 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
812 // Lookup the symbol variant if used.
813 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
814 if (Split.first.size() != Identifier.size()) {
815 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
816 if (Variant == MCSymbolRefExpr::VK_Invalid) {
817 Variant = MCSymbolRefExpr::VK_None;
818 return TokError("invalid variant '" + Split.second + "'");
822 // If this is an absolute variable reference, substitute it now to preserve
823 // semantics in the face of reassignment.
824 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
826 return Error(EndLoc, "unexpected modifier on variable reference");
828 Res = Sym->getVariableValue();
832 // Otherwise create a symbol ref.
833 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
836 case AsmToken::Integer: {
837 SMLoc Loc = getTok().getLoc();
838 int64_t IntVal = getTok().getIntVal();
839 Res = MCConstantExpr::Create(IntVal, getContext());
840 EndLoc = Lexer.getTok().getEndLoc();
842 // Look for 'b' or 'f' following an Integer as a directional label
843 if (Lexer.getKind() == AsmToken::Identifier) {
844 StringRef IDVal = getTok().getString();
845 if (IDVal == "f" || IDVal == "b"){
846 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
847 IDVal == "f" ? 1 : 0);
848 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
850 if (IDVal == "b" && Sym->isUndefined())
851 return Error(Loc, "invalid reference to undefined symbol");
852 EndLoc = Lexer.getTok().getEndLoc();
853 Lex(); // Eat identifier.
858 case AsmToken::Real: {
859 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
860 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
861 Res = MCConstantExpr::Create(IntVal, getContext());
862 EndLoc = Lexer.getTok().getEndLoc();
866 case AsmToken::Dot: {
867 // This is a '.' reference, which references the current PC. Emit a
868 // temporary label to the streamer and refer to it.
869 MCSymbol *Sym = Ctx.CreateTempSymbol();
871 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
872 EndLoc = Lexer.getTok().getEndLoc();
873 Lex(); // Eat identifier.
876 case AsmToken::LParen:
877 Lex(); // Eat the '('.
878 return ParseParenExpr(Res, EndLoc);
879 case AsmToken::LBrac:
880 if (!PlatformParser->HasBracketExpressions())
881 return TokError("brackets expression not supported on this target");
882 Lex(); // Eat the '['.
883 return ParseBracketExpr(Res, EndLoc);
884 case AsmToken::Minus:
885 Lex(); // Eat the operator.
886 if (ParsePrimaryExpr(Res, EndLoc))
888 Res = MCUnaryExpr::CreateMinus(Res, getContext());
891 Lex(); // Eat the operator.
892 if (ParsePrimaryExpr(Res, EndLoc))
894 Res = MCUnaryExpr::CreatePlus(Res, getContext());
896 case AsmToken::Tilde:
897 Lex(); // Eat the operator.
898 if (ParsePrimaryExpr(Res, EndLoc))
900 Res = MCUnaryExpr::CreateNot(Res, getContext());
905 bool AsmParser::ParseExpression(const MCExpr *&Res) {
907 return ParseExpression(Res, EndLoc);
911 AsmParser::ApplyModifierToExpr(const MCExpr *E,
912 MCSymbolRefExpr::VariantKind Variant) {
913 // Recurse over the given expression, rebuilding it to apply the given variant
914 // if there is exactly one symbol.
915 switch (E->getKind()) {
917 case MCExpr::Constant:
920 case MCExpr::SymbolRef: {
921 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
923 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
924 TokError("invalid variant on expression '" +
925 getTok().getIdentifier() + "' (already modified)");
929 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
932 case MCExpr::Unary: {
933 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
934 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
937 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
940 case MCExpr::Binary: {
941 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
942 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
943 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
948 if (!LHS) LHS = BE->getLHS();
949 if (!RHS) RHS = BE->getRHS();
951 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
955 llvm_unreachable("Invalid expression kind!");
958 /// ParseExpression - Parse an expression and return it.
960 /// expr ::= expr &&,|| expr -> lowest.
961 /// expr ::= expr |,^,&,! expr
962 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
963 /// expr ::= expr <<,>> expr
964 /// expr ::= expr +,- expr
965 /// expr ::= expr *,/,% expr -> highest.
966 /// expr ::= primaryexpr
968 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
969 // Parse the expression.
971 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
974 // As a special case, we support 'a op b @ modifier' by rewriting the
975 // expression to include the modifier. This is inefficient, but in general we
976 // expect users to use 'a@modifier op b'.
977 if (Lexer.getKind() == AsmToken::At) {
980 if (Lexer.isNot(AsmToken::Identifier))
981 return TokError("unexpected symbol modifier following '@'");
983 MCSymbolRefExpr::VariantKind Variant =
984 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
985 if (Variant == MCSymbolRefExpr::VK_Invalid)
986 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
988 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
990 return TokError("invalid modifier '" + getTok().getIdentifier() +
991 "' (no symbols present)");
998 // Try to constant fold it up front, if possible.
1000 if (Res->EvaluateAsAbsolute(Value))
1001 Res = MCConstantExpr::Create(Value, getContext());
1006 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1008 return ParseParenExpr(Res, EndLoc) ||
1009 ParseBinOpRHS(1, Res, EndLoc);
1012 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
1015 SMLoc StartLoc = Lexer.getLoc();
1016 if (ParseExpression(Expr))
1019 if (!Expr->EvaluateAsAbsolute(Res))
1020 return Error(StartLoc, "expected absolute expression");
1025 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1026 MCBinaryExpr::Opcode &Kind) {
1029 return 0; // not a binop.
1031 // Lowest Precedence: &&, ||
1032 case AsmToken::AmpAmp:
1033 Kind = MCBinaryExpr::LAnd;
1035 case AsmToken::PipePipe:
1036 Kind = MCBinaryExpr::LOr;
1040 // Low Precedence: |, &, ^
1042 // FIXME: gas seems to support '!' as an infix operator?
1043 case AsmToken::Pipe:
1044 Kind = MCBinaryExpr::Or;
1046 case AsmToken::Caret:
1047 Kind = MCBinaryExpr::Xor;
1050 Kind = MCBinaryExpr::And;
1053 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1054 case AsmToken::EqualEqual:
1055 Kind = MCBinaryExpr::EQ;
1057 case AsmToken::ExclaimEqual:
1058 case AsmToken::LessGreater:
1059 Kind = MCBinaryExpr::NE;
1061 case AsmToken::Less:
1062 Kind = MCBinaryExpr::LT;
1064 case AsmToken::LessEqual:
1065 Kind = MCBinaryExpr::LTE;
1067 case AsmToken::Greater:
1068 Kind = MCBinaryExpr::GT;
1070 case AsmToken::GreaterEqual:
1071 Kind = MCBinaryExpr::GTE;
1074 // Intermediate Precedence: <<, >>
1075 case AsmToken::LessLess:
1076 Kind = MCBinaryExpr::Shl;
1078 case AsmToken::GreaterGreater:
1079 Kind = MCBinaryExpr::Shr;
1082 // High Intermediate Precedence: +, -
1083 case AsmToken::Plus:
1084 Kind = MCBinaryExpr::Add;
1086 case AsmToken::Minus:
1087 Kind = MCBinaryExpr::Sub;
1090 // Highest Precedence: *, /, %
1091 case AsmToken::Star:
1092 Kind = MCBinaryExpr::Mul;
1094 case AsmToken::Slash:
1095 Kind = MCBinaryExpr::Div;
1097 case AsmToken::Percent:
1098 Kind = MCBinaryExpr::Mod;
1104 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1105 /// Res contains the LHS of the expression on input.
1106 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1109 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1110 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1112 // If the next token is lower precedence than we are allowed to eat, return
1113 // successfully with what we ate already.
1114 if (TokPrec < Precedence)
1119 // Eat the next primary expression.
1121 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1123 // If BinOp binds less tightly with RHS than the operator after RHS, let
1124 // the pending operator take RHS as its LHS.
1125 MCBinaryExpr::Opcode Dummy;
1126 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1127 if (TokPrec < NextTokPrec) {
1128 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1131 // Merge LHS and RHS according to operator.
1132 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1137 /// ::= EndOfStatement
1138 /// ::= Label* Directive ...Operands... EndOfStatement
1139 /// ::= Label* Identifier OperandList* EndOfStatement
1140 bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
1141 if (Lexer.is(AsmToken::EndOfStatement)) {
1147 // Statements always start with an identifier or are a full line comment.
1148 AsmToken ID = getTok();
1149 SMLoc IDLoc = ID.getLoc();
1151 int64_t LocalLabelVal = -1;
1152 // A full line comment is a '#' as the first token.
1153 if (Lexer.is(AsmToken::Hash))
1154 return ParseCppHashLineFilenameComment(IDLoc);
1156 // Allow an integer followed by a ':' as a directional local label.
1157 if (Lexer.is(AsmToken::Integer)) {
1158 LocalLabelVal = getTok().getIntVal();
1159 if (LocalLabelVal < 0) {
1160 if (!TheCondState.Ignore)
1161 return TokError("unexpected token at start of statement");
1165 IDVal = getTok().getString();
1166 Lex(); // Consume the integer token to be used as an identifier token.
1167 if (Lexer.getKind() != AsmToken::Colon) {
1168 if (!TheCondState.Ignore)
1169 return TokError("unexpected token at start of statement");
1173 } else if (Lexer.is(AsmToken::Dot)) {
1174 // Treat '.' as a valid identifier in this context.
1178 } else if (ParseIdentifier(IDVal)) {
1179 if (!TheCondState.Ignore)
1180 return TokError("unexpected token at start of statement");
1184 // Handle conditional assembly here before checking for skipping. We
1185 // have to do this so that .endif isn't skipped in a ".if 0" block for
1187 StringMap<DirectiveKind>::const_iterator DirKindIt =
1188 DirectiveKindMapping.find(IDVal);
1189 DirectiveKind DirKind =
1190 (DirKindIt == DirectiveKindMapping.end()) ? DK_NO_DIRECTIVE :
1191 DirKindIt->getValue();
1196 return ParseDirectiveIf(IDLoc);
1198 return ParseDirectiveIfb(IDLoc, true);
1200 return ParseDirectiveIfb(IDLoc, false);
1202 return ParseDirectiveIfc(IDLoc, true);
1204 return ParseDirectiveIfc(IDLoc, false);
1206 return ParseDirectiveIfdef(IDLoc, true);
1209 return ParseDirectiveIfdef(IDLoc, false);
1211 return ParseDirectiveElseIf(IDLoc);
1213 return ParseDirectiveElse(IDLoc);
1215 return ParseDirectiveEndIf(IDLoc);
1218 // If we are in a ".if 0" block, ignore this statement.
1219 if (TheCondState.Ignore) {
1220 EatToEndOfStatement();
1224 // FIXME: Recurse on local labels?
1226 // See what kind of statement we have.
1227 switch (Lexer.getKind()) {
1228 case AsmToken::Colon: {
1229 CheckForValidSection();
1231 // identifier ':' -> Label.
1234 // Diagnose attempt to use '.' as a label.
1236 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1238 // Diagnose attempt to use a variable as a label.
1240 // FIXME: Diagnostics. Note the location of the definition as a label.
1241 // FIXME: This doesn't diagnose assignment to a symbol which has been
1242 // implicitly marked as external.
1244 if (LocalLabelVal == -1)
1245 Sym = getContext().GetOrCreateSymbol(IDVal);
1247 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1248 if (!Sym->isUndefined() || Sym->isVariable())
1249 return Error(IDLoc, "invalid symbol redefinition");
1252 if (!ParsingInlineAsm)
1255 // If we are generating dwarf for assembly source files then gather the
1256 // info to make a dwarf label entry for this label if needed.
1257 if (getContext().getGenDwarfForAssembly())
1258 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1261 // Consume any end of statement token, if present, to avoid spurious
1262 // AddBlankLine calls().
1263 if (Lexer.is(AsmToken::EndOfStatement)) {
1265 if (Lexer.is(AsmToken::Eof))
1272 case AsmToken::Equal:
1273 // identifier '=' ... -> assignment statement
1276 return ParseAssignment(IDVal, true);
1278 default: // Normal instruction or directive.
1282 // If macros are enabled, check to see if this is a macro instantiation.
1283 if (MacrosEnabled())
1284 if (const Macro *M = MacroMap.lookup(IDVal))
1285 return HandleMacroEntry(IDVal, IDLoc, M);
1287 // Otherwise, we have a normal instruction or directive.
1288 if (IDVal[0] == '.' && IDVal != ".") {
1290 // Target hook for parsing target specific directives.
1291 if (!getTargetParser().ParseDirective(ID))
1299 return ParseDirectiveSet(IDVal, true);
1301 return ParseDirectiveSet(IDVal, false);
1303 return ParseDirectiveAscii(IDVal, false);
1306 return ParseDirectiveAscii(IDVal, true);
1308 return ParseDirectiveValue(1);
1312 return ParseDirectiveValue(2);
1316 return ParseDirectiveValue(4);
1319 return ParseDirectiveValue(8);
1322 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1324 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1326 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1327 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1330 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1331 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1334 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1336 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1338 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1340 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1342 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1344 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1346 return ParseDirectiveOrg();
1348 return ParseDirectiveFill();
1350 return ParseDirectiveZero();
1352 EatToEndOfStatement(); // .extern is the default, ignore it.
1356 return ParseDirectiveSymbolAttribute(MCSA_Global);
1357 case DK_INDIRECT_SYMBOL:
1358 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1359 case DK_LAZY_REFERENCE:
1360 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1361 case DK_NO_DEAD_STRIP:
1362 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1363 case DK_SYMBOL_RESOLVER:
1364 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1365 case DK_PRIVATE_EXTERN:
1366 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1368 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1369 case DK_WEAK_DEFINITION:
1370 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1371 case DK_WEAK_REFERENCE:
1372 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1373 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1374 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1377 return ParseDirectiveComm(/*IsLocal=*/false);
1379 return ParseDirectiveComm(/*IsLocal=*/true);
1381 return ParseDirectiveAbort();
1383 return ParseDirectiveInclude();
1385 return ParseDirectiveIncbin();
1388 return TokError(Twine(IDVal) + " not supported yet");
1390 return ParseDirectiveRept(IDLoc);
1392 return ParseDirectiveIrp(IDLoc);
1394 return ParseDirectiveIrpc(IDLoc);
1396 return ParseDirectiveEndr(IDLoc);
1397 case DK_BUNDLE_ALIGN_MODE:
1398 return ParseDirectiveBundleAlignMode();
1399 case DK_BUNDLE_LOCK:
1400 return ParseDirectiveBundleLock();
1401 case DK_BUNDLE_UNLOCK:
1402 return ParseDirectiveBundleUnlock();
1405 // Look up the handler in the extension handler table.
1406 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1407 DirectiveMap.lookup(IDVal);
1409 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1411 return Error(IDLoc, "unknown directive");
1415 if (ParsingInlineAsm && IDVal == "_emit")
1416 return ParseDirectiveEmit(IDLoc, Info);
1418 CheckForValidSection();
1420 // Canonicalize the opcode to lower case.
1421 SmallString<128> OpcodeStr;
1422 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1423 OpcodeStr.push_back(tolower(IDVal[i]));
1425 ParseInstructionInfo IInfo(Info.AsmRewrites);
1426 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1427 IDLoc,Info.ParsedOperands);
1428 Info.ParseError = HadError;
1430 // Dump the parsed representation, if requested.
1431 if (getShowParsedOperands()) {
1432 SmallString<256> Str;
1433 raw_svector_ostream OS(Str);
1434 OS << "parsed instruction: [";
1435 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1438 Info.ParsedOperands[i]->print(OS);
1442 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1445 // If we are generating dwarf for assembly source files and the current
1446 // section is the initial text section then generate a .loc directive for
1448 if (!HadError && getContext().getGenDwarfForAssembly() &&
1449 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
1451 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1453 // If we previously parsed a cpp hash file line comment then make sure the
1454 // current Dwarf File is for the CppHashFilename if not then emit the
1455 // Dwarf File table for it and adjust the line number for the .loc.
1456 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1457 getContext().getMCDwarfFiles();
1458 if (CppHashFilename.size() != 0) {
1459 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1461 getStreamer().EmitDwarfFileDirective(
1462 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1464 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
1465 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1468 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1469 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1470 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1474 // If parsing succeeded, match the instruction.
1477 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1478 Info.ParsedOperands,
1483 // Don't skip the rest of the line, the instruction parser is responsible for
1488 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1489 /// since they may not be able to be tokenized to get to the end of line token.
1490 void AsmParser::EatToEndOfLine() {
1491 if (!Lexer.is(AsmToken::EndOfStatement))
1492 Lexer.LexUntilEndOfLine();
1497 /// ParseCppHashLineFilenameComment as this:
1498 /// ::= # number "filename"
1499 /// or just as a full line comment if it doesn't have a number and a string.
1500 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1501 Lex(); // Eat the hash token.
1503 if (getLexer().isNot(AsmToken::Integer)) {
1504 // Consume the line since in cases it is not a well-formed line directive,
1505 // as if were simply a full line comment.
1510 int64_t LineNumber = getTok().getIntVal();
1513 if (getLexer().isNot(AsmToken::String)) {
1518 StringRef Filename = getTok().getString();
1519 // Get rid of the enclosing quotes.
1520 Filename = Filename.substr(1, Filename.size()-2);
1522 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1524 CppHashFilename = Filename;
1525 CppHashLineNumber = LineNumber;
1526 CppHashBuf = CurBuffer;
1528 // Ignore any trailing characters, they're just comment.
1533 /// DiagHandler - will use the last parsed cpp hash line filename comment
1534 /// for the Filename and LineNo if any in the diagnostic.
1535 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1536 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1537 raw_ostream &OS = errs();
1539 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1540 const SMLoc &DiagLoc = Diag.getLoc();
1541 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1542 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1544 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1545 // before printing the message.
1546 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1547 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1548 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1549 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1552 // If we have not parsed a cpp hash line filename comment or the source
1553 // manager changed or buffer changed (like in a nested include) then just
1554 // print the normal diagnostic using its Filename and LineNo.
1555 if (!Parser->CppHashLineNumber ||
1556 &DiagSrcMgr != &Parser->SrcMgr ||
1557 DiagBuf != CppHashBuf) {
1558 if (Parser->SavedDiagHandler)
1559 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1565 // Use the CppHashFilename and calculate a line number based on the
1566 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1568 const std::string Filename = Parser->CppHashFilename;
1570 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1571 int CppHashLocLineNo =
1572 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1573 int LineNo = Parser->CppHashLineNumber - 1 +
1574 (DiagLocLineNo - CppHashLocLineNo);
1576 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1577 Filename, LineNo, Diag.getColumnNo(),
1578 Diag.getKind(), Diag.getMessage(),
1579 Diag.getLineContents(), Diag.getRanges());
1581 if (Parser->SavedDiagHandler)
1582 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1584 NewDiag.print(0, OS);
1587 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1588 // difference being that that function accepts '@' as part of identifiers and
1589 // we can't do that. AsmLexer.cpp should probably be changed to handle
1590 // '@' as a special case when needed.
1591 static bool isIdentifierChar(char c) {
1592 return isalnum(c) || c == '_' || c == '$' || c == '.';
1595 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1596 const MacroParameters &Parameters,
1597 const MacroArguments &A,
1599 unsigned NParameters = Parameters.size();
1600 if (NParameters != 0 && NParameters != A.size())
1601 return Error(L, "Wrong number of arguments");
1603 // A macro without parameters is handled differently on Darwin:
1604 // gas accepts no arguments and does no substitutions
1605 while (!Body.empty()) {
1606 // Scan for the next substitution.
1607 std::size_t End = Body.size(), Pos = 0;
1608 for (; Pos != End; ++Pos) {
1609 // Check for a substitution or escape.
1611 // This macro has no parameters, look for $0, $1, etc.
1612 if (Body[Pos] != '$' || Pos + 1 == End)
1615 char Next = Body[Pos + 1];
1616 if (Next == '$' || Next == 'n' || isdigit(Next))
1619 // This macro has parameters, look for \foo, \bar, etc.
1620 if (Body[Pos] == '\\' && Pos + 1 != End)
1626 OS << Body.slice(0, Pos);
1628 // Check if we reached the end.
1633 switch (Body[Pos+1]) {
1639 // $n => number of arguments
1644 // $[0-9] => argument
1646 // Missing arguments are ignored.
1647 unsigned Index = Body[Pos+1] - '0';
1648 if (Index >= A.size())
1651 // Otherwise substitute with the token values, with spaces eliminated.
1652 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1653 ie = A[Index].end(); it != ie; ++it)
1654 OS << it->getString();
1660 unsigned I = Pos + 1;
1661 while (isIdentifierChar(Body[I]) && I + 1 != End)
1664 const char *Begin = Body.data() + Pos +1;
1665 StringRef Argument(Begin, I - (Pos +1));
1667 for (; Index < NParameters; ++Index)
1668 if (Parameters[Index].first == Argument)
1671 if (Index == NParameters) {
1672 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1675 OS << '\\' << Argument;
1679 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1680 ie = A[Index].end(); it != ie; ++it)
1681 if (it->getKind() == AsmToken::String)
1682 OS << it->getStringContents();
1684 OS << it->getString();
1686 Pos += 1 + Argument.size();
1689 // Update the scan point.
1690 Body = Body.substr(Pos);
1696 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL,
1699 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1704 static bool IsOperator(AsmToken::TokenKind kind)
1710 case AsmToken::Plus:
1711 case AsmToken::Minus:
1712 case AsmToken::Tilde:
1713 case AsmToken::Slash:
1714 case AsmToken::Star:
1716 case AsmToken::Equal:
1717 case AsmToken::EqualEqual:
1718 case AsmToken::Pipe:
1719 case AsmToken::PipePipe:
1720 case AsmToken::Caret:
1722 case AsmToken::AmpAmp:
1723 case AsmToken::Exclaim:
1724 case AsmToken::ExclaimEqual:
1725 case AsmToken::Percent:
1726 case AsmToken::Less:
1727 case AsmToken::LessEqual:
1728 case AsmToken::LessLess:
1729 case AsmToken::LessGreater:
1730 case AsmToken::Greater:
1731 case AsmToken::GreaterEqual:
1732 case AsmToken::GreaterGreater:
1737 bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
1738 AsmToken::TokenKind &ArgumentDelimiter) {
1739 unsigned ParenLevel = 0;
1740 unsigned AddTokens = 0;
1742 // gas accepts arguments separated by whitespace, except on Darwin
1744 Lexer.setSkipSpace(false);
1747 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1748 Lexer.setSkipSpace(true);
1749 return TokError("unexpected token in macro instantiation");
1752 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1753 // Spaces and commas cannot be mixed to delimit parameters
1754 if (ArgumentDelimiter == AsmToken::Eof)
1755 ArgumentDelimiter = AsmToken::Comma;
1756 else if (ArgumentDelimiter != AsmToken::Comma) {
1757 Lexer.setSkipSpace(true);
1758 return TokError("expected ' ' for macro argument separator");
1763 if (Lexer.is(AsmToken::Space)) {
1764 Lex(); // Eat spaces
1766 // Spaces can delimit parameters, but could also be part an expression.
1767 // If the token after a space is an operator, add the token and the next
1768 // one into this argument
1769 if (ArgumentDelimiter == AsmToken::Space ||
1770 ArgumentDelimiter == AsmToken::Eof) {
1771 if (IsOperator(Lexer.getKind())) {
1772 // Check to see whether the token is used as an operator,
1773 // or part of an identifier
1774 const char *NextChar = getTok().getEndLoc().getPointer();
1775 if (*NextChar == ' ')
1779 if (!AddTokens && ParenLevel == 0) {
1780 if (ArgumentDelimiter == AsmToken::Eof &&
1781 !IsOperator(Lexer.getKind()))
1782 ArgumentDelimiter = AsmToken::Space;
1788 // HandleMacroEntry relies on not advancing the lexer here
1789 // to be able to fill in the remaining default parameter values
1790 if (Lexer.is(AsmToken::EndOfStatement))
1793 // Adjust the current parentheses level.
1794 if (Lexer.is(AsmToken::LParen))
1796 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1799 // Append the token to the current argument list.
1800 MA.push_back(getTok());
1806 Lexer.setSkipSpace(true);
1807 if (ParenLevel != 0)
1808 return TokError("unbalanced parentheses in macro argument");
1812 // Parse the macro instantiation arguments.
1813 bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
1814 const unsigned NParameters = M ? M->Parameters.size() : 0;
1815 // Argument delimiter is initially unknown. It will be set by
1816 // ParseMacroArgument()
1817 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1819 // Parse two kinds of macro invocations:
1820 // - macros defined without any parameters accept an arbitrary number of them
1821 // - macros defined with parameters accept at most that many of them
1822 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1824 MCAsmMacroArgument MA;
1826 if (ParseMacroArgument(MA, ArgumentDelimiter))
1829 if (!MA.empty() || !NParameters)
1831 else if (NParameters) {
1832 if (!M->Parameters[Parameter].second.empty())
1833 A.push_back(M->Parameters[Parameter].second);
1836 // At the end of the statement, fill in remaining arguments that have
1837 // default values. If there aren't any, then the next argument is
1838 // required but missing
1839 if (Lexer.is(AsmToken::EndOfStatement)) {
1840 if (NParameters && Parameter < NParameters - 1) {
1841 if (M->Parameters[Parameter + 1].second.empty())
1842 return TokError("macro argument '" +
1843 Twine(M->Parameters[Parameter + 1].first) +
1851 if (Lexer.is(AsmToken::Comma))
1854 return TokError("Too many arguments");
1857 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1859 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1860 // this, although we should protect against infinite loops.
1861 if (ActiveMacros.size() == 20)
1862 return TokError("macros cannot be nested more than 20 levels deep");
1865 if (ParseMacroArguments(M, A))
1868 // Remove any trailing empty arguments. Do this after-the-fact as we have
1869 // to keep empty arguments in the middle of the list or positionality
1870 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1871 while (!A.empty() && A.back().empty())
1874 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1875 // to hold the macro body with substitutions.
1876 SmallString<256> Buf;
1877 StringRef Body = M->Body;
1878 raw_svector_ostream OS(Buf);
1880 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1883 // We include the .endmacro in the buffer as our queue to exit the macro
1885 OS << ".endmacro\n";
1887 MemoryBuffer *Instantiation =
1888 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1890 // Create the macro instantiation object and add to the current macro
1891 // instantiation stack.
1892 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1896 ActiveMacros.push_back(MI);
1898 // Jump to the macro instantiation and prime the lexer.
1899 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1900 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1906 void AsmParser::HandleMacroExit() {
1907 // Jump to the EndOfStatement we should return to, and consume it.
1908 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
1911 // Pop the instantiation entry.
1912 delete ActiveMacros.back();
1913 ActiveMacros.pop_back();
1916 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1917 switch (Value->getKind()) {
1918 case MCExpr::Binary: {
1919 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1920 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1923 case MCExpr::Target:
1924 case MCExpr::Constant:
1926 case MCExpr::SymbolRef: {
1927 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1929 return IsUsedIn(Sym, S.getVariableValue());
1933 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1936 llvm_unreachable("Unknown expr kind!");
1939 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1941 // FIXME: Use better location, we should use proper tokens.
1942 SMLoc EqualLoc = Lexer.getLoc();
1944 const MCExpr *Value;
1945 if (ParseExpression(Value))
1948 // Note: we don't count b as used in "a = b". This is to allow
1952 if (Lexer.isNot(AsmToken::EndOfStatement))
1953 return TokError("unexpected token in assignment");
1955 // Error on assignment to '.'.
1957 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1958 "(use '.space' or '.org').)"));
1961 // Eat the end of statement marker.
1964 // Validate that the LHS is allowed to be a variable (either it has not been
1965 // used as a symbol, or it is an absolute symbol).
1966 MCSymbol *Sym = getContext().LookupSymbol(Name);
1968 // Diagnose assignment to a label.
1970 // FIXME: Diagnostics. Note the location of the definition as a label.
1971 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1972 if (IsUsedIn(Sym, Value))
1973 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1974 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1975 ; // Allow redefinitions of undefined symbols only used in directives.
1976 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1977 ; // Allow redefinitions of variables that haven't yet been used.
1978 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1979 return Error(EqualLoc, "redefinition of '" + Name + "'");
1980 else if (!Sym->isVariable())
1981 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1982 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1983 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1986 // Don't count these checks as uses.
1987 Sym->setUsed(false);
1989 Sym = getContext().GetOrCreateSymbol(Name);
1991 // FIXME: Handle '.'.
1993 // Do the assignment.
1994 Out.EmitAssignment(Sym, Value);
1996 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2002 /// ParseIdentifier:
2005 bool AsmParser::ParseIdentifier(StringRef &Res) {
2006 // The assembler has relaxed rules for accepting identifiers, in particular we
2007 // allow things like '.globl $foo', which would normally be separate
2008 // tokens. At this level, we have already lexed so we cannot (currently)
2009 // handle this as a context dependent token, instead we detect adjacent tokens
2010 // and return the combined identifier.
2011 if (Lexer.is(AsmToken::Dollar)) {
2012 SMLoc DollarLoc = getLexer().getLoc();
2014 // Consume the dollar sign, and check for a following identifier.
2016 if (Lexer.isNot(AsmToken::Identifier))
2019 // We have a '$' followed by an identifier, make sure they are adjacent.
2020 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2023 // Construct the joined identifier and consume the token.
2024 Res = StringRef(DollarLoc.getPointer(),
2025 getTok().getIdentifier().size() + 1);
2030 if (Lexer.isNot(AsmToken::Identifier) &&
2031 Lexer.isNot(AsmToken::String))
2034 Res = getTok().getIdentifier();
2036 Lex(); // Consume the identifier token.
2041 /// ParseDirectiveSet:
2042 /// ::= .equ identifier ',' expression
2043 /// ::= .equiv identifier ',' expression
2044 /// ::= .set identifier ',' expression
2045 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
2048 if (ParseIdentifier(Name))
2049 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2051 if (getLexer().isNot(AsmToken::Comma))
2052 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2055 return ParseAssignment(Name, allow_redef, true);
2058 bool AsmParser::ParseEscapedString(std::string &Data) {
2059 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2062 StringRef Str = getTok().getStringContents();
2063 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2064 if (Str[i] != '\\') {
2069 // Recognize escaped characters. Note that this escape semantics currently
2070 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2073 return TokError("unexpected backslash at end of string");
2075 // Recognize octal sequences.
2076 if ((unsigned) (Str[i] - '0') <= 7) {
2077 // Consume up to three octal characters.
2078 unsigned Value = Str[i] - '0';
2080 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2082 Value = Value * 8 + (Str[i] - '0');
2084 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2086 Value = Value * 8 + (Str[i] - '0');
2091 return TokError("invalid octal escape sequence (out of range)");
2093 Data += (unsigned char) Value;
2097 // Otherwise recognize individual escapes.
2100 // Just reject invalid escape sequences for now.
2101 return TokError("invalid escape sequence (unrecognized character)");
2103 case 'b': Data += '\b'; break;
2104 case 'f': Data += '\f'; break;
2105 case 'n': Data += '\n'; break;
2106 case 'r': Data += '\r'; break;
2107 case 't': Data += '\t'; break;
2108 case '"': Data += '"'; break;
2109 case '\\': Data += '\\'; break;
2116 /// ParseDirectiveAscii:
2117 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2118 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2119 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2120 CheckForValidSection();
2123 if (getLexer().isNot(AsmToken::String))
2124 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2127 if (ParseEscapedString(Data))
2130 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2132 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2136 if (getLexer().is(AsmToken::EndOfStatement))
2139 if (getLexer().isNot(AsmToken::Comma))
2140 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2149 /// ParseDirectiveValue
2150 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2151 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2152 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2153 CheckForValidSection();
2156 const MCExpr *Value;
2157 SMLoc ExprLoc = getLexer().getLoc();
2158 if (ParseExpression(Value))
2161 // Special case constant expressions to match code generator.
2162 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2163 assert(Size <= 8 && "Invalid size");
2164 uint64_t IntValue = MCE->getValue();
2165 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2166 return Error(ExprLoc, "literal value out of range for directive");
2167 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2169 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2171 if (getLexer().is(AsmToken::EndOfStatement))
2174 // FIXME: Improve diagnostic.
2175 if (getLexer().isNot(AsmToken::Comma))
2176 return TokError("unexpected token in directive");
2185 /// ParseDirectiveRealValue
2186 /// ::= (.single | .double) [ expression (, expression)* ]
2187 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2188 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2189 CheckForValidSection();
2192 // We don't truly support arithmetic on floating point expressions, so we
2193 // have to manually parse unary prefixes.
2195 if (getLexer().is(AsmToken::Minus)) {
2198 } else if (getLexer().is(AsmToken::Plus))
2201 if (getLexer().isNot(AsmToken::Integer) &&
2202 getLexer().isNot(AsmToken::Real) &&
2203 getLexer().isNot(AsmToken::Identifier))
2204 return TokError("unexpected token in directive");
2206 // Convert to an APFloat.
2207 APFloat Value(Semantics);
2208 StringRef IDVal = getTok().getString();
2209 if (getLexer().is(AsmToken::Identifier)) {
2210 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2211 Value = APFloat::getInf(Semantics);
2212 else if (!IDVal.compare_lower("nan"))
2213 Value = APFloat::getNaN(Semantics, false, ~0);
2215 return TokError("invalid floating point literal");
2216 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2217 APFloat::opInvalidOp)
2218 return TokError("invalid floating point literal");
2222 // Consume the numeric token.
2225 // Emit the value as an integer.
2226 APInt AsInt = Value.bitcastToAPInt();
2227 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2228 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2230 if (getLexer().is(AsmToken::EndOfStatement))
2233 if (getLexer().isNot(AsmToken::Comma))
2234 return TokError("unexpected token in directive");
2243 /// ParseDirectiveZero
2244 /// ::= .zero expression
2245 bool AsmParser::ParseDirectiveZero() {
2246 CheckForValidSection();
2249 if (ParseAbsoluteExpression(NumBytes))
2253 if (getLexer().is(AsmToken::Comma)) {
2255 if (ParseAbsoluteExpression(Val))
2259 if (getLexer().isNot(AsmToken::EndOfStatement))
2260 return TokError("unexpected token in '.zero' directive");
2264 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2269 /// ParseDirectiveFill
2270 /// ::= .fill expression , expression , expression
2271 bool AsmParser::ParseDirectiveFill() {
2272 CheckForValidSection();
2275 if (ParseAbsoluteExpression(NumValues))
2278 if (getLexer().isNot(AsmToken::Comma))
2279 return TokError("unexpected token in '.fill' directive");
2283 if (ParseAbsoluteExpression(FillSize))
2286 if (getLexer().isNot(AsmToken::Comma))
2287 return TokError("unexpected token in '.fill' directive");
2291 if (ParseAbsoluteExpression(FillExpr))
2294 if (getLexer().isNot(AsmToken::EndOfStatement))
2295 return TokError("unexpected token in '.fill' directive");
2299 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2300 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2302 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2303 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2308 /// ParseDirectiveOrg
2309 /// ::= .org expression [ , expression ]
2310 bool AsmParser::ParseDirectiveOrg() {
2311 CheckForValidSection();
2313 const MCExpr *Offset;
2314 SMLoc Loc = getTok().getLoc();
2315 if (ParseExpression(Offset))
2318 // Parse optional fill expression.
2319 int64_t FillExpr = 0;
2320 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2321 if (getLexer().isNot(AsmToken::Comma))
2322 return TokError("unexpected token in '.org' directive");
2325 if (ParseAbsoluteExpression(FillExpr))
2328 if (getLexer().isNot(AsmToken::EndOfStatement))
2329 return TokError("unexpected token in '.org' directive");
2334 // Only limited forms of relocatable expressions are accepted here, it
2335 // has to be relative to the current section. The streamer will return
2336 // 'true' if the expression wasn't evaluatable.
2337 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2338 return Error(Loc, "expected assembly-time absolute expression");
2343 /// ParseDirectiveAlign
2344 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2345 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2346 CheckForValidSection();
2348 SMLoc AlignmentLoc = getLexer().getLoc();
2350 if (ParseAbsoluteExpression(Alignment))
2354 bool HasFillExpr = false;
2355 int64_t FillExpr = 0;
2356 int64_t MaxBytesToFill = 0;
2357 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2358 if (getLexer().isNot(AsmToken::Comma))
2359 return TokError("unexpected token in directive");
2362 // The fill expression can be omitted while specifying a maximum number of
2363 // alignment bytes, e.g:
2365 if (getLexer().isNot(AsmToken::Comma)) {
2367 if (ParseAbsoluteExpression(FillExpr))
2371 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2372 if (getLexer().isNot(AsmToken::Comma))
2373 return TokError("unexpected token in directive");
2376 MaxBytesLoc = getLexer().getLoc();
2377 if (ParseAbsoluteExpression(MaxBytesToFill))
2380 if (getLexer().isNot(AsmToken::EndOfStatement))
2381 return TokError("unexpected token in directive");
2390 // Compute alignment in bytes.
2392 // FIXME: Diagnose overflow.
2393 if (Alignment >= 32) {
2394 Error(AlignmentLoc, "invalid alignment value");
2398 Alignment = 1ULL << Alignment;
2401 // Diagnose non-sensical max bytes to align.
2402 if (MaxBytesLoc.isValid()) {
2403 if (MaxBytesToFill < 1) {
2404 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2405 "many bytes, ignoring maximum bytes expression");
2409 if (MaxBytesToFill >= Alignment) {
2410 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2416 // Check whether we should use optimal code alignment for this .align
2418 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2419 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2420 ValueSize == 1 && UseCodeAlign) {
2421 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2423 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2424 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2432 /// ParseDirectiveBundleAlignMode
2433 /// ::= {.bundle_align_mode} expression
2434 bool AsmParser::ParseDirectiveBundleAlignMode() {
2435 CheckForValidSection();
2437 // Expect a single argument: an expression that evaluates to a constant
2438 // in the inclusive range 0-30.
2439 SMLoc ExprLoc = getLexer().getLoc();
2440 int64_t AlignSizePow2;
2441 if (ParseAbsoluteExpression(AlignSizePow2))
2443 else if (getLexer().isNot(AsmToken::EndOfStatement))
2444 return TokError("unexpected token after expression in"
2445 " '.bundle_align_mode' directive");
2446 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
2447 return Error(ExprLoc,
2448 "invalid bundle alignment size (expected between 0 and 30)");
2452 // Because of AlignSizePow2's verified range we can safely truncate it to
2454 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
2458 /// ParseDirectiveBundleLock
2459 /// ::= {.bundle_lock} [align_to_end]
2460 bool AsmParser::ParseDirectiveBundleLock() {
2461 CheckForValidSection();
2462 bool AlignToEnd = false;
2464 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2466 SMLoc Loc = getTok().getLoc();
2467 const char *kInvalidOptionError =
2468 "invalid option for '.bundle_lock' directive";
2470 if (ParseIdentifier(Option))
2471 return Error(Loc, kInvalidOptionError);
2473 if (Option != "align_to_end")
2474 return Error(Loc, kInvalidOptionError);
2475 else if (getLexer().isNot(AsmToken::EndOfStatement))
2477 "unexpected token after '.bundle_lock' directive option");
2483 getStreamer().EmitBundleLock(AlignToEnd);
2487 /// ParseDirectiveBundleLock
2488 /// ::= {.bundle_lock}
2489 bool AsmParser::ParseDirectiveBundleUnlock() {
2490 CheckForValidSection();
2492 if (getLexer().isNot(AsmToken::EndOfStatement))
2493 return TokError("unexpected token in '.bundle_unlock' directive");
2496 getStreamer().EmitBundleUnlock();
2500 /// ParseDirectiveSymbolAttribute
2501 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2502 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2503 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2506 SMLoc Loc = getTok().getLoc();
2508 if (ParseIdentifier(Name))
2509 return Error(Loc, "expected identifier in directive");
2511 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2513 // Assembler local symbols don't make any sense here. Complain loudly.
2514 if (Sym->isTemporary())
2515 return Error(Loc, "non-local symbol required in directive");
2517 getStreamer().EmitSymbolAttribute(Sym, Attr);
2519 if (getLexer().is(AsmToken::EndOfStatement))
2522 if (getLexer().isNot(AsmToken::Comma))
2523 return TokError("unexpected token in directive");
2532 /// ParseDirectiveComm
2533 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2534 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2535 CheckForValidSection();
2537 SMLoc IDLoc = getLexer().getLoc();
2539 if (ParseIdentifier(Name))
2540 return TokError("expected identifier in directive");
2542 // Handle the identifier as the key symbol.
2543 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2545 if (getLexer().isNot(AsmToken::Comma))
2546 return TokError("unexpected token in directive");
2550 SMLoc SizeLoc = getLexer().getLoc();
2551 if (ParseAbsoluteExpression(Size))
2554 int64_t Pow2Alignment = 0;
2555 SMLoc Pow2AlignmentLoc;
2556 if (getLexer().is(AsmToken::Comma)) {
2558 Pow2AlignmentLoc = getLexer().getLoc();
2559 if (ParseAbsoluteExpression(Pow2Alignment))
2562 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2563 if (IsLocal && LCOMM == LCOMM::NoAlignment)
2564 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2566 // If this target takes alignments in bytes (not log) validate and convert.
2567 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2568 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
2569 if (!isPowerOf2_64(Pow2Alignment))
2570 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2571 Pow2Alignment = Log2_64(Pow2Alignment);
2575 if (getLexer().isNot(AsmToken::EndOfStatement))
2576 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2580 // NOTE: a size of zero for a .comm should create a undefined symbol
2581 // but a size of .lcomm creates a bss symbol of size zero.
2583 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2584 "be less than zero");
2586 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2587 // may internally end up wanting an alignment in bytes.
2588 // FIXME: Diagnose overflow.
2589 if (Pow2Alignment < 0)
2590 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2591 "alignment, can't be less than zero");
2593 if (!Sym->isUndefined())
2594 return Error(IDLoc, "invalid symbol redefinition");
2596 // Create the Symbol as a common or local common with Size and Pow2Alignment
2598 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2602 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2606 /// ParseDirectiveAbort
2607 /// ::= .abort [... message ...]
2608 bool AsmParser::ParseDirectiveAbort() {
2609 // FIXME: Use loc from directive.
2610 SMLoc Loc = getLexer().getLoc();
2612 StringRef Str = ParseStringToEndOfStatement();
2613 if (getLexer().isNot(AsmToken::EndOfStatement))
2614 return TokError("unexpected token in '.abort' directive");
2619 Error(Loc, ".abort detected. Assembly stopping.");
2621 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2622 // FIXME: Actually abort assembly here.
2627 /// ParseDirectiveInclude
2628 /// ::= .include "filename"
2629 bool AsmParser::ParseDirectiveInclude() {
2630 if (getLexer().isNot(AsmToken::String))
2631 return TokError("expected string in '.include' directive");
2633 std::string Filename = getTok().getString();
2634 SMLoc IncludeLoc = getLexer().getLoc();
2637 if (getLexer().isNot(AsmToken::EndOfStatement))
2638 return TokError("unexpected token in '.include' directive");
2640 // Strip the quotes.
2641 Filename = Filename.substr(1, Filename.size()-2);
2643 // Attempt to switch the lexer to the included file before consuming the end
2644 // of statement to avoid losing it when we switch.
2645 if (EnterIncludeFile(Filename)) {
2646 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2653 /// ParseDirectiveIncbin
2654 /// ::= .incbin "filename"
2655 bool AsmParser::ParseDirectiveIncbin() {
2656 if (getLexer().isNot(AsmToken::String))
2657 return TokError("expected string in '.incbin' directive");
2659 std::string Filename = getTok().getString();
2660 SMLoc IncbinLoc = getLexer().getLoc();
2663 if (getLexer().isNot(AsmToken::EndOfStatement))
2664 return TokError("unexpected token in '.incbin' directive");
2666 // Strip the quotes.
2667 Filename = Filename.substr(1, Filename.size()-2);
2669 // Attempt to process the included file.
2670 if (ProcessIncbinFile(Filename)) {
2671 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2678 /// ParseDirectiveIf
2679 /// ::= .if expression
2680 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2681 TheCondStack.push_back(TheCondState);
2682 TheCondState.TheCond = AsmCond::IfCond;
2683 if (TheCondState.Ignore) {
2684 EatToEndOfStatement();
2687 if (ParseAbsoluteExpression(ExprValue))
2690 if (getLexer().isNot(AsmToken::EndOfStatement))
2691 return TokError("unexpected token in '.if' directive");
2695 TheCondState.CondMet = ExprValue;
2696 TheCondState.Ignore = !TheCondState.CondMet;
2702 /// ParseDirectiveIfb
2704 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2705 TheCondStack.push_back(TheCondState);
2706 TheCondState.TheCond = AsmCond::IfCond;
2708 if (TheCondState.Ignore) {
2709 EatToEndOfStatement();
2711 StringRef Str = ParseStringToEndOfStatement();
2713 if (getLexer().isNot(AsmToken::EndOfStatement))
2714 return TokError("unexpected token in '.ifb' directive");
2718 TheCondState.CondMet = ExpectBlank == Str.empty();
2719 TheCondState.Ignore = !TheCondState.CondMet;
2725 /// ParseDirectiveIfc
2726 /// ::= .ifc string1, string2
2727 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2728 TheCondStack.push_back(TheCondState);
2729 TheCondState.TheCond = AsmCond::IfCond;
2731 if (TheCondState.Ignore) {
2732 EatToEndOfStatement();
2734 StringRef Str1 = ParseStringToComma();
2736 if (getLexer().isNot(AsmToken::Comma))
2737 return TokError("unexpected token in '.ifc' directive");
2741 StringRef Str2 = ParseStringToEndOfStatement();
2743 if (getLexer().isNot(AsmToken::EndOfStatement))
2744 return TokError("unexpected token in '.ifc' directive");
2748 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2749 TheCondState.Ignore = !TheCondState.CondMet;
2755 /// ParseDirectiveIfdef
2756 /// ::= .ifdef symbol
2757 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2759 TheCondStack.push_back(TheCondState);
2760 TheCondState.TheCond = AsmCond::IfCond;
2762 if (TheCondState.Ignore) {
2763 EatToEndOfStatement();
2765 if (ParseIdentifier(Name))
2766 return TokError("expected identifier after '.ifdef'");
2770 MCSymbol *Sym = getContext().LookupSymbol(Name);
2773 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2775 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2776 TheCondState.Ignore = !TheCondState.CondMet;
2782 /// ParseDirectiveElseIf
2783 /// ::= .elseif expression
2784 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2785 if (TheCondState.TheCond != AsmCond::IfCond &&
2786 TheCondState.TheCond != AsmCond::ElseIfCond)
2787 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2789 TheCondState.TheCond = AsmCond::ElseIfCond;
2791 bool LastIgnoreState = false;
2792 if (!TheCondStack.empty())
2793 LastIgnoreState = TheCondStack.back().Ignore;
2794 if (LastIgnoreState || TheCondState.CondMet) {
2795 TheCondState.Ignore = true;
2796 EatToEndOfStatement();
2800 if (ParseAbsoluteExpression(ExprValue))
2803 if (getLexer().isNot(AsmToken::EndOfStatement))
2804 return TokError("unexpected token in '.elseif' directive");
2807 TheCondState.CondMet = ExprValue;
2808 TheCondState.Ignore = !TheCondState.CondMet;
2814 /// ParseDirectiveElse
2816 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2817 if (getLexer().isNot(AsmToken::EndOfStatement))
2818 return TokError("unexpected token in '.else' directive");
2822 if (TheCondState.TheCond != AsmCond::IfCond &&
2823 TheCondState.TheCond != AsmCond::ElseIfCond)
2824 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2826 TheCondState.TheCond = AsmCond::ElseCond;
2827 bool LastIgnoreState = false;
2828 if (!TheCondStack.empty())
2829 LastIgnoreState = TheCondStack.back().Ignore;
2830 if (LastIgnoreState || TheCondState.CondMet)
2831 TheCondState.Ignore = true;
2833 TheCondState.Ignore = false;
2838 /// ParseDirectiveEndIf
2840 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2841 if (getLexer().isNot(AsmToken::EndOfStatement))
2842 return TokError("unexpected token in '.endif' directive");
2846 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2847 TheCondStack.empty())
2848 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2850 if (!TheCondStack.empty()) {
2851 TheCondState = TheCondStack.back();
2852 TheCondStack.pop_back();
2858 void AsmParser::initializeDirectiveKindMapping() {
2859 DirectiveKindMapping[".set"] = DK_SET;
2860 DirectiveKindMapping[".equ"] = DK_EQU;
2861 DirectiveKindMapping[".equiv"] = DK_EQUIV;
2862 DirectiveKindMapping[".ascii"] = DK_ASCII;
2863 DirectiveKindMapping[".asciz"] = DK_ASCIZ;
2864 DirectiveKindMapping[".string"] = DK_STRING;
2865 DirectiveKindMapping[".byte"] = DK_BYTE;
2866 DirectiveKindMapping[".short"] = DK_SHORT;
2867 DirectiveKindMapping[".value"] = DK_VALUE;
2868 DirectiveKindMapping[".2byte"] = DK_2BYTE;
2869 DirectiveKindMapping[".long"] = DK_LONG;
2870 DirectiveKindMapping[".int"] = DK_INT;
2871 DirectiveKindMapping[".4byte"] = DK_4BYTE;
2872 DirectiveKindMapping[".quad"] = DK_QUAD;
2873 DirectiveKindMapping[".8byte"] = DK_8BYTE;
2874 DirectiveKindMapping[".single"] = DK_SINGLE;
2875 DirectiveKindMapping[".float"] = DK_FLOAT;
2876 DirectiveKindMapping[".double"] = DK_DOUBLE;
2877 DirectiveKindMapping[".align"] = DK_ALIGN;
2878 DirectiveKindMapping[".align32"] = DK_ALIGN32;
2879 DirectiveKindMapping[".balign"] = DK_BALIGN;
2880 DirectiveKindMapping[".balignw"] = DK_BALIGNW;
2881 DirectiveKindMapping[".balignl"] = DK_BALIGNL;
2882 DirectiveKindMapping[".p2align"] = DK_P2ALIGN;
2883 DirectiveKindMapping[".p2alignw"] = DK_P2ALIGNW;
2884 DirectiveKindMapping[".p2alignl"] = DK_P2ALIGNL;
2885 DirectiveKindMapping[".org"] = DK_ORG;
2886 DirectiveKindMapping[".fill"] = DK_FILL;
2887 DirectiveKindMapping[".zero"] = DK_ZERO;
2888 DirectiveKindMapping[".extern"] = DK_EXTERN;
2889 DirectiveKindMapping[".globl"] = DK_GLOBL;
2890 DirectiveKindMapping[".global"] = DK_GLOBAL;
2891 DirectiveKindMapping[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
2892 DirectiveKindMapping[".lazy_reference"] = DK_LAZY_REFERENCE;
2893 DirectiveKindMapping[".no_dead_strip"] = DK_NO_DEAD_STRIP;
2894 DirectiveKindMapping[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
2895 DirectiveKindMapping[".private_extern"] = DK_PRIVATE_EXTERN;
2896 DirectiveKindMapping[".reference"] = DK_REFERENCE;
2897 DirectiveKindMapping[".weak_definition"] = DK_WEAK_DEFINITION;
2898 DirectiveKindMapping[".weak_reference"] = DK_WEAK_REFERENCE;
2899 DirectiveKindMapping[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
2900 DirectiveKindMapping[".comm"] = DK_COMM;
2901 DirectiveKindMapping[".common"] = DK_COMMON;
2902 DirectiveKindMapping[".lcomm"] = DK_LCOMM;
2903 DirectiveKindMapping[".abort"] = DK_ABORT;
2904 DirectiveKindMapping[".include"] = DK_INCLUDE;
2905 DirectiveKindMapping[".incbin"] = DK_INCBIN;
2906 DirectiveKindMapping[".code16"] = DK_CODE16;
2907 DirectiveKindMapping[".code16gcc"] = DK_CODE16GCC;
2908 DirectiveKindMapping[".rept"] = DK_REPT;
2909 DirectiveKindMapping[".irp"] = DK_IRP;
2910 DirectiveKindMapping[".irpc"] = DK_IRPC;
2911 DirectiveKindMapping[".endr"] = DK_ENDR;
2912 DirectiveKindMapping[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
2913 DirectiveKindMapping[".bundle_lock"] = DK_BUNDLE_LOCK;
2914 DirectiveKindMapping[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
2915 DirectiveKindMapping[".if"] = DK_IF;
2916 DirectiveKindMapping[".ifb"] = DK_IFB;
2917 DirectiveKindMapping[".ifnb"] = DK_IFNB;
2918 DirectiveKindMapping[".ifc"] = DK_IFC;
2919 DirectiveKindMapping[".ifnc"] = DK_IFNC;
2920 DirectiveKindMapping[".ifdef"] = DK_IFDEF;
2921 DirectiveKindMapping[".ifndef"] = DK_IFNDEF;
2922 DirectiveKindMapping[".ifnotdef"] = DK_IFNOTDEF;
2923 DirectiveKindMapping[".elseif"] = DK_ELSEIF;
2924 DirectiveKindMapping[".else"] = DK_ELSE;
2925 DirectiveKindMapping[".endif"] = DK_ENDIF;
2928 /// ParseDirectiveFile
2929 /// ::= .file [number] filename
2930 /// ::= .file number directory filename
2931 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2932 // FIXME: I'm not sure what this is.
2933 int64_t FileNumber = -1;
2934 SMLoc FileNumberLoc = getLexer().getLoc();
2935 if (getLexer().is(AsmToken::Integer)) {
2936 FileNumber = getTok().getIntVal();
2940 return TokError("file number less than one");
2943 if (getLexer().isNot(AsmToken::String))
2944 return TokError("unexpected token in '.file' directive");
2946 // Usually the directory and filename together, otherwise just the directory.
2947 StringRef Path = getTok().getString();
2948 Path = Path.substr(1, Path.size()-2);
2951 StringRef Directory;
2953 if (getLexer().is(AsmToken::String)) {
2954 if (FileNumber == -1)
2955 return TokError("explicit path specified, but no file number");
2956 Filename = getTok().getString();
2957 Filename = Filename.substr(1, Filename.size()-2);
2964 if (getLexer().isNot(AsmToken::EndOfStatement))
2965 return TokError("unexpected token in '.file' directive");
2967 if (FileNumber == -1)
2968 getStreamer().EmitFileDirective(Filename);
2970 if (getContext().getGenDwarfForAssembly() == true)
2971 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2972 "used to generate dwarf debug info for assembly code");
2974 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2975 Error(FileNumberLoc, "file number already allocated");
2981 /// ParseDirectiveLine
2982 /// ::= .line [number]
2983 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2984 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2985 if (getLexer().isNot(AsmToken::Integer))
2986 return TokError("unexpected token in '.line' directive");
2988 int64_t LineNumber = getTok().getIntVal();
2992 // FIXME: Do something with the .line.
2995 if (getLexer().isNot(AsmToken::EndOfStatement))
2996 return TokError("unexpected token in '.line' directive");
3002 /// ParseDirectiveLoc
3003 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3004 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3005 /// The first number is a file number, must have been previously assigned with
3006 /// a .file directive, the second number is the line number and optionally the
3007 /// third number is a column position (zero if not specified). The remaining
3008 /// optional items are .loc sub-directives.
3009 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
3011 if (getLexer().isNot(AsmToken::Integer))
3012 return TokError("unexpected token in '.loc' directive");
3013 int64_t FileNumber = getTok().getIntVal();
3015 return TokError("file number less than one in '.loc' directive");
3016 if (!getContext().isValidDwarfFileNumber(FileNumber))
3017 return TokError("unassigned file number in '.loc' directive");
3020 int64_t LineNumber = 0;
3021 if (getLexer().is(AsmToken::Integer)) {
3022 LineNumber = getTok().getIntVal();
3024 return TokError("line number less than one in '.loc' directive");
3028 int64_t ColumnPos = 0;
3029 if (getLexer().is(AsmToken::Integer)) {
3030 ColumnPos = getTok().getIntVal();
3032 return TokError("column position less than zero in '.loc' directive");
3036 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3038 int64_t Discriminator = 0;
3039 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3041 if (getLexer().is(AsmToken::EndOfStatement))
3045 SMLoc Loc = getTok().getLoc();
3046 if (getParser().ParseIdentifier(Name))
3047 return TokError("unexpected token in '.loc' directive");
3049 if (Name == "basic_block")
3050 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3051 else if (Name == "prologue_end")
3052 Flags |= DWARF2_FLAG_PROLOGUE_END;
3053 else if (Name == "epilogue_begin")
3054 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3055 else if (Name == "is_stmt") {
3056 Loc = getTok().getLoc();
3057 const MCExpr *Value;
3058 if (getParser().ParseExpression(Value))
3060 // The expression must be the constant 0 or 1.
3061 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3062 int Value = MCE->getValue();
3064 Flags &= ~DWARF2_FLAG_IS_STMT;
3065 else if (Value == 1)
3066 Flags |= DWARF2_FLAG_IS_STMT;
3068 return Error(Loc, "is_stmt value not 0 or 1");
3071 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3074 else if (Name == "isa") {
3075 Loc = getTok().getLoc();
3076 const MCExpr *Value;
3077 if (getParser().ParseExpression(Value))
3079 // The expression must be a constant greater or equal to 0.
3080 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3081 int Value = MCE->getValue();
3083 return Error(Loc, "isa number less than zero");
3087 return Error(Loc, "isa number not a constant value");
3090 else if (Name == "discriminator") {
3091 if (getParser().ParseAbsoluteExpression(Discriminator))
3095 return Error(Loc, "unknown sub-directive in '.loc' directive");
3098 if (getLexer().is(AsmToken::EndOfStatement))
3103 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3104 Isa, Discriminator, StringRef());
3109 /// ParseDirectiveStabs
3110 /// ::= .stabs string, number, number, number
3111 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
3112 SMLoc DirectiveLoc) {
3113 return TokError("unsupported directive '" + Directive + "'");
3116 /// ParseDirectiveSpace
3117 /// ::= .space expression [ , expression ]
3118 bool GenericAsmParser::ParseDirectiveSpace(StringRef, SMLoc DirectiveLoc) {
3119 getParser().CheckForValidSection();
3122 if (getParser().ParseAbsoluteExpression(NumBytes))
3125 int64_t FillExpr = 0;
3126 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3127 if (getLexer().isNot(AsmToken::Comma))
3128 return TokError("unexpected token in '.space' directive");
3131 if (getParser().ParseAbsoluteExpression(FillExpr))
3134 if (getLexer().isNot(AsmToken::EndOfStatement))
3135 return TokError("unexpected token in '.space' directive");
3141 return TokError("invalid number of bytes in '.space' directive");
3143 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3144 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3149 /// ParseDirectiveCFISections
3150 /// ::= .cfi_sections section [, section]
3151 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
3152 SMLoc DirectiveLoc) {
3157 if (getParser().ParseIdentifier(Name))
3158 return TokError("Expected an identifier");
3160 if (Name == ".eh_frame")
3162 else if (Name == ".debug_frame")
3165 if (getLexer().is(AsmToken::Comma)) {
3168 if (getParser().ParseIdentifier(Name))
3169 return TokError("Expected an identifier");
3171 if (Name == ".eh_frame")
3173 else if (Name == ".debug_frame")
3177 getStreamer().EmitCFISections(EH, Debug);
3182 /// ParseDirectiveCFIStartProc
3183 /// ::= .cfi_startproc
3184 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
3185 SMLoc DirectiveLoc) {
3186 getStreamer().EmitCFIStartProc();
3190 /// ParseDirectiveCFIEndProc
3191 /// ::= .cfi_endproc
3192 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
3193 getStreamer().EmitCFIEndProc();
3197 /// ParseRegisterOrRegisterNumber - parse register name or number.
3198 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3199 SMLoc DirectiveLoc) {
3202 if (getLexer().isNot(AsmToken::Integer)) {
3203 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3206 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
3208 return getParser().ParseAbsoluteExpression(Register);
3213 /// ParseDirectiveCFIDefCfa
3214 /// ::= .cfi_def_cfa register, offset
3215 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3216 SMLoc DirectiveLoc) {
3217 int64_t Register = 0;
3218 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3221 if (getLexer().isNot(AsmToken::Comma))
3222 return TokError("unexpected token in directive");
3226 if (getParser().ParseAbsoluteExpression(Offset))
3229 getStreamer().EmitCFIDefCfa(Register, Offset);
3233 /// ParseDirectiveCFIDefCfaOffset
3234 /// ::= .cfi_def_cfa_offset offset
3235 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3236 SMLoc DirectiveLoc) {
3238 if (getParser().ParseAbsoluteExpression(Offset))
3241 getStreamer().EmitCFIDefCfaOffset(Offset);
3245 /// ParseDirectiveCFIAdjustCfaOffset
3246 /// ::= .cfi_adjust_cfa_offset adjustment
3247 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3248 SMLoc DirectiveLoc) {
3249 int64_t Adjustment = 0;
3250 if (getParser().ParseAbsoluteExpression(Adjustment))
3253 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3257 /// ParseDirectiveCFIDefCfaRegister
3258 /// ::= .cfi_def_cfa_register register
3259 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3260 SMLoc DirectiveLoc) {
3261 int64_t Register = 0;
3262 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3265 getStreamer().EmitCFIDefCfaRegister(Register);
3269 /// ParseDirectiveCFIOffset
3270 /// ::= .cfi_offset register, offset
3271 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3272 int64_t Register = 0;
3275 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3278 if (getLexer().isNot(AsmToken::Comma))
3279 return TokError("unexpected token in directive");
3282 if (getParser().ParseAbsoluteExpression(Offset))
3285 getStreamer().EmitCFIOffset(Register, Offset);
3289 /// ParseDirectiveCFIRelOffset
3290 /// ::= .cfi_rel_offset register, offset
3291 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3292 SMLoc DirectiveLoc) {
3293 int64_t Register = 0;
3295 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3298 if (getLexer().isNot(AsmToken::Comma))
3299 return TokError("unexpected token in directive");
3303 if (getParser().ParseAbsoluteExpression(Offset))
3306 getStreamer().EmitCFIRelOffset(Register, Offset);
3310 static bool isValidEncoding(int64_t Encoding) {
3311 if (Encoding & ~0xff)
3314 if (Encoding == dwarf::DW_EH_PE_omit)
3317 const unsigned Format = Encoding & 0xf;
3318 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3319 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3320 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3321 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3324 const unsigned Application = Encoding & 0x70;
3325 if (Application != dwarf::DW_EH_PE_absptr &&
3326 Application != dwarf::DW_EH_PE_pcrel)
3332 /// ParseDirectiveCFIPersonalityOrLsda
3333 /// ::= .cfi_personality encoding, [symbol_name]
3334 /// ::= .cfi_lsda encoding, [symbol_name]
3335 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
3336 SMLoc DirectiveLoc) {
3337 int64_t Encoding = 0;
3338 if (getParser().ParseAbsoluteExpression(Encoding))
3340 if (Encoding == dwarf::DW_EH_PE_omit)
3343 if (!isValidEncoding(Encoding))
3344 return TokError("unsupported encoding.");
3346 if (getLexer().isNot(AsmToken::Comma))
3347 return TokError("unexpected token in directive");
3351 if (getParser().ParseIdentifier(Name))
3352 return TokError("expected identifier in directive");
3354 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3356 if (IDVal == ".cfi_personality")
3357 getStreamer().EmitCFIPersonality(Sym, Encoding);
3359 assert(IDVal == ".cfi_lsda");
3360 getStreamer().EmitCFILsda(Sym, Encoding);
3365 /// ParseDirectiveCFIRememberState
3366 /// ::= .cfi_remember_state
3367 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3368 SMLoc DirectiveLoc) {
3369 getStreamer().EmitCFIRememberState();
3373 /// ParseDirectiveCFIRestoreState
3374 /// ::= .cfi_remember_state
3375 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3376 SMLoc DirectiveLoc) {
3377 getStreamer().EmitCFIRestoreState();
3381 /// ParseDirectiveCFISameValue
3382 /// ::= .cfi_same_value register
3383 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3384 SMLoc DirectiveLoc) {
3385 int64_t Register = 0;
3387 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3390 getStreamer().EmitCFISameValue(Register);
3395 /// ParseDirectiveCFIRestore
3396 /// ::= .cfi_restore register
3397 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
3398 SMLoc DirectiveLoc) {
3399 int64_t Register = 0;
3400 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3403 getStreamer().EmitCFIRestore(Register);
3408 /// ParseDirectiveCFIEscape
3409 /// ::= .cfi_escape expression[,...]
3410 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3411 SMLoc DirectiveLoc) {
3414 if (getParser().ParseAbsoluteExpression(CurrValue))
3417 Values.push_back((uint8_t)CurrValue);
3419 while (getLexer().is(AsmToken::Comma)) {
3422 if (getParser().ParseAbsoluteExpression(CurrValue))
3425 Values.push_back((uint8_t)CurrValue);
3428 getStreamer().EmitCFIEscape(Values);
3432 /// ParseDirectiveCFISignalFrame
3433 /// ::= .cfi_signal_frame
3434 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3435 SMLoc DirectiveLoc) {
3436 if (getLexer().isNot(AsmToken::EndOfStatement))
3437 return Error(getLexer().getLoc(),
3438 "unexpected token in '" + Directive + "' directive");
3440 getStreamer().EmitCFISignalFrame();
3445 /// ParseDirectiveCFIUndefined
3446 /// ::= .cfi_undefined register
3447 bool GenericAsmParser::ParseDirectiveCFIUndefined(StringRef Directive,
3448 SMLoc DirectiveLoc) {
3449 int64_t Register = 0;
3451 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3454 getStreamer().EmitCFIUndefined(Register);
3459 /// ParseDirectiveCFIRegister
3460 /// ::= .cfi_register register, register
3461 bool GenericAsmParser::ParseDirectiveCFIRegister(StringRef Directive,
3462 SMLoc DirectiveLoc) {
3463 int64_t Register1 = 0;
3465 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3468 if (getLexer().isNot(AsmToken::Comma))
3469 return TokError("unexpected token in directive");
3472 int64_t Register2 = 0;
3474 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3477 getStreamer().EmitCFIRegister(Register1, Register2);
3482 /// ParseDirectiveMacrosOnOff
3485 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3486 SMLoc DirectiveLoc) {
3487 if (getLexer().isNot(AsmToken::EndOfStatement))
3488 return Error(getLexer().getLoc(),
3489 "unexpected token in '" + Directive + "' directive");
3491 getParser().SetMacrosEnabled(Directive == ".macros_on");
3496 /// ParseDirectiveMacro
3497 /// ::= .macro name [parameters]
3498 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3499 SMLoc DirectiveLoc) {
3501 if (getParser().ParseIdentifier(Name))
3502 return TokError("expected identifier in '.macro' directive");
3504 MacroParameters Parameters;
3505 // Argument delimiter is initially unknown. It will be set by
3506 // ParseMacroArgument()
3507 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3508 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3510 MacroParameter Parameter;
3511 if (getParser().ParseIdentifier(Parameter.first))
3512 return TokError("expected identifier in '.macro' directive");
3514 if (getLexer().is(AsmToken::Equal)) {
3516 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3520 Parameters.push_back(Parameter);
3522 if (getLexer().is(AsmToken::Comma))
3524 else if (getLexer().is(AsmToken::EndOfStatement))
3529 // Eat the end of statement.
3532 AsmToken EndToken, StartToken = getTok();
3534 // Lex the macro definition.
3536 // Check whether we have reached the end of the file.
3537 if (getLexer().is(AsmToken::Eof))
3538 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3540 // Otherwise, check whether we have reach the .endmacro.
3541 if (getLexer().is(AsmToken::Identifier) &&
3542 (getTok().getIdentifier() == ".endm" ||
3543 getTok().getIdentifier() == ".endmacro")) {
3544 EndToken = getTok();
3546 if (getLexer().isNot(AsmToken::EndOfStatement))
3547 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3552 // Otherwise, scan til the end of the statement.
3553 getParser().EatToEndOfStatement();
3556 if (getParser().MacroMap.lookup(Name)) {
3557 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3560 const char *BodyStart = StartToken.getLoc().getPointer();
3561 const char *BodyEnd = EndToken.getLoc().getPointer();
3562 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3563 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3567 /// ParseDirectiveEndMacro
3570 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3571 SMLoc DirectiveLoc) {
3572 if (getLexer().isNot(AsmToken::EndOfStatement))
3573 return TokError("unexpected token in '" + Directive + "' directive");
3575 // If we are inside a macro instantiation, terminate the current
3577 if (!getParser().ActiveMacros.empty()) {
3578 getParser().HandleMacroExit();
3582 // Otherwise, this .endmacro is a stray entry in the file; well formed
3583 // .endmacro directives are handled during the macro definition parsing.
3584 return TokError("unexpected '" + Directive + "' in file, "
3585 "no current macro definition");
3588 /// ParseDirectivePurgeMacro
3590 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3591 SMLoc DirectiveLoc) {
3593 if (getParser().ParseIdentifier(Name))
3594 return TokError("expected identifier in '.purgem' directive");
3596 if (getLexer().isNot(AsmToken::EndOfStatement))
3597 return TokError("unexpected token in '.purgem' directive");
3599 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3600 if (I == getParser().MacroMap.end())
3601 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3603 // Undefine the macro.
3604 delete I->getValue();
3605 getParser().MacroMap.erase(I);
3609 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3610 getParser().CheckForValidSection();
3612 const MCExpr *Value;
3614 if (getParser().ParseExpression(Value))
3617 if (getLexer().isNot(AsmToken::EndOfStatement))
3618 return TokError("unexpected token in directive");
3620 if (DirName[1] == 's')
3621 getStreamer().EmitSLEB128Value(Value);
3623 getStreamer().EmitULEB128Value(Value);
3628 Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3629 AsmToken EndToken, StartToken = getTok();
3631 unsigned NestLevel = 0;
3633 // Check whether we have reached the end of the file.
3634 if (getLexer().is(AsmToken::Eof)) {
3635 Error(DirectiveLoc, "no matching '.endr' in definition");
3639 if (Lexer.is(AsmToken::Identifier) &&
3640 (getTok().getIdentifier() == ".rept")) {
3644 // Otherwise, check whether we have reached the .endr.
3645 if (Lexer.is(AsmToken::Identifier) &&
3646 getTok().getIdentifier() == ".endr") {
3647 if (NestLevel == 0) {
3648 EndToken = getTok();
3650 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3651 TokError("unexpected token in '.endr' directive");
3659 // Otherwise, scan till the end of the statement.
3660 EatToEndOfStatement();
3663 const char *BodyStart = StartToken.getLoc().getPointer();
3664 const char *BodyEnd = EndToken.getLoc().getPointer();
3665 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3667 // We Are Anonymous.
3669 MacroParameters Parameters;
3670 return new Macro(Name, Body, Parameters);
3673 void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3674 raw_svector_ostream &OS) {
3677 MemoryBuffer *Instantiation =
3678 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3680 // Create the macro instantiation object and add to the current macro
3681 // instantiation stack.
3682 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3686 ActiveMacros.push_back(MI);
3688 // Jump to the macro instantiation and prime the lexer.
3689 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3690 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3694 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3696 if (ParseAbsoluteExpression(Count))
3697 return TokError("unexpected token in '.rept' directive");
3700 return TokError("Count is negative");
3702 if (Lexer.isNot(AsmToken::EndOfStatement))
3703 return TokError("unexpected token in '.rept' directive");
3705 // Eat the end of statement.
3708 // Lex the rept definition.
3709 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3713 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3714 // to hold the macro body with substitutions.
3715 SmallString<256> Buf;
3716 MacroParameters Parameters;
3718 raw_svector_ostream OS(Buf);
3720 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3723 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3728 /// ParseDirectiveIrp
3729 /// ::= .irp symbol,values
3730 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3731 MacroParameters Parameters;
3732 MacroParameter Parameter;
3734 if (ParseIdentifier(Parameter.first))
3735 return TokError("expected identifier in '.irp' directive");
3737 Parameters.push_back(Parameter);
3739 if (Lexer.isNot(AsmToken::Comma))
3740 return TokError("expected comma in '.irp' directive");
3745 if (ParseMacroArguments(0, A))
3748 // Eat the end of statement.
3751 // Lex the irp definition.
3752 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3756 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3757 // to hold the macro body with substitutions.
3758 SmallString<256> Buf;
3759 raw_svector_ostream OS(Buf);
3761 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3762 MacroArguments Args;
3765 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3769 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3774 /// ParseDirectiveIrpc
3775 /// ::= .irpc symbol,values
3776 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3777 MacroParameters Parameters;
3778 MacroParameter Parameter;
3780 if (ParseIdentifier(Parameter.first))
3781 return TokError("expected identifier in '.irpc' directive");
3783 Parameters.push_back(Parameter);
3785 if (Lexer.isNot(AsmToken::Comma))
3786 return TokError("expected comma in '.irpc' directive");
3791 if (ParseMacroArguments(0, A))
3794 if (A.size() != 1 || A.front().size() != 1)
3795 return TokError("unexpected token in '.irpc' directive");
3797 // Eat the end of statement.
3800 // Lex the irpc definition.
3801 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3805 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3806 // to hold the macro body with substitutions.
3807 SmallString<256> Buf;
3808 raw_svector_ostream OS(Buf);
3810 StringRef Values = A.front().front().getString();
3811 std::size_t I, End = Values.size();
3812 for (I = 0; I < End; ++I) {
3813 MCAsmMacroArgument Arg;
3814 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3816 MacroArguments Args;
3817 Args.push_back(Arg);
3819 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3823 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3828 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3829 if (ActiveMacros.empty())
3830 return TokError("unmatched '.endr' directive");
3832 // The only .repl that should get here are the ones created by
3833 // InstantiateMacroLikeBody.
3834 assert(getLexer().is(AsmToken::EndOfStatement));
3840 bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3841 const MCExpr *Value;
3842 SMLoc ExprLoc = getLexer().getLoc();
3843 if (ParseExpression(Value))
3845 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3847 return Error(ExprLoc, "unexpected expression in _emit");
3848 uint64_t IntValue = MCE->getValue();
3849 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3850 return Error(ExprLoc, "literal value out of range for directive");
3852 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3856 bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3857 unsigned &NumOutputs, unsigned &NumInputs,
3858 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
3859 SmallVectorImpl<std::string> &Constraints,
3860 SmallVectorImpl<std::string> &Clobbers,
3861 const MCInstrInfo *MII,
3862 const MCInstPrinter *IP,
3863 MCAsmParserSemaCallback &SI) {
3864 SmallVector<void *, 4> InputDecls;
3865 SmallVector<void *, 4> OutputDecls;
3866 SmallVector<bool, 4> InputDeclsAddressOf;
3867 SmallVector<bool, 4> OutputDeclsAddressOf;
3868 SmallVector<std::string, 4> InputConstraints;
3869 SmallVector<std::string, 4> OutputConstraints;
3870 std::set<std::string> ClobberRegs;
3872 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
3877 // While we have input, parse each statement.
3878 unsigned InputIdx = 0;
3879 unsigned OutputIdx = 0;
3880 while (getLexer().isNot(AsmToken::Eof)) {
3881 ParseStatementInfo Info(&AsmStrRewrites);
3882 if (ParseStatement(Info))
3885 if (Info.ParseError)
3888 if (Info.Opcode != ~0U) {
3889 const MCInstrDesc &Desc = MII->get(Info.Opcode);
3891 // Build the list of clobbers, outputs and inputs.
3892 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3893 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
3896 if (Operand->isImm()) {
3897 if (Operand->needAsmRewrite())
3898 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3899 Operand->getStartLoc()));
3903 // Register operand.
3904 if (Operand->isReg() && !Operand->needAddressOf()) {
3905 unsigned NumDefs = Desc.getNumDefs();
3907 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3909 raw_string_ostream OS(Reg);
3910 IP->printRegName(OS, Operand->getReg());
3911 ClobberRegs.insert(StringRef(OS.str()));
3916 // Expr/Input or Output.
3919 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3922 bool isOutput = (i == 1) && Desc.mayStore();
3923 if (Operand->isMem() && Operand->needSizeDirective())
3924 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
3925 Operand->getStartLoc(),
3927 Operand->getMemSize()));
3929 std::string Constraint = "=";
3931 OutputDecls.push_back(OpDecl);
3932 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
3933 Constraint += Operand->getConstraint().str();
3934 OutputConstraints.push_back(Constraint);
3935 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
3936 Operand->getStartLoc(),
3937 Operand->getNameLen()));
3939 InputDecls.push_back(OpDecl);
3940 InputDeclsAddressOf.push_back(Operand->needAddressOf());
3941 InputConstraints.push_back(Operand->getConstraint().str());
3942 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
3943 Operand->getStartLoc(),
3944 Operand->getNameLen()));
3951 // Set the number of Outputs and Inputs.
3952 NumOutputs = OutputDecls.size();
3953 NumInputs = InputDecls.size();
3955 // Set the unique clobbers.
3956 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3957 E = ClobberRegs.end(); I != E; ++I)
3958 Clobbers.push_back(*I);
3960 // Merge the various outputs and inputs. Output are expected first.
3961 if (NumOutputs || NumInputs) {
3962 unsigned NumExprs = NumOutputs + NumInputs;
3963 OpDecls.resize(NumExprs);
3964 Constraints.resize(NumExprs);
3965 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3966 // constraint for addressof. This needs to be cleaned up!
3967 for (unsigned i = 0; i < NumOutputs; ++i) {
3968 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
3969 Constraints[i] = OutputDeclsAddressOf[i] ? "=r" : OutputConstraints[i];
3971 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
3972 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
3973 Constraints[j] = InputDeclsAddressOf[i] ? "r" : InputConstraints[i];
3977 // Build the IR assembly string.
3978 std::string AsmStringIR;
3979 AsmRewriteKind PrevKind = AOK_Imm;
3980 raw_string_ostream OS(AsmStringIR);
3981 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
3982 for (SmallVectorImpl<struct AsmRewrite>::iterator
3983 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3984 const char *Loc = (*I).Loc.getPointer();
3986 AsmRewriteKind Kind = (*I).Kind;
3988 // Emit everything up to the immediate/expression. If the previous rewrite
3989 // was a size directive, then this has already been done.
3990 if (PrevKind != AOK_SizeDirective)
3991 OS << StringRef(Start, Loc - Start);
3994 // Skip the original expression.
3995 if (Kind == AOK_Skip) {
3996 Start = Loc + (*I).Len;
4000 // Rewrite expressions in $N notation.
4018 case AOK_SizeDirective:
4021 case 8: OS << "byte ptr "; break;
4022 case 16: OS << "word ptr "; break;
4023 case 32: OS << "dword ptr "; break;
4024 case 64: OS << "qword ptr "; break;
4025 case 80: OS << "xword ptr "; break;
4026 case 128: OS << "xmmword ptr "; break;
4027 case 256: OS << "ymmword ptr "; break;
4033 case AOK_DotOperator:
4038 // Skip the original expression.
4039 if (Kind != AOK_SizeDirective)
4040 Start = Loc + (*I).Len;
4043 // Emit the remainder of the asm string.
4044 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4045 if (Start != AsmEnd)
4046 OS << StringRef(Start, AsmEnd - Start);
4048 AsmString = OS.str();
4052 /// \brief Create an MCAsmParser instance.
4053 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
4054 MCContext &C, MCStreamer &Out,
4055 const MCAsmInfo &MAI) {
4056 return new AsmParser(SM, C, Out, MAI);