1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCDwarf.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInstPrinter.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCParser/AsmCond.h"
25 #include "llvm/MC/MCParser/AsmLexer.h"
26 #include "llvm/MC/MCParser/MCAsmParser.h"
27 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSectionMachO.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/MC/MCTargetAsmParser.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/raw_ostream.h"
46 FatalAssemblerWarnings("fatal-assembler-warnings",
47 cl::desc("Consider warnings as error"));
49 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
53 /// \brief Helper class for tracking macro definitions.
54 typedef std::vector<AsmToken> MacroArgument;
55 typedef std::vector<MacroArgument> MacroArguments;
56 typedef std::pair<StringRef, MacroArgument> MacroParameter;
57 typedef std::vector<MacroParameter> MacroParameters;
62 MacroParameters Parameters;
65 Macro(StringRef N, StringRef B, const MacroParameters &P) :
66 Name(N), Body(B), Parameters(P) {}
69 /// \brief Helper class for storing information about an active macro
71 struct MacroInstantiation {
72 /// The macro being instantiated.
73 const Macro *TheMacro;
75 /// The macro instantiation with substitutions.
76 MemoryBuffer *Instantiation;
78 /// The location of the instantiation.
79 SMLoc InstantiationLoc;
81 /// The buffer where parsing should resume upon instantiation completion.
84 /// The location where parsing should resume upon instantiation completion.
88 MacroInstantiation(const Macro *M, SMLoc IL, int EB, SMLoc EL,
93 struct ParseStatementInfo {
94 /// ParsedOperands - The parsed operands from the last parsed statement.
95 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
97 /// Opcode - The opcode from the last parsed instruction.
100 /// Error - Was there an error parsing the inline assembly?
103 SmallVectorImpl<AsmRewrite> *AsmRewrites;
105 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
106 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
107 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
109 ~ParseStatementInfo() {
110 // Free any parsed operands.
111 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
112 delete ParsedOperands[i];
113 ParsedOperands.clear();
117 /// \brief The concrete assembly parser instance.
118 class AsmParser : public MCAsmParser {
119 friend class GenericAsmParser;
121 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
122 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
127 const MCAsmInfo &MAI;
129 SourceMgr::DiagHandlerTy SavedDiagHandler;
130 void *SavedDiagContext;
131 MCAsmParserExtension *GenericParser;
132 MCAsmParserExtension *PlatformParser;
134 /// This is the current buffer index we're lexing from as managed by the
135 /// SourceMgr object.
138 AsmCond TheCondState;
139 std::vector<AsmCond> TheCondStack;
141 /// DirectiveMap - This is a table handlers for directives. Each handler is
142 /// invoked after the directive identifier is read and is responsible for
143 /// parsing and validating the rest of the directive. The handler is passed
144 /// in the directive name and the location of the directive keyword.
145 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
147 /// MacroMap - Map of currently defined macros.
148 StringMap<Macro*> MacroMap;
150 /// ActiveMacros - Stack of active macro instantiations.
151 std::vector<MacroInstantiation*> ActiveMacros;
153 /// Boolean tracking whether macro substitution is enabled.
154 unsigned MacrosEnabled : 1;
156 /// Flag tracking whether any errors have been encountered.
157 unsigned HadError : 1;
159 /// The values from the last parsed cpp hash file line comment if any.
160 StringRef CppHashFilename;
161 int64_t CppHashLineNumber;
165 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
166 unsigned AssemblerDialect;
168 /// IsDarwin - is Darwin compatibility enabled?
171 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
172 bool ParsingInlineAsm;
175 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
176 const MCAsmInfo &MAI);
177 virtual ~AsmParser();
179 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
181 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
183 DirectiveHandler Handler) {
184 DirectiveMap[Directive] = std::make_pair(Object, Handler);
188 /// @name MCAsmParser Interface
191 virtual SourceMgr &getSourceManager() { return SrcMgr; }
192 virtual MCAsmLexer &getLexer() { return Lexer; }
193 virtual MCContext &getContext() { return Ctx; }
194 virtual MCStreamer &getStreamer() { return Out; }
195 virtual unsigned getAssemblerDialect() {
196 if (AssemblerDialect == ~0U)
197 return MAI.getAssemblerDialect();
199 return AssemblerDialect;
201 virtual void setAssemblerDialect(unsigned i) {
202 AssemblerDialect = i;
205 virtual bool Warning(SMLoc L, const Twine &Msg,
206 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
207 virtual bool Error(SMLoc L, const Twine &Msg,
208 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
210 virtual const AsmToken &Lex();
212 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
213 bool isParsingInlineAsm() { return ParsingInlineAsm; }
215 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
216 unsigned &NumOutputs, unsigned &NumInputs,
217 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
218 SmallVectorImpl<std::string> &Constraints,
219 SmallVectorImpl<std::string> &Clobbers,
220 const MCInstrInfo *MII,
221 const MCInstPrinter *IP,
222 MCAsmParserSemaCallback &SI);
224 bool ParseExpression(const MCExpr *&Res);
225 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
226 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
227 virtual bool ParseAbsoluteExpression(int64_t &Res);
232 void CheckForValidSection();
234 bool ParseStatement(ParseStatementInfo &Info);
235 void EatToEndOfLine();
236 bool ParseCppHashLineFilenameComment(const SMLoc &L);
238 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
239 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
240 const MacroParameters &Parameters,
241 const MacroArguments &A,
243 void HandleMacroExit();
245 void PrintMacroInstantiations();
246 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
247 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
248 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
250 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
252 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
253 bool EnterIncludeFile(const std::string &Filename);
254 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
255 /// This returns true on failure.
256 bool ProcessIncbinFile(const std::string &Filename);
258 /// \brief Reset the current lexer position to that given by \p Loc. The
259 /// current token is not set; clients should ensure Lex() is called
262 /// \param InBuffer If not -1, should be the known buffer id that contains the
264 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
266 virtual void EatToEndOfStatement();
268 bool ParseMacroArgument(MacroArgument &MA,
269 AsmToken::TokenKind &ArgumentDelimiter);
270 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
272 /// \brief Parse up to the end of statement and a return the contents from the
273 /// current token until the end of the statement; the current token on exit
274 /// will be either the EndOfStatement or EOF.
275 virtual StringRef ParseStringToEndOfStatement();
277 /// \brief Parse until the end of a statement or a comma is encountered,
278 /// return the contents from the current token up to the end or comma.
279 StringRef ParseStringToComma();
281 bool ParseAssignment(StringRef Name, bool allow_redef,
282 bool NoDeadStrip = false);
284 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
285 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
286 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
287 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
289 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
290 /// and set \p Res to the identifier contents.
291 virtual bool ParseIdentifier(StringRef &Res);
293 // Directive Parsing.
296 DK_NO_DIRECTIVE, // Placeholder
297 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
298 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
299 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
300 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
301 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
302 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
303 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
304 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
305 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
306 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
307 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
308 DK_ELSEIF, DK_ELSE, DK_ENDIF
311 StringMap<DirectiveKind> DirectiveKindMapping;
313 // ".ascii", ".asciz", ".string"
314 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
315 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
316 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
317 bool ParseDirectiveFill(); // ".fill"
318 bool ParseDirectiveZero(); // ".zero"
319 // ".set", ".equ", ".equiv"
320 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
321 bool ParseDirectiveOrg(); // ".org"
322 // ".align{,32}", ".p2align{,w,l}"
323 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
325 // ".bundle_align_mode"
326 bool ParseDirectiveBundleAlignMode();
328 bool ParseDirectiveBundleLock();
330 bool ParseDirectiveBundleUnlock();
332 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
333 /// accepts a single symbol (which should be a label or an external).
334 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
336 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
338 bool ParseDirectiveAbort(); // ".abort"
339 bool ParseDirectiveInclude(); // ".include"
340 bool ParseDirectiveIncbin(); // ".incbin"
342 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
343 // ".ifb" or ".ifnb", depending on ExpectBlank.
344 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
345 // ".ifc" or ".ifnc", depending on ExpectEqual.
346 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
347 // ".ifdef" or ".ifndef", depending on expect_defined
348 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
349 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
350 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
351 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
353 /// ParseEscapedString - Parse the current token as a string which may include
354 /// escaped characters and return the string contents.
355 bool ParseEscapedString(std::string &Data);
357 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
358 MCSymbolRefExpr::VariantKind Variant);
360 // Macro-like directives
361 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
362 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
363 raw_svector_ostream &OS);
364 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
365 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
366 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
367 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
370 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
372 void initializeDirectiveKindMapping();
375 /// \brief Generic implementation of directive handling, etc. which is shared
376 /// (or the default, at least) for all assembler parsers.
377 class GenericAsmParser : public MCAsmParserExtension {
378 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
379 void AddDirectiveHandler(StringRef Directive) {
380 getParser().AddDirectiveHandler(this, Directive,
381 HandleDirective<GenericAsmParser, Handler>);
384 GenericAsmParser() {}
386 AsmParser &getParser() {
387 return (AsmParser&) this->MCAsmParserExtension::getParser();
390 virtual void Initialize(MCAsmParser &Parser) {
391 // Call the base implementation.
392 this->MCAsmParserExtension::Initialize(Parser);
394 // Debugging directives.
395 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
396 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
397 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
398 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
400 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveSpace>(".space");
401 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveSpace>(".skip");
404 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
406 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
408 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
410 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
412 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
413 ".cfi_def_cfa_offset");
414 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
415 ".cfi_adjust_cfa_offset");
416 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
417 ".cfi_def_cfa_register");
418 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
420 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
423 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
425 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
427 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
429 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
431 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
433 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
435 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
437 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
439 &GenericAsmParser::ParseDirectiveCFIUndefined>(".cfi_undefined");
441 &GenericAsmParser::ParseDirectiveCFIRegister>(".cfi_register");
444 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
446 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
448 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
449 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
450 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
451 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
453 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
454 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
457 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
459 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
460 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
461 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
462 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
463 bool ParseDirectiveSpace(StringRef, SMLoc DirectiveLoc);
464 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
465 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
466 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
467 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
468 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
469 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
470 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
471 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
472 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
473 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
474 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
475 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
476 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
477 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
478 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
479 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
480 bool ParseDirectiveCFIUndefined(StringRef, SMLoc DirectiveLoc);
481 bool ParseDirectiveCFIRegister(StringRef, SMLoc DirectiveLoc);
483 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
484 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
485 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
486 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
488 bool ParseDirectiveLEB128(StringRef, SMLoc);
495 extern MCAsmParserExtension *createDarwinAsmParser();
496 extern MCAsmParserExtension *createELFAsmParser();
497 extern MCAsmParserExtension *createCOFFAsmParser();
501 enum { DEFAULT_ADDRSPACE = 0 };
503 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
504 MCStreamer &_Out, const MCAsmInfo &_MAI)
505 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
506 GenericParser(new GenericAsmParser), PlatformParser(0),
507 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
508 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
509 // Save the old handler.
510 SavedDiagHandler = SrcMgr.getDiagHandler();
511 SavedDiagContext = SrcMgr.getDiagContext();
512 // Set our own handler which calls the saved handler.
513 SrcMgr.setDiagHandler(DiagHandler, this);
514 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
516 // Initialize the generic parser.
517 GenericParser->Initialize(*this);
519 // Initialize the platform / file format parser.
521 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
523 if (_MAI.hasMicrosoftFastStdCallMangling()) {
524 PlatformParser = createCOFFAsmParser();
525 PlatformParser->Initialize(*this);
526 } else if (_MAI.hasSubsectionsViaSymbols()) {
527 PlatformParser = createDarwinAsmParser();
528 PlatformParser->Initialize(*this);
531 PlatformParser = createELFAsmParser();
532 PlatformParser->Initialize(*this);
535 initializeDirectiveKindMapping();
538 AsmParser::~AsmParser() {
539 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
541 // Destroy any macros.
542 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
543 ie = MacroMap.end(); it != ie; ++it)
544 delete it->getValue();
546 delete PlatformParser;
547 delete GenericParser;
550 void AsmParser::PrintMacroInstantiations() {
551 // Print the active macro instantiation stack.
552 for (std::vector<MacroInstantiation*>::const_reverse_iterator
553 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
554 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
555 "while in macro instantiation");
558 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
559 if (FatalAssemblerWarnings)
560 return Error(L, Msg, Ranges);
561 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
562 PrintMacroInstantiations();
566 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
568 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
569 PrintMacroInstantiations();
573 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
574 std::string IncludedFile;
575 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
581 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
586 /// Process the specified .incbin file by seaching for it in the include paths
587 /// then just emitting the byte contents of the file to the streamer. This
588 /// returns true on failure.
589 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
590 std::string IncludedFile;
591 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
595 // Pick up the bytes from the file and emit them.
596 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
601 void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
602 if (InBuffer != -1) {
603 CurBuffer = InBuffer;
605 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
607 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
610 const AsmToken &AsmParser::Lex() {
611 const AsmToken *tok = &Lexer.Lex();
613 if (tok->is(AsmToken::Eof)) {
614 // If this is the end of an included file, pop the parent file off the
616 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
617 if (ParentIncludeLoc != SMLoc()) {
618 JumpToLoc(ParentIncludeLoc);
623 if (tok->is(AsmToken::Error))
624 Error(Lexer.getErrLoc(), Lexer.getErr());
629 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
630 // Create the initial section, if requested.
631 if (!NoInitialTextSection)
638 AsmCond StartingCondState = TheCondState;
640 // If we are generating dwarf for assembly source files save the initial text
641 // section and generate a .file directive.
642 if (getContext().getGenDwarfForAssembly()) {
643 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
644 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
645 getStreamer().EmitLabel(SectionStartSym);
646 getContext().setGenDwarfSectionStartSym(SectionStartSym);
647 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
649 getContext().getMainFileName());
652 // While we have input, parse each statement.
653 while (Lexer.isNot(AsmToken::Eof)) {
654 ParseStatementInfo Info;
655 if (!ParseStatement(Info)) continue;
657 // We had an error, validate that one was emitted and recover by skipping to
659 assert(HadError && "Parse statement returned an error, but none emitted!");
660 EatToEndOfStatement();
663 if (TheCondState.TheCond != StartingCondState.TheCond ||
664 TheCondState.Ignore != StartingCondState.Ignore)
665 return TokError("unmatched .ifs or .elses");
667 // Check to see there are no empty DwarfFile slots.
668 const std::vector<MCDwarfFile *> &MCDwarfFiles =
669 getContext().getMCDwarfFiles();
670 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
671 if (!MCDwarfFiles[i])
672 TokError("unassigned file number: " + Twine(i) + " for .file directives");
675 // Check to see that all assembler local symbols were actually defined.
676 // Targets that don't do subsections via symbols may not want this, though,
677 // so conservatively exclude them. Only do this if we're finalizing, though,
678 // as otherwise we won't necessarilly have seen everything yet.
679 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
680 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
681 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
684 MCSymbol *Sym = i->getValue();
685 // Variable symbols may not be marked as defined, so check those
686 // explicitly. If we know it's a variable, we have a definition for
687 // the purposes of this check.
688 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
689 // FIXME: We would really like to refer back to where the symbol was
690 // first referenced for a source location. We need to add something
691 // to track that. Currently, we just point to the end of the file.
692 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
693 "assembler local symbol '" + Sym->getName() +
699 // Finalize the output stream if there are no errors and if the client wants
701 if (!HadError && !NoFinalize)
707 void AsmParser::CheckForValidSection() {
708 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
709 TokError("expected section directive before assembly directive");
710 Out.SwitchSection(Ctx.getMachOSection(
712 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
713 0, SectionKind::getText()));
717 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
718 void AsmParser::EatToEndOfStatement() {
719 while (Lexer.isNot(AsmToken::EndOfStatement) &&
720 Lexer.isNot(AsmToken::Eof))
724 if (Lexer.is(AsmToken::EndOfStatement))
728 StringRef AsmParser::ParseStringToEndOfStatement() {
729 const char *Start = getTok().getLoc().getPointer();
731 while (Lexer.isNot(AsmToken::EndOfStatement) &&
732 Lexer.isNot(AsmToken::Eof))
735 const char *End = getTok().getLoc().getPointer();
736 return StringRef(Start, End - Start);
739 StringRef AsmParser::ParseStringToComma() {
740 const char *Start = getTok().getLoc().getPointer();
742 while (Lexer.isNot(AsmToken::EndOfStatement) &&
743 Lexer.isNot(AsmToken::Comma) &&
744 Lexer.isNot(AsmToken::Eof))
747 const char *End = getTok().getLoc().getPointer();
748 return StringRef(Start, End - Start);
751 /// ParseParenExpr - Parse a paren expression and return it.
752 /// NOTE: This assumes the leading '(' has already been consumed.
754 /// parenexpr ::= expr)
756 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
757 if (ParseExpression(Res)) return true;
758 if (Lexer.isNot(AsmToken::RParen))
759 return TokError("expected ')' in parentheses expression");
760 EndLoc = Lexer.getTok().getEndLoc();
765 /// ParseBracketExpr - Parse a bracket expression and return it.
766 /// NOTE: This assumes the leading '[' has already been consumed.
768 /// bracketexpr ::= expr]
770 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
771 if (ParseExpression(Res)) return true;
772 if (Lexer.isNot(AsmToken::RBrac))
773 return TokError("expected ']' in brackets expression");
774 EndLoc = Lexer.getTok().getEndLoc();
779 /// ParsePrimaryExpr - Parse a primary expression and return it.
780 /// primaryexpr ::= (parenexpr
781 /// primaryexpr ::= symbol
782 /// primaryexpr ::= number
783 /// primaryexpr ::= '.'
784 /// primaryexpr ::= ~,+,- primaryexpr
785 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
786 switch (Lexer.getKind()) {
788 return TokError("unknown token in expression");
789 // If we have an error assume that we've already handled it.
790 case AsmToken::Error:
792 case AsmToken::Exclaim:
793 Lex(); // Eat the operator.
794 if (ParsePrimaryExpr(Res, EndLoc))
796 Res = MCUnaryExpr::CreateLNot(Res, getContext());
798 case AsmToken::Dollar:
799 case AsmToken::String:
800 case AsmToken::Identifier: {
801 StringRef Identifier;
802 if (ParseIdentifier(Identifier))
805 EndLoc = SMLoc::getFromPointer(Identifier.end());
807 // This is a symbol reference.
808 std::pair<StringRef, StringRef> Split = Identifier.split('@');
809 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
811 // Lookup the symbol variant if used.
812 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
813 if (Split.first.size() != Identifier.size()) {
814 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
815 if (Variant == MCSymbolRefExpr::VK_Invalid) {
816 Variant = MCSymbolRefExpr::VK_None;
817 return TokError("invalid variant '" + Split.second + "'");
821 // If this is an absolute variable reference, substitute it now to preserve
822 // semantics in the face of reassignment.
823 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
825 return Error(EndLoc, "unexpected modifier on variable reference");
827 Res = Sym->getVariableValue();
831 // Otherwise create a symbol ref.
832 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
835 case AsmToken::Integer: {
836 SMLoc Loc = getTok().getLoc();
837 int64_t IntVal = getTok().getIntVal();
838 Res = MCConstantExpr::Create(IntVal, getContext());
839 EndLoc = Lexer.getTok().getEndLoc();
841 // Look for 'b' or 'f' following an Integer as a directional label
842 if (Lexer.getKind() == AsmToken::Identifier) {
843 StringRef IDVal = getTok().getString();
844 if (IDVal == "f" || IDVal == "b"){
845 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
846 IDVal == "f" ? 1 : 0);
847 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
849 if (IDVal == "b" && Sym->isUndefined())
850 return Error(Loc, "invalid reference to undefined symbol");
851 EndLoc = Lexer.getTok().getEndLoc();
852 Lex(); // Eat identifier.
857 case AsmToken::Real: {
858 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
859 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
860 Res = MCConstantExpr::Create(IntVal, getContext());
861 EndLoc = Lexer.getTok().getEndLoc();
865 case AsmToken::Dot: {
866 // This is a '.' reference, which references the current PC. Emit a
867 // temporary label to the streamer and refer to it.
868 MCSymbol *Sym = Ctx.CreateTempSymbol();
870 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
871 EndLoc = Lexer.getTok().getEndLoc();
872 Lex(); // Eat identifier.
875 case AsmToken::LParen:
876 Lex(); // Eat the '('.
877 return ParseParenExpr(Res, EndLoc);
878 case AsmToken::LBrac:
879 if (!PlatformParser->HasBracketExpressions())
880 return TokError("brackets expression not supported on this target");
881 Lex(); // Eat the '['.
882 return ParseBracketExpr(Res, EndLoc);
883 case AsmToken::Minus:
884 Lex(); // Eat the operator.
885 if (ParsePrimaryExpr(Res, EndLoc))
887 Res = MCUnaryExpr::CreateMinus(Res, getContext());
890 Lex(); // Eat the operator.
891 if (ParsePrimaryExpr(Res, EndLoc))
893 Res = MCUnaryExpr::CreatePlus(Res, getContext());
895 case AsmToken::Tilde:
896 Lex(); // Eat the operator.
897 if (ParsePrimaryExpr(Res, EndLoc))
899 Res = MCUnaryExpr::CreateNot(Res, getContext());
904 bool AsmParser::ParseExpression(const MCExpr *&Res) {
906 return ParseExpression(Res, EndLoc);
910 AsmParser::ApplyModifierToExpr(const MCExpr *E,
911 MCSymbolRefExpr::VariantKind Variant) {
912 // Recurse over the given expression, rebuilding it to apply the given variant
913 // if there is exactly one symbol.
914 switch (E->getKind()) {
916 case MCExpr::Constant:
919 case MCExpr::SymbolRef: {
920 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
922 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
923 TokError("invalid variant on expression '" +
924 getTok().getIdentifier() + "' (already modified)");
928 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
931 case MCExpr::Unary: {
932 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
933 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
936 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
939 case MCExpr::Binary: {
940 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
941 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
942 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
947 if (!LHS) LHS = BE->getLHS();
948 if (!RHS) RHS = BE->getRHS();
950 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
954 llvm_unreachable("Invalid expression kind!");
957 /// ParseExpression - Parse an expression and return it.
959 /// expr ::= expr &&,|| expr -> lowest.
960 /// expr ::= expr |,^,&,! expr
961 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
962 /// expr ::= expr <<,>> expr
963 /// expr ::= expr +,- expr
964 /// expr ::= expr *,/,% expr -> highest.
965 /// expr ::= primaryexpr
967 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
968 // Parse the expression.
970 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
973 // As a special case, we support 'a op b @ modifier' by rewriting the
974 // expression to include the modifier. This is inefficient, but in general we
975 // expect users to use 'a@modifier op b'.
976 if (Lexer.getKind() == AsmToken::At) {
979 if (Lexer.isNot(AsmToken::Identifier))
980 return TokError("unexpected symbol modifier following '@'");
982 MCSymbolRefExpr::VariantKind Variant =
983 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
984 if (Variant == MCSymbolRefExpr::VK_Invalid)
985 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
987 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
989 return TokError("invalid modifier '" + getTok().getIdentifier() +
990 "' (no symbols present)");
997 // Try to constant fold it up front, if possible.
999 if (Res->EvaluateAsAbsolute(Value))
1000 Res = MCConstantExpr::Create(Value, getContext());
1005 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1007 return ParseParenExpr(Res, EndLoc) ||
1008 ParseBinOpRHS(1, Res, EndLoc);
1011 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
1014 SMLoc StartLoc = Lexer.getLoc();
1015 if (ParseExpression(Expr))
1018 if (!Expr->EvaluateAsAbsolute(Res))
1019 return Error(StartLoc, "expected absolute expression");
1024 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1025 MCBinaryExpr::Opcode &Kind) {
1028 return 0; // not a binop.
1030 // Lowest Precedence: &&, ||
1031 case AsmToken::AmpAmp:
1032 Kind = MCBinaryExpr::LAnd;
1034 case AsmToken::PipePipe:
1035 Kind = MCBinaryExpr::LOr;
1039 // Low Precedence: |, &, ^
1041 // FIXME: gas seems to support '!' as an infix operator?
1042 case AsmToken::Pipe:
1043 Kind = MCBinaryExpr::Or;
1045 case AsmToken::Caret:
1046 Kind = MCBinaryExpr::Xor;
1049 Kind = MCBinaryExpr::And;
1052 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1053 case AsmToken::EqualEqual:
1054 Kind = MCBinaryExpr::EQ;
1056 case AsmToken::ExclaimEqual:
1057 case AsmToken::LessGreater:
1058 Kind = MCBinaryExpr::NE;
1060 case AsmToken::Less:
1061 Kind = MCBinaryExpr::LT;
1063 case AsmToken::LessEqual:
1064 Kind = MCBinaryExpr::LTE;
1066 case AsmToken::Greater:
1067 Kind = MCBinaryExpr::GT;
1069 case AsmToken::GreaterEqual:
1070 Kind = MCBinaryExpr::GTE;
1073 // Intermediate Precedence: <<, >>
1074 case AsmToken::LessLess:
1075 Kind = MCBinaryExpr::Shl;
1077 case AsmToken::GreaterGreater:
1078 Kind = MCBinaryExpr::Shr;
1081 // High Intermediate Precedence: +, -
1082 case AsmToken::Plus:
1083 Kind = MCBinaryExpr::Add;
1085 case AsmToken::Minus:
1086 Kind = MCBinaryExpr::Sub;
1089 // Highest Precedence: *, /, %
1090 case AsmToken::Star:
1091 Kind = MCBinaryExpr::Mul;
1093 case AsmToken::Slash:
1094 Kind = MCBinaryExpr::Div;
1096 case AsmToken::Percent:
1097 Kind = MCBinaryExpr::Mod;
1103 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1104 /// Res contains the LHS of the expression on input.
1105 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1108 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1109 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1111 // If the next token is lower precedence than we are allowed to eat, return
1112 // successfully with what we ate already.
1113 if (TokPrec < Precedence)
1118 // Eat the next primary expression.
1120 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1122 // If BinOp binds less tightly with RHS than the operator after RHS, let
1123 // the pending operator take RHS as its LHS.
1124 MCBinaryExpr::Opcode Dummy;
1125 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1126 if (TokPrec < NextTokPrec) {
1127 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1130 // Merge LHS and RHS according to operator.
1131 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1136 /// ::= EndOfStatement
1137 /// ::= Label* Directive ...Operands... EndOfStatement
1138 /// ::= Label* Identifier OperandList* EndOfStatement
1139 bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
1140 if (Lexer.is(AsmToken::EndOfStatement)) {
1146 // Statements always start with an identifier or are a full line comment.
1147 AsmToken ID = getTok();
1148 SMLoc IDLoc = ID.getLoc();
1150 int64_t LocalLabelVal = -1;
1151 // A full line comment is a '#' as the first token.
1152 if (Lexer.is(AsmToken::Hash))
1153 return ParseCppHashLineFilenameComment(IDLoc);
1155 // Allow an integer followed by a ':' as a directional local label.
1156 if (Lexer.is(AsmToken::Integer)) {
1157 LocalLabelVal = getTok().getIntVal();
1158 if (LocalLabelVal < 0) {
1159 if (!TheCondState.Ignore)
1160 return TokError("unexpected token at start of statement");
1164 IDVal = getTok().getString();
1165 Lex(); // Consume the integer token to be used as an identifier token.
1166 if (Lexer.getKind() != AsmToken::Colon) {
1167 if (!TheCondState.Ignore)
1168 return TokError("unexpected token at start of statement");
1172 } else if (Lexer.is(AsmToken::Dot)) {
1173 // Treat '.' as a valid identifier in this context.
1177 } else if (ParseIdentifier(IDVal)) {
1178 if (!TheCondState.Ignore)
1179 return TokError("unexpected token at start of statement");
1183 // Handle conditional assembly here before checking for skipping. We
1184 // have to do this so that .endif isn't skipped in a ".if 0" block for
1186 StringMap<DirectiveKind>::const_iterator DirKindIt =
1187 DirectiveKindMapping.find(IDVal);
1188 DirectiveKind DirKind =
1189 (DirKindIt == DirectiveKindMapping.end()) ? DK_NO_DIRECTIVE :
1190 DirKindIt->getValue();
1195 return ParseDirectiveIf(IDLoc);
1197 return ParseDirectiveIfb(IDLoc, true);
1199 return ParseDirectiveIfb(IDLoc, false);
1201 return ParseDirectiveIfc(IDLoc, true);
1203 return ParseDirectiveIfc(IDLoc, false);
1205 return ParseDirectiveIfdef(IDLoc, true);
1208 return ParseDirectiveIfdef(IDLoc, false);
1210 return ParseDirectiveElseIf(IDLoc);
1212 return ParseDirectiveElse(IDLoc);
1214 return ParseDirectiveEndIf(IDLoc);
1217 // If we are in a ".if 0" block, ignore this statement.
1218 if (TheCondState.Ignore) {
1219 EatToEndOfStatement();
1223 // FIXME: Recurse on local labels?
1225 // See what kind of statement we have.
1226 switch (Lexer.getKind()) {
1227 case AsmToken::Colon: {
1228 CheckForValidSection();
1230 // identifier ':' -> Label.
1233 // Diagnose attempt to use '.' as a label.
1235 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1237 // Diagnose attempt to use a variable as a label.
1239 // FIXME: Diagnostics. Note the location of the definition as a label.
1240 // FIXME: This doesn't diagnose assignment to a symbol which has been
1241 // implicitly marked as external.
1243 if (LocalLabelVal == -1)
1244 Sym = getContext().GetOrCreateSymbol(IDVal);
1246 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1247 if (!Sym->isUndefined() || Sym->isVariable())
1248 return Error(IDLoc, "invalid symbol redefinition");
1251 if (!ParsingInlineAsm)
1254 // If we are generating dwarf for assembly source files then gather the
1255 // info to make a dwarf label entry for this label if needed.
1256 if (getContext().getGenDwarfForAssembly())
1257 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1260 // Consume any end of statement token, if present, to avoid spurious
1261 // AddBlankLine calls().
1262 if (Lexer.is(AsmToken::EndOfStatement)) {
1264 if (Lexer.is(AsmToken::Eof))
1271 case AsmToken::Equal:
1272 // identifier '=' ... -> assignment statement
1275 return ParseAssignment(IDVal, true);
1277 default: // Normal instruction or directive.
1281 // If macros are enabled, check to see if this is a macro instantiation.
1283 if (const Macro *M = MacroMap.lookup(IDVal))
1284 return HandleMacroEntry(IDVal, IDLoc, M);
1286 // Otherwise, we have a normal instruction or directive.
1287 if (IDVal[0] == '.' && IDVal != ".") {
1289 // Target hook for parsing target specific directives.
1290 if (!getTargetParser().ParseDirective(ID))
1298 return ParseDirectiveSet(IDVal, true);
1300 return ParseDirectiveSet(IDVal, false);
1302 return ParseDirectiveAscii(IDVal, false);
1305 return ParseDirectiveAscii(IDVal, true);
1307 return ParseDirectiveValue(1);
1311 return ParseDirectiveValue(2);
1315 return ParseDirectiveValue(4);
1318 return ParseDirectiveValue(8);
1321 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1323 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1325 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1326 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1329 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1330 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1333 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1335 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1337 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1339 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1341 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1343 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1345 return ParseDirectiveOrg();
1347 return ParseDirectiveFill();
1349 return ParseDirectiveZero();
1351 EatToEndOfStatement(); // .extern is the default, ignore it.
1355 return ParseDirectiveSymbolAttribute(MCSA_Global);
1356 case DK_INDIRECT_SYMBOL:
1357 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1358 case DK_LAZY_REFERENCE:
1359 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1360 case DK_NO_DEAD_STRIP:
1361 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1362 case DK_SYMBOL_RESOLVER:
1363 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1364 case DK_PRIVATE_EXTERN:
1365 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1367 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1368 case DK_WEAK_DEFINITION:
1369 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1370 case DK_WEAK_REFERENCE:
1371 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1372 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1373 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1376 return ParseDirectiveComm(/*IsLocal=*/false);
1378 return ParseDirectiveComm(/*IsLocal=*/true);
1380 return ParseDirectiveAbort();
1382 return ParseDirectiveInclude();
1384 return ParseDirectiveIncbin();
1387 return TokError(Twine(IDVal) + " not supported yet");
1389 return ParseDirectiveRept(IDLoc);
1391 return ParseDirectiveIrp(IDLoc);
1393 return ParseDirectiveIrpc(IDLoc);
1395 return ParseDirectiveEndr(IDLoc);
1396 case DK_BUNDLE_ALIGN_MODE:
1397 return ParseDirectiveBundleAlignMode();
1398 case DK_BUNDLE_LOCK:
1399 return ParseDirectiveBundleLock();
1400 case DK_BUNDLE_UNLOCK:
1401 return ParseDirectiveBundleUnlock();
1404 // Look up the handler in the extension handler table.
1405 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1406 DirectiveMap.lookup(IDVal);
1408 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1410 return Error(IDLoc, "unknown directive");
1414 if (ParsingInlineAsm && IDVal == "_emit")
1415 return ParseDirectiveEmit(IDLoc, Info);
1417 CheckForValidSection();
1419 // Canonicalize the opcode to lower case.
1420 SmallString<128> OpcodeStr;
1421 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1422 OpcodeStr.push_back(tolower(IDVal[i]));
1424 ParseInstructionInfo IInfo(Info.AsmRewrites);
1425 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1426 IDLoc,Info.ParsedOperands);
1427 Info.ParseError = HadError;
1429 // Dump the parsed representation, if requested.
1430 if (getShowParsedOperands()) {
1431 SmallString<256> Str;
1432 raw_svector_ostream OS(Str);
1433 OS << "parsed instruction: [";
1434 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1437 Info.ParsedOperands[i]->print(OS);
1441 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1444 // If we are generating dwarf for assembly source files and the current
1445 // section is the initial text section then generate a .loc directive for
1447 if (!HadError && getContext().getGenDwarfForAssembly() &&
1448 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
1450 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1452 // If we previously parsed a cpp hash file line comment then make sure the
1453 // current Dwarf File is for the CppHashFilename if not then emit the
1454 // Dwarf File table for it and adjust the line number for the .loc.
1455 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1456 getContext().getMCDwarfFiles();
1457 if (CppHashFilename.size() != 0) {
1458 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1460 getStreamer().EmitDwarfFileDirective(
1461 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1463 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
1464 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1467 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1468 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1469 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1473 // If parsing succeeded, match the instruction.
1476 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1477 Info.ParsedOperands,
1482 // Don't skip the rest of the line, the instruction parser is responsible for
1487 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1488 /// since they may not be able to be tokenized to get to the end of line token.
1489 void AsmParser::EatToEndOfLine() {
1490 if (!Lexer.is(AsmToken::EndOfStatement))
1491 Lexer.LexUntilEndOfLine();
1496 /// ParseCppHashLineFilenameComment as this:
1497 /// ::= # number "filename"
1498 /// or just as a full line comment if it doesn't have a number and a string.
1499 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1500 Lex(); // Eat the hash token.
1502 if (getLexer().isNot(AsmToken::Integer)) {
1503 // Consume the line since in cases it is not a well-formed line directive,
1504 // as if were simply a full line comment.
1509 int64_t LineNumber = getTok().getIntVal();
1512 if (getLexer().isNot(AsmToken::String)) {
1517 StringRef Filename = getTok().getString();
1518 // Get rid of the enclosing quotes.
1519 Filename = Filename.substr(1, Filename.size()-2);
1521 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1523 CppHashFilename = Filename;
1524 CppHashLineNumber = LineNumber;
1525 CppHashBuf = CurBuffer;
1527 // Ignore any trailing characters, they're just comment.
1532 /// DiagHandler - will use the last parsed cpp hash line filename comment
1533 /// for the Filename and LineNo if any in the diagnostic.
1534 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1535 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1536 raw_ostream &OS = errs();
1538 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1539 const SMLoc &DiagLoc = Diag.getLoc();
1540 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1541 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1543 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1544 // before printing the message.
1545 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1546 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1547 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1548 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1551 // If we have not parsed a cpp hash line filename comment or the source
1552 // manager changed or buffer changed (like in a nested include) then just
1553 // print the normal diagnostic using its Filename and LineNo.
1554 if (!Parser->CppHashLineNumber ||
1555 &DiagSrcMgr != &Parser->SrcMgr ||
1556 DiagBuf != CppHashBuf) {
1557 if (Parser->SavedDiagHandler)
1558 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1564 // Use the CppHashFilename and calculate a line number based on the
1565 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1567 const std::string Filename = Parser->CppHashFilename;
1569 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1570 int CppHashLocLineNo =
1571 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1572 int LineNo = Parser->CppHashLineNumber - 1 +
1573 (DiagLocLineNo - CppHashLocLineNo);
1575 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1576 Filename, LineNo, Diag.getColumnNo(),
1577 Diag.getKind(), Diag.getMessage(),
1578 Diag.getLineContents(), Diag.getRanges());
1580 if (Parser->SavedDiagHandler)
1581 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1583 NewDiag.print(0, OS);
1586 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1587 // difference being that that function accepts '@' as part of identifiers and
1588 // we can't do that. AsmLexer.cpp should probably be changed to handle
1589 // '@' as a special case when needed.
1590 static bool isIdentifierChar(char c) {
1591 return isalnum(c) || c == '_' || c == '$' || c == '.';
1594 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1595 const MacroParameters &Parameters,
1596 const MacroArguments &A,
1598 unsigned NParameters = Parameters.size();
1599 if (NParameters != 0 && NParameters != A.size())
1600 return Error(L, "Wrong number of arguments");
1602 // A macro without parameters is handled differently on Darwin:
1603 // gas accepts no arguments and does no substitutions
1604 while (!Body.empty()) {
1605 // Scan for the next substitution.
1606 std::size_t End = Body.size(), Pos = 0;
1607 for (; Pos != End; ++Pos) {
1608 // Check for a substitution or escape.
1610 // This macro has no parameters, look for $0, $1, etc.
1611 if (Body[Pos] != '$' || Pos + 1 == End)
1614 char Next = Body[Pos + 1];
1615 if (Next == '$' || Next == 'n' || isdigit(Next))
1618 // This macro has parameters, look for \foo, \bar, etc.
1619 if (Body[Pos] == '\\' && Pos + 1 != End)
1625 OS << Body.slice(0, Pos);
1627 // Check if we reached the end.
1632 switch (Body[Pos+1]) {
1638 // $n => number of arguments
1643 // $[0-9] => argument
1645 // Missing arguments are ignored.
1646 unsigned Index = Body[Pos+1] - '0';
1647 if (Index >= A.size())
1650 // Otherwise substitute with the token values, with spaces eliminated.
1651 for (MacroArgument::const_iterator it = A[Index].begin(),
1652 ie = A[Index].end(); it != ie; ++it)
1653 OS << it->getString();
1659 unsigned I = Pos + 1;
1660 while (isIdentifierChar(Body[I]) && I + 1 != End)
1663 const char *Begin = Body.data() + Pos +1;
1664 StringRef Argument(Begin, I - (Pos +1));
1666 for (; Index < NParameters; ++Index)
1667 if (Parameters[Index].first == Argument)
1670 if (Index == NParameters) {
1671 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1674 OS << '\\' << Argument;
1678 for (MacroArgument::const_iterator it = A[Index].begin(),
1679 ie = A[Index].end(); it != ie; ++it)
1680 if (it->getKind() == AsmToken::String)
1681 OS << it->getStringContents();
1683 OS << it->getString();
1685 Pos += 1 + Argument.size();
1688 // Update the scan point.
1689 Body = Body.substr(Pos);
1695 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL,
1698 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1703 static bool IsOperator(AsmToken::TokenKind kind)
1709 case AsmToken::Plus:
1710 case AsmToken::Minus:
1711 case AsmToken::Tilde:
1712 case AsmToken::Slash:
1713 case AsmToken::Star:
1715 case AsmToken::Equal:
1716 case AsmToken::EqualEqual:
1717 case AsmToken::Pipe:
1718 case AsmToken::PipePipe:
1719 case AsmToken::Caret:
1721 case AsmToken::AmpAmp:
1722 case AsmToken::Exclaim:
1723 case AsmToken::ExclaimEqual:
1724 case AsmToken::Percent:
1725 case AsmToken::Less:
1726 case AsmToken::LessEqual:
1727 case AsmToken::LessLess:
1728 case AsmToken::LessGreater:
1729 case AsmToken::Greater:
1730 case AsmToken::GreaterEqual:
1731 case AsmToken::GreaterGreater:
1736 /// ParseMacroArgument - Extract AsmTokens for a macro argument.
1737 /// This is used for both default macro parameter values and the
1738 /// arguments in macro invocations
1739 bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1740 AsmToken::TokenKind &ArgumentDelimiter) {
1741 unsigned ParenLevel = 0;
1742 unsigned AddTokens = 0;
1744 // gas accepts arguments separated by whitespace, except on Darwin
1746 Lexer.setSkipSpace(false);
1749 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1750 Lexer.setSkipSpace(true);
1751 return TokError("unexpected token in macro instantiation");
1754 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1755 // Spaces and commas cannot be mixed to delimit parameters
1756 if (ArgumentDelimiter == AsmToken::Eof)
1757 ArgumentDelimiter = AsmToken::Comma;
1758 else if (ArgumentDelimiter != AsmToken::Comma) {
1759 Lexer.setSkipSpace(true);
1760 return TokError("expected ' ' for macro argument separator");
1765 if (Lexer.is(AsmToken::Space)) {
1766 Lex(); // Eat spaces
1768 // Spaces can delimit parameters, but could also be part an expression.
1769 // If the token after a space is an operator, add the token and the next
1770 // one into this argument
1771 if (ArgumentDelimiter == AsmToken::Space ||
1772 ArgumentDelimiter == AsmToken::Eof) {
1773 if (IsOperator(Lexer.getKind())) {
1774 // Check to see whether the token is used as an operator,
1775 // or part of an identifier
1776 const char *NextChar = getTok().getEndLoc().getPointer();
1777 if (*NextChar == ' ')
1781 if (!AddTokens && ParenLevel == 0) {
1782 if (ArgumentDelimiter == AsmToken::Eof &&
1783 !IsOperator(Lexer.getKind()))
1784 ArgumentDelimiter = AsmToken::Space;
1790 // HandleMacroEntry relies on not advancing the lexer here
1791 // to be able to fill in the remaining default parameter values
1792 if (Lexer.is(AsmToken::EndOfStatement))
1795 // Adjust the current parentheses level.
1796 if (Lexer.is(AsmToken::LParen))
1798 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1801 // Append the token to the current argument list.
1802 MA.push_back(getTok());
1808 Lexer.setSkipSpace(true);
1809 if (ParenLevel != 0)
1810 return TokError("unbalanced parentheses in macro argument");
1814 // Parse the macro instantiation arguments.
1815 bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
1816 const unsigned NParameters = M ? M->Parameters.size() : 0;
1817 // Argument delimiter is initially unknown. It will be set by
1818 // ParseMacroArgument()
1819 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1821 // Parse two kinds of macro invocations:
1822 // - macros defined without any parameters accept an arbitrary number of them
1823 // - macros defined with parameters accept at most that many of them
1824 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1828 if (ParseMacroArgument(MA, ArgumentDelimiter))
1831 if (!MA.empty() || !NParameters)
1833 else if (NParameters) {
1834 if (!M->Parameters[Parameter].second.empty())
1835 A.push_back(M->Parameters[Parameter].second);
1838 // At the end of the statement, fill in remaining arguments that have
1839 // default values. If there aren't any, then the next argument is
1840 // required but missing
1841 if (Lexer.is(AsmToken::EndOfStatement)) {
1842 if (NParameters && Parameter < NParameters - 1) {
1843 if (M->Parameters[Parameter + 1].second.empty())
1844 return TokError("macro argument '" +
1845 Twine(M->Parameters[Parameter + 1].first) +
1853 if (Lexer.is(AsmToken::Comma))
1856 return TokError("Too many arguments");
1859 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1861 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1862 // this, although we should protect against infinite loops.
1863 if (ActiveMacros.size() == 20)
1864 return TokError("macros cannot be nested more than 20 levels deep");
1867 if (ParseMacroArguments(M, A))
1870 // Remove any trailing empty arguments. Do this after-the-fact as we have
1871 // to keep empty arguments in the middle of the list or positionality
1872 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1873 while (!A.empty() && A.back().empty())
1876 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1877 // to hold the macro body with substitutions.
1878 SmallString<256> Buf;
1879 StringRef Body = M->Body;
1880 raw_svector_ostream OS(Buf);
1882 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1885 // We include the .endmacro in the buffer as our queue to exit the macro
1887 OS << ".endmacro\n";
1889 MemoryBuffer *Instantiation =
1890 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1892 // Create the macro instantiation object and add to the current macro
1893 // instantiation stack.
1894 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1898 ActiveMacros.push_back(MI);
1900 // Jump to the macro instantiation and prime the lexer.
1901 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1902 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1908 void AsmParser::HandleMacroExit() {
1909 // Jump to the EndOfStatement we should return to, and consume it.
1910 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
1913 // Pop the instantiation entry.
1914 delete ActiveMacros.back();
1915 ActiveMacros.pop_back();
1918 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1919 switch (Value->getKind()) {
1920 case MCExpr::Binary: {
1921 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1922 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1925 case MCExpr::Target:
1926 case MCExpr::Constant:
1928 case MCExpr::SymbolRef: {
1929 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1931 return IsUsedIn(Sym, S.getVariableValue());
1935 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1938 llvm_unreachable("Unknown expr kind!");
1941 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1943 // FIXME: Use better location, we should use proper tokens.
1944 SMLoc EqualLoc = Lexer.getLoc();
1946 const MCExpr *Value;
1947 if (ParseExpression(Value))
1950 // Note: we don't count b as used in "a = b". This is to allow
1954 if (Lexer.isNot(AsmToken::EndOfStatement))
1955 return TokError("unexpected token in assignment");
1957 // Error on assignment to '.'.
1959 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1960 "(use '.space' or '.org').)"));
1963 // Eat the end of statement marker.
1966 // Validate that the LHS is allowed to be a variable (either it has not been
1967 // used as a symbol, or it is an absolute symbol).
1968 MCSymbol *Sym = getContext().LookupSymbol(Name);
1970 // Diagnose assignment to a label.
1972 // FIXME: Diagnostics. Note the location of the definition as a label.
1973 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1974 if (IsUsedIn(Sym, Value))
1975 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1976 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1977 ; // Allow redefinitions of undefined symbols only used in directives.
1978 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1979 ; // Allow redefinitions of variables that haven't yet been used.
1980 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1981 return Error(EqualLoc, "redefinition of '" + Name + "'");
1982 else if (!Sym->isVariable())
1983 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1984 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1985 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1988 // Don't count these checks as uses.
1989 Sym->setUsed(false);
1991 Sym = getContext().GetOrCreateSymbol(Name);
1993 // FIXME: Handle '.'.
1995 // Do the assignment.
1996 Out.EmitAssignment(Sym, Value);
1998 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2004 /// ParseIdentifier:
2007 bool AsmParser::ParseIdentifier(StringRef &Res) {
2008 // The assembler has relaxed rules for accepting identifiers, in particular we
2009 // allow things like '.globl $foo', which would normally be separate
2010 // tokens. At this level, we have already lexed so we cannot (currently)
2011 // handle this as a context dependent token, instead we detect adjacent tokens
2012 // and return the combined identifier.
2013 if (Lexer.is(AsmToken::Dollar)) {
2014 SMLoc DollarLoc = getLexer().getLoc();
2016 // Consume the dollar sign, and check for a following identifier.
2018 if (Lexer.isNot(AsmToken::Identifier))
2021 // We have a '$' followed by an identifier, make sure they are adjacent.
2022 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2025 // Construct the joined identifier and consume the token.
2026 Res = StringRef(DollarLoc.getPointer(),
2027 getTok().getIdentifier().size() + 1);
2032 if (Lexer.isNot(AsmToken::Identifier) &&
2033 Lexer.isNot(AsmToken::String))
2036 Res = getTok().getIdentifier();
2038 Lex(); // Consume the identifier token.
2043 /// ParseDirectiveSet:
2044 /// ::= .equ identifier ',' expression
2045 /// ::= .equiv identifier ',' expression
2046 /// ::= .set identifier ',' expression
2047 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
2050 if (ParseIdentifier(Name))
2051 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2053 if (getLexer().isNot(AsmToken::Comma))
2054 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2057 return ParseAssignment(Name, allow_redef, true);
2060 bool AsmParser::ParseEscapedString(std::string &Data) {
2061 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2064 StringRef Str = getTok().getStringContents();
2065 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2066 if (Str[i] != '\\') {
2071 // Recognize escaped characters. Note that this escape semantics currently
2072 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2075 return TokError("unexpected backslash at end of string");
2077 // Recognize octal sequences.
2078 if ((unsigned) (Str[i] - '0') <= 7) {
2079 // Consume up to three octal characters.
2080 unsigned Value = Str[i] - '0';
2082 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2084 Value = Value * 8 + (Str[i] - '0');
2086 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2088 Value = Value * 8 + (Str[i] - '0');
2093 return TokError("invalid octal escape sequence (out of range)");
2095 Data += (unsigned char) Value;
2099 // Otherwise recognize individual escapes.
2102 // Just reject invalid escape sequences for now.
2103 return TokError("invalid escape sequence (unrecognized character)");
2105 case 'b': Data += '\b'; break;
2106 case 'f': Data += '\f'; break;
2107 case 'n': Data += '\n'; break;
2108 case 'r': Data += '\r'; break;
2109 case 't': Data += '\t'; break;
2110 case '"': Data += '"'; break;
2111 case '\\': Data += '\\'; break;
2118 /// ParseDirectiveAscii:
2119 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2120 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2121 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2122 CheckForValidSection();
2125 if (getLexer().isNot(AsmToken::String))
2126 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2129 if (ParseEscapedString(Data))
2132 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2134 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2138 if (getLexer().is(AsmToken::EndOfStatement))
2141 if (getLexer().isNot(AsmToken::Comma))
2142 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2151 /// ParseDirectiveValue
2152 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2153 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2154 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2155 CheckForValidSection();
2158 const MCExpr *Value;
2159 SMLoc ExprLoc = getLexer().getLoc();
2160 if (ParseExpression(Value))
2163 // Special case constant expressions to match code generator.
2164 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2165 assert(Size <= 8 && "Invalid size");
2166 uint64_t IntValue = MCE->getValue();
2167 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2168 return Error(ExprLoc, "literal value out of range for directive");
2169 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2171 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2173 if (getLexer().is(AsmToken::EndOfStatement))
2176 // FIXME: Improve diagnostic.
2177 if (getLexer().isNot(AsmToken::Comma))
2178 return TokError("unexpected token in directive");
2187 /// ParseDirectiveRealValue
2188 /// ::= (.single | .double) [ expression (, expression)* ]
2189 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2190 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2191 CheckForValidSection();
2194 // We don't truly support arithmetic on floating point expressions, so we
2195 // have to manually parse unary prefixes.
2197 if (getLexer().is(AsmToken::Minus)) {
2200 } else if (getLexer().is(AsmToken::Plus))
2203 if (getLexer().isNot(AsmToken::Integer) &&
2204 getLexer().isNot(AsmToken::Real) &&
2205 getLexer().isNot(AsmToken::Identifier))
2206 return TokError("unexpected token in directive");
2208 // Convert to an APFloat.
2209 APFloat Value(Semantics);
2210 StringRef IDVal = getTok().getString();
2211 if (getLexer().is(AsmToken::Identifier)) {
2212 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2213 Value = APFloat::getInf(Semantics);
2214 else if (!IDVal.compare_lower("nan"))
2215 Value = APFloat::getNaN(Semantics, false, ~0);
2217 return TokError("invalid floating point literal");
2218 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2219 APFloat::opInvalidOp)
2220 return TokError("invalid floating point literal");
2224 // Consume the numeric token.
2227 // Emit the value as an integer.
2228 APInt AsInt = Value.bitcastToAPInt();
2229 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2230 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2232 if (getLexer().is(AsmToken::EndOfStatement))
2235 if (getLexer().isNot(AsmToken::Comma))
2236 return TokError("unexpected token in directive");
2245 /// ParseDirectiveZero
2246 /// ::= .zero expression
2247 bool AsmParser::ParseDirectiveZero() {
2248 CheckForValidSection();
2251 if (ParseAbsoluteExpression(NumBytes))
2255 if (getLexer().is(AsmToken::Comma)) {
2257 if (ParseAbsoluteExpression(Val))
2261 if (getLexer().isNot(AsmToken::EndOfStatement))
2262 return TokError("unexpected token in '.zero' directive");
2266 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2271 /// ParseDirectiveFill
2272 /// ::= .fill expression , expression , expression
2273 bool AsmParser::ParseDirectiveFill() {
2274 CheckForValidSection();
2277 if (ParseAbsoluteExpression(NumValues))
2280 if (getLexer().isNot(AsmToken::Comma))
2281 return TokError("unexpected token in '.fill' directive");
2285 if (ParseAbsoluteExpression(FillSize))
2288 if (getLexer().isNot(AsmToken::Comma))
2289 return TokError("unexpected token in '.fill' directive");
2293 if (ParseAbsoluteExpression(FillExpr))
2296 if (getLexer().isNot(AsmToken::EndOfStatement))
2297 return TokError("unexpected token in '.fill' directive");
2301 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2302 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2304 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2305 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2310 /// ParseDirectiveOrg
2311 /// ::= .org expression [ , expression ]
2312 bool AsmParser::ParseDirectiveOrg() {
2313 CheckForValidSection();
2315 const MCExpr *Offset;
2316 SMLoc Loc = getTok().getLoc();
2317 if (ParseExpression(Offset))
2320 // Parse optional fill expression.
2321 int64_t FillExpr = 0;
2322 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2323 if (getLexer().isNot(AsmToken::Comma))
2324 return TokError("unexpected token in '.org' directive");
2327 if (ParseAbsoluteExpression(FillExpr))
2330 if (getLexer().isNot(AsmToken::EndOfStatement))
2331 return TokError("unexpected token in '.org' directive");
2336 // Only limited forms of relocatable expressions are accepted here, it
2337 // has to be relative to the current section. The streamer will return
2338 // 'true' if the expression wasn't evaluatable.
2339 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2340 return Error(Loc, "expected assembly-time absolute expression");
2345 /// ParseDirectiveAlign
2346 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2347 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2348 CheckForValidSection();
2350 SMLoc AlignmentLoc = getLexer().getLoc();
2352 if (ParseAbsoluteExpression(Alignment))
2356 bool HasFillExpr = false;
2357 int64_t FillExpr = 0;
2358 int64_t MaxBytesToFill = 0;
2359 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2360 if (getLexer().isNot(AsmToken::Comma))
2361 return TokError("unexpected token in directive");
2364 // The fill expression can be omitted while specifying a maximum number of
2365 // alignment bytes, e.g:
2367 if (getLexer().isNot(AsmToken::Comma)) {
2369 if (ParseAbsoluteExpression(FillExpr))
2373 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2374 if (getLexer().isNot(AsmToken::Comma))
2375 return TokError("unexpected token in directive");
2378 MaxBytesLoc = getLexer().getLoc();
2379 if (ParseAbsoluteExpression(MaxBytesToFill))
2382 if (getLexer().isNot(AsmToken::EndOfStatement))
2383 return TokError("unexpected token in directive");
2392 // Compute alignment in bytes.
2394 // FIXME: Diagnose overflow.
2395 if (Alignment >= 32) {
2396 Error(AlignmentLoc, "invalid alignment value");
2400 Alignment = 1ULL << Alignment;
2403 // Diagnose non-sensical max bytes to align.
2404 if (MaxBytesLoc.isValid()) {
2405 if (MaxBytesToFill < 1) {
2406 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2407 "many bytes, ignoring maximum bytes expression");
2411 if (MaxBytesToFill >= Alignment) {
2412 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2418 // Check whether we should use optimal code alignment for this .align
2420 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2421 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2422 ValueSize == 1 && UseCodeAlign) {
2423 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2425 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2426 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2434 /// ParseDirectiveBundleAlignMode
2435 /// ::= {.bundle_align_mode} expression
2436 bool AsmParser::ParseDirectiveBundleAlignMode() {
2437 CheckForValidSection();
2439 // Expect a single argument: an expression that evaluates to a constant
2440 // in the inclusive range 0-30.
2441 SMLoc ExprLoc = getLexer().getLoc();
2442 int64_t AlignSizePow2;
2443 if (ParseAbsoluteExpression(AlignSizePow2))
2445 else if (getLexer().isNot(AsmToken::EndOfStatement))
2446 return TokError("unexpected token after expression in"
2447 " '.bundle_align_mode' directive");
2448 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
2449 return Error(ExprLoc,
2450 "invalid bundle alignment size (expected between 0 and 30)");
2454 // Because of AlignSizePow2's verified range we can safely truncate it to
2456 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
2460 /// ParseDirectiveBundleLock
2461 /// ::= {.bundle_lock} [align_to_end]
2462 bool AsmParser::ParseDirectiveBundleLock() {
2463 CheckForValidSection();
2464 bool AlignToEnd = false;
2466 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2468 SMLoc Loc = getTok().getLoc();
2469 const char *kInvalidOptionError =
2470 "invalid option for '.bundle_lock' directive";
2472 if (ParseIdentifier(Option))
2473 return Error(Loc, kInvalidOptionError);
2475 if (Option != "align_to_end")
2476 return Error(Loc, kInvalidOptionError);
2477 else if (getLexer().isNot(AsmToken::EndOfStatement))
2479 "unexpected token after '.bundle_lock' directive option");
2485 getStreamer().EmitBundleLock(AlignToEnd);
2489 /// ParseDirectiveBundleLock
2490 /// ::= {.bundle_lock}
2491 bool AsmParser::ParseDirectiveBundleUnlock() {
2492 CheckForValidSection();
2494 if (getLexer().isNot(AsmToken::EndOfStatement))
2495 return TokError("unexpected token in '.bundle_unlock' directive");
2498 getStreamer().EmitBundleUnlock();
2502 /// ParseDirectiveSymbolAttribute
2503 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2504 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2505 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2508 SMLoc Loc = getTok().getLoc();
2510 if (ParseIdentifier(Name))
2511 return Error(Loc, "expected identifier in directive");
2513 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2515 // Assembler local symbols don't make any sense here. Complain loudly.
2516 if (Sym->isTemporary())
2517 return Error(Loc, "non-local symbol required in directive");
2519 getStreamer().EmitSymbolAttribute(Sym, Attr);
2521 if (getLexer().is(AsmToken::EndOfStatement))
2524 if (getLexer().isNot(AsmToken::Comma))
2525 return TokError("unexpected token in directive");
2534 /// ParseDirectiveComm
2535 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2536 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2537 CheckForValidSection();
2539 SMLoc IDLoc = getLexer().getLoc();
2541 if (ParseIdentifier(Name))
2542 return TokError("expected identifier in directive");
2544 // Handle the identifier as the key symbol.
2545 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2547 if (getLexer().isNot(AsmToken::Comma))
2548 return TokError("unexpected token in directive");
2552 SMLoc SizeLoc = getLexer().getLoc();
2553 if (ParseAbsoluteExpression(Size))
2556 int64_t Pow2Alignment = 0;
2557 SMLoc Pow2AlignmentLoc;
2558 if (getLexer().is(AsmToken::Comma)) {
2560 Pow2AlignmentLoc = getLexer().getLoc();
2561 if (ParseAbsoluteExpression(Pow2Alignment))
2564 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2565 if (IsLocal && LCOMM == LCOMM::NoAlignment)
2566 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2568 // If this target takes alignments in bytes (not log) validate and convert.
2569 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2570 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
2571 if (!isPowerOf2_64(Pow2Alignment))
2572 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2573 Pow2Alignment = Log2_64(Pow2Alignment);
2577 if (getLexer().isNot(AsmToken::EndOfStatement))
2578 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2582 // NOTE: a size of zero for a .comm should create a undefined symbol
2583 // but a size of .lcomm creates a bss symbol of size zero.
2585 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2586 "be less than zero");
2588 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2589 // may internally end up wanting an alignment in bytes.
2590 // FIXME: Diagnose overflow.
2591 if (Pow2Alignment < 0)
2592 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2593 "alignment, can't be less than zero");
2595 if (!Sym->isUndefined())
2596 return Error(IDLoc, "invalid symbol redefinition");
2598 // Create the Symbol as a common or local common with Size and Pow2Alignment
2600 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2604 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2608 /// ParseDirectiveAbort
2609 /// ::= .abort [... message ...]
2610 bool AsmParser::ParseDirectiveAbort() {
2611 // FIXME: Use loc from directive.
2612 SMLoc Loc = getLexer().getLoc();
2614 StringRef Str = ParseStringToEndOfStatement();
2615 if (getLexer().isNot(AsmToken::EndOfStatement))
2616 return TokError("unexpected token in '.abort' directive");
2621 Error(Loc, ".abort detected. Assembly stopping.");
2623 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2624 // FIXME: Actually abort assembly here.
2629 /// ParseDirectiveInclude
2630 /// ::= .include "filename"
2631 bool AsmParser::ParseDirectiveInclude() {
2632 if (getLexer().isNot(AsmToken::String))
2633 return TokError("expected string in '.include' directive");
2635 std::string Filename = getTok().getString();
2636 SMLoc IncludeLoc = getLexer().getLoc();
2639 if (getLexer().isNot(AsmToken::EndOfStatement))
2640 return TokError("unexpected token in '.include' directive");
2642 // Strip the quotes.
2643 Filename = Filename.substr(1, Filename.size()-2);
2645 // Attempt to switch the lexer to the included file before consuming the end
2646 // of statement to avoid losing it when we switch.
2647 if (EnterIncludeFile(Filename)) {
2648 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2655 /// ParseDirectiveIncbin
2656 /// ::= .incbin "filename"
2657 bool AsmParser::ParseDirectiveIncbin() {
2658 if (getLexer().isNot(AsmToken::String))
2659 return TokError("expected string in '.incbin' directive");
2661 std::string Filename = getTok().getString();
2662 SMLoc IncbinLoc = getLexer().getLoc();
2665 if (getLexer().isNot(AsmToken::EndOfStatement))
2666 return TokError("unexpected token in '.incbin' directive");
2668 // Strip the quotes.
2669 Filename = Filename.substr(1, Filename.size()-2);
2671 // Attempt to process the included file.
2672 if (ProcessIncbinFile(Filename)) {
2673 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2680 /// ParseDirectiveIf
2681 /// ::= .if expression
2682 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2683 TheCondStack.push_back(TheCondState);
2684 TheCondState.TheCond = AsmCond::IfCond;
2685 if (TheCondState.Ignore) {
2686 EatToEndOfStatement();
2689 if (ParseAbsoluteExpression(ExprValue))
2692 if (getLexer().isNot(AsmToken::EndOfStatement))
2693 return TokError("unexpected token in '.if' directive");
2697 TheCondState.CondMet = ExprValue;
2698 TheCondState.Ignore = !TheCondState.CondMet;
2704 /// ParseDirectiveIfb
2706 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2707 TheCondStack.push_back(TheCondState);
2708 TheCondState.TheCond = AsmCond::IfCond;
2710 if (TheCondState.Ignore) {
2711 EatToEndOfStatement();
2713 StringRef Str = ParseStringToEndOfStatement();
2715 if (getLexer().isNot(AsmToken::EndOfStatement))
2716 return TokError("unexpected token in '.ifb' directive");
2720 TheCondState.CondMet = ExpectBlank == Str.empty();
2721 TheCondState.Ignore = !TheCondState.CondMet;
2727 /// ParseDirectiveIfc
2728 /// ::= .ifc string1, string2
2729 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2730 TheCondStack.push_back(TheCondState);
2731 TheCondState.TheCond = AsmCond::IfCond;
2733 if (TheCondState.Ignore) {
2734 EatToEndOfStatement();
2736 StringRef Str1 = ParseStringToComma();
2738 if (getLexer().isNot(AsmToken::Comma))
2739 return TokError("unexpected token in '.ifc' directive");
2743 StringRef Str2 = ParseStringToEndOfStatement();
2745 if (getLexer().isNot(AsmToken::EndOfStatement))
2746 return TokError("unexpected token in '.ifc' directive");
2750 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2751 TheCondState.Ignore = !TheCondState.CondMet;
2757 /// ParseDirectiveIfdef
2758 /// ::= .ifdef symbol
2759 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2761 TheCondStack.push_back(TheCondState);
2762 TheCondState.TheCond = AsmCond::IfCond;
2764 if (TheCondState.Ignore) {
2765 EatToEndOfStatement();
2767 if (ParseIdentifier(Name))
2768 return TokError("expected identifier after '.ifdef'");
2772 MCSymbol *Sym = getContext().LookupSymbol(Name);
2775 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2777 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2778 TheCondState.Ignore = !TheCondState.CondMet;
2784 /// ParseDirectiveElseIf
2785 /// ::= .elseif expression
2786 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2787 if (TheCondState.TheCond != AsmCond::IfCond &&
2788 TheCondState.TheCond != AsmCond::ElseIfCond)
2789 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2791 TheCondState.TheCond = AsmCond::ElseIfCond;
2793 bool LastIgnoreState = false;
2794 if (!TheCondStack.empty())
2795 LastIgnoreState = TheCondStack.back().Ignore;
2796 if (LastIgnoreState || TheCondState.CondMet) {
2797 TheCondState.Ignore = true;
2798 EatToEndOfStatement();
2802 if (ParseAbsoluteExpression(ExprValue))
2805 if (getLexer().isNot(AsmToken::EndOfStatement))
2806 return TokError("unexpected token in '.elseif' directive");
2809 TheCondState.CondMet = ExprValue;
2810 TheCondState.Ignore = !TheCondState.CondMet;
2816 /// ParseDirectiveElse
2818 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2819 if (getLexer().isNot(AsmToken::EndOfStatement))
2820 return TokError("unexpected token in '.else' directive");
2824 if (TheCondState.TheCond != AsmCond::IfCond &&
2825 TheCondState.TheCond != AsmCond::ElseIfCond)
2826 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2828 TheCondState.TheCond = AsmCond::ElseCond;
2829 bool LastIgnoreState = false;
2830 if (!TheCondStack.empty())
2831 LastIgnoreState = TheCondStack.back().Ignore;
2832 if (LastIgnoreState || TheCondState.CondMet)
2833 TheCondState.Ignore = true;
2835 TheCondState.Ignore = false;
2840 /// ParseDirectiveEndIf
2842 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2843 if (getLexer().isNot(AsmToken::EndOfStatement))
2844 return TokError("unexpected token in '.endif' directive");
2848 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2849 TheCondStack.empty())
2850 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2852 if (!TheCondStack.empty()) {
2853 TheCondState = TheCondStack.back();
2854 TheCondStack.pop_back();
2860 void AsmParser::initializeDirectiveKindMapping() {
2861 DirectiveKindMapping[".set"] = DK_SET;
2862 DirectiveKindMapping[".equ"] = DK_EQU;
2863 DirectiveKindMapping[".equiv"] = DK_EQUIV;
2864 DirectiveKindMapping[".ascii"] = DK_ASCII;
2865 DirectiveKindMapping[".asciz"] = DK_ASCIZ;
2866 DirectiveKindMapping[".string"] = DK_STRING;
2867 DirectiveKindMapping[".byte"] = DK_BYTE;
2868 DirectiveKindMapping[".short"] = DK_SHORT;
2869 DirectiveKindMapping[".value"] = DK_VALUE;
2870 DirectiveKindMapping[".2byte"] = DK_2BYTE;
2871 DirectiveKindMapping[".long"] = DK_LONG;
2872 DirectiveKindMapping[".int"] = DK_INT;
2873 DirectiveKindMapping[".4byte"] = DK_4BYTE;
2874 DirectiveKindMapping[".quad"] = DK_QUAD;
2875 DirectiveKindMapping[".8byte"] = DK_8BYTE;
2876 DirectiveKindMapping[".single"] = DK_SINGLE;
2877 DirectiveKindMapping[".float"] = DK_FLOAT;
2878 DirectiveKindMapping[".double"] = DK_DOUBLE;
2879 DirectiveKindMapping[".align"] = DK_ALIGN;
2880 DirectiveKindMapping[".align32"] = DK_ALIGN32;
2881 DirectiveKindMapping[".balign"] = DK_BALIGN;
2882 DirectiveKindMapping[".balignw"] = DK_BALIGNW;
2883 DirectiveKindMapping[".balignl"] = DK_BALIGNL;
2884 DirectiveKindMapping[".p2align"] = DK_P2ALIGN;
2885 DirectiveKindMapping[".p2alignw"] = DK_P2ALIGNW;
2886 DirectiveKindMapping[".p2alignl"] = DK_P2ALIGNL;
2887 DirectiveKindMapping[".org"] = DK_ORG;
2888 DirectiveKindMapping[".fill"] = DK_FILL;
2889 DirectiveKindMapping[".zero"] = DK_ZERO;
2890 DirectiveKindMapping[".extern"] = DK_EXTERN;
2891 DirectiveKindMapping[".globl"] = DK_GLOBL;
2892 DirectiveKindMapping[".global"] = DK_GLOBAL;
2893 DirectiveKindMapping[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
2894 DirectiveKindMapping[".lazy_reference"] = DK_LAZY_REFERENCE;
2895 DirectiveKindMapping[".no_dead_strip"] = DK_NO_DEAD_STRIP;
2896 DirectiveKindMapping[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
2897 DirectiveKindMapping[".private_extern"] = DK_PRIVATE_EXTERN;
2898 DirectiveKindMapping[".reference"] = DK_REFERENCE;
2899 DirectiveKindMapping[".weak_definition"] = DK_WEAK_DEFINITION;
2900 DirectiveKindMapping[".weak_reference"] = DK_WEAK_REFERENCE;
2901 DirectiveKindMapping[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
2902 DirectiveKindMapping[".comm"] = DK_COMM;
2903 DirectiveKindMapping[".common"] = DK_COMMON;
2904 DirectiveKindMapping[".lcomm"] = DK_LCOMM;
2905 DirectiveKindMapping[".abort"] = DK_ABORT;
2906 DirectiveKindMapping[".include"] = DK_INCLUDE;
2907 DirectiveKindMapping[".incbin"] = DK_INCBIN;
2908 DirectiveKindMapping[".code16"] = DK_CODE16;
2909 DirectiveKindMapping[".code16gcc"] = DK_CODE16GCC;
2910 DirectiveKindMapping[".rept"] = DK_REPT;
2911 DirectiveKindMapping[".irp"] = DK_IRP;
2912 DirectiveKindMapping[".irpc"] = DK_IRPC;
2913 DirectiveKindMapping[".endr"] = DK_ENDR;
2914 DirectiveKindMapping[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
2915 DirectiveKindMapping[".bundle_lock"] = DK_BUNDLE_LOCK;
2916 DirectiveKindMapping[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
2917 DirectiveKindMapping[".if"] = DK_IF;
2918 DirectiveKindMapping[".ifb"] = DK_IFB;
2919 DirectiveKindMapping[".ifnb"] = DK_IFNB;
2920 DirectiveKindMapping[".ifc"] = DK_IFC;
2921 DirectiveKindMapping[".ifnc"] = DK_IFNC;
2922 DirectiveKindMapping[".ifdef"] = DK_IFDEF;
2923 DirectiveKindMapping[".ifndef"] = DK_IFNDEF;
2924 DirectiveKindMapping[".ifnotdef"] = DK_IFNOTDEF;
2925 DirectiveKindMapping[".elseif"] = DK_ELSEIF;
2926 DirectiveKindMapping[".else"] = DK_ELSE;
2927 DirectiveKindMapping[".endif"] = DK_ENDIF;
2930 /// ParseDirectiveFile
2931 /// ::= .file [number] filename
2932 /// ::= .file number directory filename
2933 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2934 // FIXME: I'm not sure what this is.
2935 int64_t FileNumber = -1;
2936 SMLoc FileNumberLoc = getLexer().getLoc();
2937 if (getLexer().is(AsmToken::Integer)) {
2938 FileNumber = getTok().getIntVal();
2942 return TokError("file number less than one");
2945 if (getLexer().isNot(AsmToken::String))
2946 return TokError("unexpected token in '.file' directive");
2948 // Usually the directory and filename together, otherwise just the directory.
2949 StringRef Path = getTok().getString();
2950 Path = Path.substr(1, Path.size()-2);
2953 StringRef Directory;
2955 if (getLexer().is(AsmToken::String)) {
2956 if (FileNumber == -1)
2957 return TokError("explicit path specified, but no file number");
2958 Filename = getTok().getString();
2959 Filename = Filename.substr(1, Filename.size()-2);
2966 if (getLexer().isNot(AsmToken::EndOfStatement))
2967 return TokError("unexpected token in '.file' directive");
2969 if (FileNumber == -1)
2970 getStreamer().EmitFileDirective(Filename);
2972 if (getContext().getGenDwarfForAssembly() == true)
2973 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2974 "used to generate dwarf debug info for assembly code");
2976 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2977 Error(FileNumberLoc, "file number already allocated");
2983 /// ParseDirectiveLine
2984 /// ::= .line [number]
2985 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2986 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2987 if (getLexer().isNot(AsmToken::Integer))
2988 return TokError("unexpected token in '.line' directive");
2990 int64_t LineNumber = getTok().getIntVal();
2994 // FIXME: Do something with the .line.
2997 if (getLexer().isNot(AsmToken::EndOfStatement))
2998 return TokError("unexpected token in '.line' directive");
3004 /// ParseDirectiveLoc
3005 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3006 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3007 /// The first number is a file number, must have been previously assigned with
3008 /// a .file directive, the second number is the line number and optionally the
3009 /// third number is a column position (zero if not specified). The remaining
3010 /// optional items are .loc sub-directives.
3011 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
3013 if (getLexer().isNot(AsmToken::Integer))
3014 return TokError("unexpected token in '.loc' directive");
3015 int64_t FileNumber = getTok().getIntVal();
3017 return TokError("file number less than one in '.loc' directive");
3018 if (!getContext().isValidDwarfFileNumber(FileNumber))
3019 return TokError("unassigned file number in '.loc' directive");
3022 int64_t LineNumber = 0;
3023 if (getLexer().is(AsmToken::Integer)) {
3024 LineNumber = getTok().getIntVal();
3026 return TokError("line number less than one in '.loc' directive");
3030 int64_t ColumnPos = 0;
3031 if (getLexer().is(AsmToken::Integer)) {
3032 ColumnPos = getTok().getIntVal();
3034 return TokError("column position less than zero in '.loc' directive");
3038 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3040 int64_t Discriminator = 0;
3041 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3043 if (getLexer().is(AsmToken::EndOfStatement))
3047 SMLoc Loc = getTok().getLoc();
3048 if (getParser().ParseIdentifier(Name))
3049 return TokError("unexpected token in '.loc' directive");
3051 if (Name == "basic_block")
3052 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3053 else if (Name == "prologue_end")
3054 Flags |= DWARF2_FLAG_PROLOGUE_END;
3055 else if (Name == "epilogue_begin")
3056 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3057 else if (Name == "is_stmt") {
3058 Loc = getTok().getLoc();
3059 const MCExpr *Value;
3060 if (getParser().ParseExpression(Value))
3062 // The expression must be the constant 0 or 1.
3063 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3064 int Value = MCE->getValue();
3066 Flags &= ~DWARF2_FLAG_IS_STMT;
3067 else if (Value == 1)
3068 Flags |= DWARF2_FLAG_IS_STMT;
3070 return Error(Loc, "is_stmt value not 0 or 1");
3073 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3076 else if (Name == "isa") {
3077 Loc = getTok().getLoc();
3078 const MCExpr *Value;
3079 if (getParser().ParseExpression(Value))
3081 // The expression must be a constant greater or equal to 0.
3082 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3083 int Value = MCE->getValue();
3085 return Error(Loc, "isa number less than zero");
3089 return Error(Loc, "isa number not a constant value");
3092 else if (Name == "discriminator") {
3093 if (getParser().ParseAbsoluteExpression(Discriminator))
3097 return Error(Loc, "unknown sub-directive in '.loc' directive");
3100 if (getLexer().is(AsmToken::EndOfStatement))
3105 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3106 Isa, Discriminator, StringRef());
3111 /// ParseDirectiveStabs
3112 /// ::= .stabs string, number, number, number
3113 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
3114 SMLoc DirectiveLoc) {
3115 return TokError("unsupported directive '" + Directive + "'");
3118 /// ParseDirectiveSpace
3119 /// ::= .space expression [ , expression ]
3120 bool GenericAsmParser::ParseDirectiveSpace(StringRef, SMLoc DirectiveLoc) {
3121 getParser().CheckForValidSection();
3124 if (getParser().ParseAbsoluteExpression(NumBytes))
3127 int64_t FillExpr = 0;
3128 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3129 if (getLexer().isNot(AsmToken::Comma))
3130 return TokError("unexpected token in '.space' directive");
3133 if (getParser().ParseAbsoluteExpression(FillExpr))
3136 if (getLexer().isNot(AsmToken::EndOfStatement))
3137 return TokError("unexpected token in '.space' directive");
3143 return TokError("invalid number of bytes in '.space' directive");
3145 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3146 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3151 /// ParseDirectiveCFISections
3152 /// ::= .cfi_sections section [, section]
3153 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
3154 SMLoc DirectiveLoc) {
3159 if (getParser().ParseIdentifier(Name))
3160 return TokError("Expected an identifier");
3162 if (Name == ".eh_frame")
3164 else if (Name == ".debug_frame")
3167 if (getLexer().is(AsmToken::Comma)) {
3170 if (getParser().ParseIdentifier(Name))
3171 return TokError("Expected an identifier");
3173 if (Name == ".eh_frame")
3175 else if (Name == ".debug_frame")
3179 getStreamer().EmitCFISections(EH, Debug);
3184 /// ParseDirectiveCFIStartProc
3185 /// ::= .cfi_startproc
3186 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
3187 SMLoc DirectiveLoc) {
3188 getStreamer().EmitCFIStartProc();
3192 /// ParseDirectiveCFIEndProc
3193 /// ::= .cfi_endproc
3194 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
3195 getStreamer().EmitCFIEndProc();
3199 /// ParseRegisterOrRegisterNumber - parse register name or number.
3200 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3201 SMLoc DirectiveLoc) {
3204 if (getLexer().isNot(AsmToken::Integer)) {
3205 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3208 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
3210 return getParser().ParseAbsoluteExpression(Register);
3215 /// ParseDirectiveCFIDefCfa
3216 /// ::= .cfi_def_cfa register, offset
3217 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3218 SMLoc DirectiveLoc) {
3219 int64_t Register = 0;
3220 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3223 if (getLexer().isNot(AsmToken::Comma))
3224 return TokError("unexpected token in directive");
3228 if (getParser().ParseAbsoluteExpression(Offset))
3231 getStreamer().EmitCFIDefCfa(Register, Offset);
3235 /// ParseDirectiveCFIDefCfaOffset
3236 /// ::= .cfi_def_cfa_offset offset
3237 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3238 SMLoc DirectiveLoc) {
3240 if (getParser().ParseAbsoluteExpression(Offset))
3243 getStreamer().EmitCFIDefCfaOffset(Offset);
3247 /// ParseDirectiveCFIAdjustCfaOffset
3248 /// ::= .cfi_adjust_cfa_offset adjustment
3249 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3250 SMLoc DirectiveLoc) {
3251 int64_t Adjustment = 0;
3252 if (getParser().ParseAbsoluteExpression(Adjustment))
3255 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3259 /// ParseDirectiveCFIDefCfaRegister
3260 /// ::= .cfi_def_cfa_register register
3261 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3262 SMLoc DirectiveLoc) {
3263 int64_t Register = 0;
3264 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3267 getStreamer().EmitCFIDefCfaRegister(Register);
3271 /// ParseDirectiveCFIOffset
3272 /// ::= .cfi_offset register, offset
3273 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3274 int64_t Register = 0;
3277 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3280 if (getLexer().isNot(AsmToken::Comma))
3281 return TokError("unexpected token in directive");
3284 if (getParser().ParseAbsoluteExpression(Offset))
3287 getStreamer().EmitCFIOffset(Register, Offset);
3291 /// ParseDirectiveCFIRelOffset
3292 /// ::= .cfi_rel_offset register, offset
3293 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3294 SMLoc DirectiveLoc) {
3295 int64_t Register = 0;
3297 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3300 if (getLexer().isNot(AsmToken::Comma))
3301 return TokError("unexpected token in directive");
3305 if (getParser().ParseAbsoluteExpression(Offset))
3308 getStreamer().EmitCFIRelOffset(Register, Offset);
3312 static bool isValidEncoding(int64_t Encoding) {
3313 if (Encoding & ~0xff)
3316 if (Encoding == dwarf::DW_EH_PE_omit)
3319 const unsigned Format = Encoding & 0xf;
3320 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3321 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3322 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3323 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3326 const unsigned Application = Encoding & 0x70;
3327 if (Application != dwarf::DW_EH_PE_absptr &&
3328 Application != dwarf::DW_EH_PE_pcrel)
3334 /// ParseDirectiveCFIPersonalityOrLsda
3335 /// ::= .cfi_personality encoding, [symbol_name]
3336 /// ::= .cfi_lsda encoding, [symbol_name]
3337 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
3338 SMLoc DirectiveLoc) {
3339 int64_t Encoding = 0;
3340 if (getParser().ParseAbsoluteExpression(Encoding))
3342 if (Encoding == dwarf::DW_EH_PE_omit)
3345 if (!isValidEncoding(Encoding))
3346 return TokError("unsupported encoding.");
3348 if (getLexer().isNot(AsmToken::Comma))
3349 return TokError("unexpected token in directive");
3353 if (getParser().ParseIdentifier(Name))
3354 return TokError("expected identifier in directive");
3356 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3358 if (IDVal == ".cfi_personality")
3359 getStreamer().EmitCFIPersonality(Sym, Encoding);
3361 assert(IDVal == ".cfi_lsda");
3362 getStreamer().EmitCFILsda(Sym, Encoding);
3367 /// ParseDirectiveCFIRememberState
3368 /// ::= .cfi_remember_state
3369 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3370 SMLoc DirectiveLoc) {
3371 getStreamer().EmitCFIRememberState();
3375 /// ParseDirectiveCFIRestoreState
3376 /// ::= .cfi_remember_state
3377 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3378 SMLoc DirectiveLoc) {
3379 getStreamer().EmitCFIRestoreState();
3383 /// ParseDirectiveCFISameValue
3384 /// ::= .cfi_same_value register
3385 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3386 SMLoc DirectiveLoc) {
3387 int64_t Register = 0;
3389 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3392 getStreamer().EmitCFISameValue(Register);
3397 /// ParseDirectiveCFIRestore
3398 /// ::= .cfi_restore register
3399 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
3400 SMLoc DirectiveLoc) {
3401 int64_t Register = 0;
3402 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3405 getStreamer().EmitCFIRestore(Register);
3410 /// ParseDirectiveCFIEscape
3411 /// ::= .cfi_escape expression[,...]
3412 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3413 SMLoc DirectiveLoc) {
3416 if (getParser().ParseAbsoluteExpression(CurrValue))
3419 Values.push_back((uint8_t)CurrValue);
3421 while (getLexer().is(AsmToken::Comma)) {
3424 if (getParser().ParseAbsoluteExpression(CurrValue))
3427 Values.push_back((uint8_t)CurrValue);
3430 getStreamer().EmitCFIEscape(Values);
3434 /// ParseDirectiveCFISignalFrame
3435 /// ::= .cfi_signal_frame
3436 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3437 SMLoc DirectiveLoc) {
3438 if (getLexer().isNot(AsmToken::EndOfStatement))
3439 return Error(getLexer().getLoc(),
3440 "unexpected token in '" + Directive + "' directive");
3442 getStreamer().EmitCFISignalFrame();
3447 /// ParseDirectiveCFIUndefined
3448 /// ::= .cfi_undefined register
3449 bool GenericAsmParser::ParseDirectiveCFIUndefined(StringRef Directive,
3450 SMLoc DirectiveLoc) {
3451 int64_t Register = 0;
3453 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3456 getStreamer().EmitCFIUndefined(Register);
3461 /// ParseDirectiveCFIRegister
3462 /// ::= .cfi_register register, register
3463 bool GenericAsmParser::ParseDirectiveCFIRegister(StringRef Directive,
3464 SMLoc DirectiveLoc) {
3465 int64_t Register1 = 0;
3467 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3470 if (getLexer().isNot(AsmToken::Comma))
3471 return TokError("unexpected token in directive");
3474 int64_t Register2 = 0;
3476 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3479 getStreamer().EmitCFIRegister(Register1, Register2);
3484 /// ParseDirectiveMacrosOnOff
3487 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3488 SMLoc DirectiveLoc) {
3489 if (getLexer().isNot(AsmToken::EndOfStatement))
3490 return Error(getLexer().getLoc(),
3491 "unexpected token in '" + Directive + "' directive");
3493 getParser().MacrosEnabled = Directive == ".macros_on";
3498 /// ParseDirectiveMacro
3499 /// ::= .macro name [parameters]
3500 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3501 SMLoc DirectiveLoc) {
3503 if (getParser().ParseIdentifier(Name))
3504 return TokError("expected identifier in '.macro' directive");
3506 MacroParameters Parameters;
3507 // Argument delimiter is initially unknown. It will be set by
3508 // ParseMacroArgument()
3509 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3510 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3512 MacroParameter Parameter;
3513 if (getParser().ParseIdentifier(Parameter.first))
3514 return TokError("expected identifier in '.macro' directive");
3516 if (getLexer().is(AsmToken::Equal)) {
3518 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3522 Parameters.push_back(Parameter);
3524 if (getLexer().is(AsmToken::Comma))
3526 else if (getLexer().is(AsmToken::EndOfStatement))
3531 // Eat the end of statement.
3534 AsmToken EndToken, StartToken = getTok();
3536 // Lex the macro definition.
3538 // Check whether we have reached the end of the file.
3539 if (getLexer().is(AsmToken::Eof))
3540 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3542 // Otherwise, check whether we have reach the .endmacro.
3543 if (getLexer().is(AsmToken::Identifier) &&
3544 (getTok().getIdentifier() == ".endm" ||
3545 getTok().getIdentifier() == ".endmacro")) {
3546 EndToken = getTok();
3548 if (getLexer().isNot(AsmToken::EndOfStatement))
3549 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3554 // Otherwise, scan til the end of the statement.
3555 getParser().EatToEndOfStatement();
3558 if (getParser().MacroMap.lookup(Name)) {
3559 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3562 const char *BodyStart = StartToken.getLoc().getPointer();
3563 const char *BodyEnd = EndToken.getLoc().getPointer();
3564 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3565 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3569 /// ParseDirectiveEndMacro
3572 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3573 SMLoc DirectiveLoc) {
3574 if (getLexer().isNot(AsmToken::EndOfStatement))
3575 return TokError("unexpected token in '" + Directive + "' directive");
3577 // If we are inside a macro instantiation, terminate the current
3579 if (!getParser().ActiveMacros.empty()) {
3580 getParser().HandleMacroExit();
3584 // Otherwise, this .endmacro is a stray entry in the file; well formed
3585 // .endmacro directives are handled during the macro definition parsing.
3586 return TokError("unexpected '" + Directive + "' in file, "
3587 "no current macro definition");
3590 /// ParseDirectivePurgeMacro
3592 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3593 SMLoc DirectiveLoc) {
3595 if (getParser().ParseIdentifier(Name))
3596 return TokError("expected identifier in '.purgem' directive");
3598 if (getLexer().isNot(AsmToken::EndOfStatement))
3599 return TokError("unexpected token in '.purgem' directive");
3601 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3602 if (I == getParser().MacroMap.end())
3603 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3605 // Undefine the macro.
3606 delete I->getValue();
3607 getParser().MacroMap.erase(I);
3611 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3612 getParser().CheckForValidSection();
3614 const MCExpr *Value;
3616 if (getParser().ParseExpression(Value))
3619 if (getLexer().isNot(AsmToken::EndOfStatement))
3620 return TokError("unexpected token in directive");
3622 if (DirName[1] == 's')
3623 getStreamer().EmitSLEB128Value(Value);
3625 getStreamer().EmitULEB128Value(Value);
3630 Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3631 AsmToken EndToken, StartToken = getTok();
3633 unsigned NestLevel = 0;
3635 // Check whether we have reached the end of the file.
3636 if (getLexer().is(AsmToken::Eof)) {
3637 Error(DirectiveLoc, "no matching '.endr' in definition");
3641 if (Lexer.is(AsmToken::Identifier) &&
3642 (getTok().getIdentifier() == ".rept")) {
3646 // Otherwise, check whether we have reached the .endr.
3647 if (Lexer.is(AsmToken::Identifier) &&
3648 getTok().getIdentifier() == ".endr") {
3649 if (NestLevel == 0) {
3650 EndToken = getTok();
3652 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3653 TokError("unexpected token in '.endr' directive");
3661 // Otherwise, scan till the end of the statement.
3662 EatToEndOfStatement();
3665 const char *BodyStart = StartToken.getLoc().getPointer();
3666 const char *BodyEnd = EndToken.getLoc().getPointer();
3667 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3669 // We Are Anonymous.
3671 MacroParameters Parameters;
3672 return new Macro(Name, Body, Parameters);
3675 void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3676 raw_svector_ostream &OS) {
3679 MemoryBuffer *Instantiation =
3680 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3682 // Create the macro instantiation object and add to the current macro
3683 // instantiation stack.
3684 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3688 ActiveMacros.push_back(MI);
3690 // Jump to the macro instantiation and prime the lexer.
3691 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3692 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3696 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3698 if (ParseAbsoluteExpression(Count))
3699 return TokError("unexpected token in '.rept' directive");
3702 return TokError("Count is negative");
3704 if (Lexer.isNot(AsmToken::EndOfStatement))
3705 return TokError("unexpected token in '.rept' directive");
3707 // Eat the end of statement.
3710 // Lex the rept definition.
3711 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3715 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3716 // to hold the macro body with substitutions.
3717 SmallString<256> Buf;
3718 MacroParameters Parameters;
3720 raw_svector_ostream OS(Buf);
3722 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3725 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3730 /// ParseDirectiveIrp
3731 /// ::= .irp symbol,values
3732 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3733 MacroParameters Parameters;
3734 MacroParameter Parameter;
3736 if (ParseIdentifier(Parameter.first))
3737 return TokError("expected identifier in '.irp' directive");
3739 Parameters.push_back(Parameter);
3741 if (Lexer.isNot(AsmToken::Comma))
3742 return TokError("expected comma in '.irp' directive");
3747 if (ParseMacroArguments(0, A))
3750 // Eat the end of statement.
3753 // Lex the irp definition.
3754 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3758 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3759 // to hold the macro body with substitutions.
3760 SmallString<256> Buf;
3761 raw_svector_ostream OS(Buf);
3763 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3764 MacroArguments Args;
3767 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3771 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3776 /// ParseDirectiveIrpc
3777 /// ::= .irpc symbol,values
3778 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3779 MacroParameters Parameters;
3780 MacroParameter Parameter;
3782 if (ParseIdentifier(Parameter.first))
3783 return TokError("expected identifier in '.irpc' directive");
3785 Parameters.push_back(Parameter);
3787 if (Lexer.isNot(AsmToken::Comma))
3788 return TokError("expected comma in '.irpc' directive");
3793 if (ParseMacroArguments(0, A))
3796 if (A.size() != 1 || A.front().size() != 1)
3797 return TokError("unexpected token in '.irpc' directive");
3799 // Eat the end of statement.
3802 // Lex the irpc definition.
3803 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3807 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3808 // to hold the macro body with substitutions.
3809 SmallString<256> Buf;
3810 raw_svector_ostream OS(Buf);
3812 StringRef Values = A.front().front().getString();
3813 std::size_t I, End = Values.size();
3814 for (I = 0; I < End; ++I) {
3816 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3818 MacroArguments Args;
3819 Args.push_back(Arg);
3821 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3825 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3830 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3831 if (ActiveMacros.empty())
3832 return TokError("unmatched '.endr' directive");
3834 // The only .repl that should get here are the ones created by
3835 // InstantiateMacroLikeBody.
3836 assert(getLexer().is(AsmToken::EndOfStatement));
3842 bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3843 const MCExpr *Value;
3844 SMLoc ExprLoc = getLexer().getLoc();
3845 if (ParseExpression(Value))
3847 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3849 return Error(ExprLoc, "unexpected expression in _emit");
3850 uint64_t IntValue = MCE->getValue();
3851 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3852 return Error(ExprLoc, "literal value out of range for directive");
3854 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3858 bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3859 unsigned &NumOutputs, unsigned &NumInputs,
3860 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
3861 SmallVectorImpl<std::string> &Constraints,
3862 SmallVectorImpl<std::string> &Clobbers,
3863 const MCInstrInfo *MII,
3864 const MCInstPrinter *IP,
3865 MCAsmParserSemaCallback &SI) {
3866 SmallVector<void *, 4> InputDecls;
3867 SmallVector<void *, 4> OutputDecls;
3868 SmallVector<bool, 4> InputDeclsAddressOf;
3869 SmallVector<bool, 4> OutputDeclsAddressOf;
3870 SmallVector<std::string, 4> InputConstraints;
3871 SmallVector<std::string, 4> OutputConstraints;
3872 std::set<std::string> ClobberRegs;
3874 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
3879 // While we have input, parse each statement.
3880 unsigned InputIdx = 0;
3881 unsigned OutputIdx = 0;
3882 while (getLexer().isNot(AsmToken::Eof)) {
3883 ParseStatementInfo Info(&AsmStrRewrites);
3884 if (ParseStatement(Info))
3887 if (Info.ParseError)
3890 if (Info.Opcode != ~0U) {
3891 const MCInstrDesc &Desc = MII->get(Info.Opcode);
3893 // Build the list of clobbers, outputs and inputs.
3894 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3895 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
3898 if (Operand->isImm()) {
3899 if (Operand->needAsmRewrite())
3900 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3901 Operand->getStartLoc()));
3905 // Register operand.
3906 if (Operand->isReg() && !Operand->needAddressOf()) {
3907 unsigned NumDefs = Desc.getNumDefs();
3909 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3911 raw_string_ostream OS(Reg);
3912 IP->printRegName(OS, Operand->getReg());
3913 ClobberRegs.insert(StringRef(OS.str()));
3918 // Expr/Input or Output.
3921 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3924 bool isOutput = (i == 1) && Desc.mayStore();
3925 if (Operand->isMem() && Operand->needSizeDirective())
3926 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
3927 Operand->getStartLoc(),
3929 Operand->getMemSize()));
3931 std::string Constraint = "=";
3933 OutputDecls.push_back(OpDecl);
3934 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
3935 Constraint += Operand->getConstraint().str();
3936 OutputConstraints.push_back(Constraint);
3937 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
3938 Operand->getStartLoc(),
3939 Operand->getNameLen()));
3941 InputDecls.push_back(OpDecl);
3942 InputDeclsAddressOf.push_back(Operand->needAddressOf());
3943 InputConstraints.push_back(Operand->getConstraint().str());
3944 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
3945 Operand->getStartLoc(),
3946 Operand->getNameLen()));
3953 // Set the number of Outputs and Inputs.
3954 NumOutputs = OutputDecls.size();
3955 NumInputs = InputDecls.size();
3957 // Set the unique clobbers.
3958 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3959 E = ClobberRegs.end(); I != E; ++I)
3960 Clobbers.push_back(*I);
3962 // Merge the various outputs and inputs. Output are expected first.
3963 if (NumOutputs || NumInputs) {
3964 unsigned NumExprs = NumOutputs + NumInputs;
3965 OpDecls.resize(NumExprs);
3966 Constraints.resize(NumExprs);
3967 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3968 // constraint for addressof. This needs to be cleaned up!
3969 for (unsigned i = 0; i < NumOutputs; ++i) {
3970 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
3971 Constraints[i] = OutputDeclsAddressOf[i] ? "=r" : OutputConstraints[i];
3973 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
3974 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
3975 Constraints[j] = InputDeclsAddressOf[i] ? "r" : InputConstraints[i];
3979 // Build the IR assembly string.
3980 std::string AsmStringIR;
3981 AsmRewriteKind PrevKind = AOK_Imm;
3982 raw_string_ostream OS(AsmStringIR);
3983 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
3984 for (SmallVectorImpl<struct AsmRewrite>::iterator
3985 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3986 const char *Loc = (*I).Loc.getPointer();
3988 AsmRewriteKind Kind = (*I).Kind;
3990 // Emit everything up to the immediate/expression. If the previous rewrite
3991 // was a size directive, then this has already been done.
3992 if (PrevKind != AOK_SizeDirective)
3993 OS << StringRef(Start, Loc - Start);
3996 // Skip the original expression.
3997 if (Kind == AOK_Skip) {
3998 Start = Loc + (*I).Len;
4002 // Rewrite expressions in $N notation.
4020 case AOK_SizeDirective:
4023 case 8: OS << "byte ptr "; break;
4024 case 16: OS << "word ptr "; break;
4025 case 32: OS << "dword ptr "; break;
4026 case 64: OS << "qword ptr "; break;
4027 case 80: OS << "xword ptr "; break;
4028 case 128: OS << "xmmword ptr "; break;
4029 case 256: OS << "ymmword ptr "; break;
4035 case AOK_DotOperator:
4040 // Skip the original expression.
4041 if (Kind != AOK_SizeDirective)
4042 Start = Loc + (*I).Len;
4045 // Emit the remainder of the asm string.
4046 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4047 if (Start != AsmEnd)
4048 OS << StringRef(Start, AsmEnd - Start);
4050 AsmString = OS.str();
4054 /// \brief Create an MCAsmParser instance.
4055 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
4056 MCContext &C, MCStreamer &Out,
4057 const MCAsmInfo &MAI) {
4058 return new AsmParser(SM, C, Out, MAI);