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() {}
54 /// \brief Helper class for storing information about an active macro
56 struct MacroInstantiation {
57 /// The macro being instantiated.
58 const MCAsmMacro *TheMacro;
60 /// The macro instantiation with substitutions.
61 MemoryBuffer *Instantiation;
63 /// The location of the instantiation.
64 SMLoc InstantiationLoc;
66 /// The buffer where parsing should resume upon instantiation completion.
69 /// The location where parsing should resume upon instantiation completion.
73 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
78 struct ParseStatementInfo {
79 /// ParsedOperands - The parsed operands from the last parsed statement.
80 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
82 /// Opcode - The opcode from the last parsed instruction.
85 /// Error - Was there an error parsing the inline assembly?
88 SmallVectorImpl<AsmRewrite> *AsmRewrites;
90 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
91 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
92 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
94 ~ParseStatementInfo() {
95 // Free any parsed operands.
96 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
97 delete ParsedOperands[i];
98 ParsedOperands.clear();
102 /// \brief The concrete assembly parser instance.
103 class AsmParser : public MCAsmParser {
104 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
105 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
110 const MCAsmInfo &MAI;
112 SourceMgr::DiagHandlerTy SavedDiagHandler;
113 void *SavedDiagContext;
114 MCAsmParserExtension *GenericParser;
115 MCAsmParserExtension *PlatformParser;
117 /// This is the current buffer index we're lexing from as managed by the
118 /// SourceMgr object.
121 AsmCond TheCondState;
122 std::vector<AsmCond> TheCondStack;
124 /// DirectiveMap - This is a table handlers for directives. Each handler is
125 /// invoked after the directive identifier is read and is responsible for
126 /// parsing and validating the rest of the directive. The handler is passed
127 /// in the directive name and the location of the directive keyword.
128 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
130 /// MacroMap - Map of currently defined macros.
131 StringMap<MCAsmMacro*> MacroMap;
133 /// ActiveMacros - Stack of active macro instantiations.
134 std::vector<MacroInstantiation*> ActiveMacros;
136 /// Boolean tracking whether macro substitution is enabled.
137 unsigned MacrosEnabledFlag : 1;
139 /// Flag tracking whether any errors have been encountered.
140 unsigned HadError : 1;
142 /// The values from the last parsed cpp hash file line comment if any.
143 StringRef CppHashFilename;
144 int64_t CppHashLineNumber;
148 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
149 unsigned AssemblerDialect;
151 /// IsDarwin - is Darwin compatibility enabled?
154 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
155 bool ParsingInlineAsm;
158 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
159 const MCAsmInfo &MAI);
160 virtual ~AsmParser();
162 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
164 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
166 DirectiveHandler Handler) {
167 DirectiveMap[Directive] = std::make_pair(Object, Handler);
171 /// @name MCAsmParser Interface
174 virtual SourceMgr &getSourceManager() { return SrcMgr; }
175 virtual MCAsmLexer &getLexer() { return Lexer; }
176 virtual MCContext &getContext() { return Ctx; }
177 virtual MCStreamer &getStreamer() { return Out; }
178 virtual unsigned getAssemblerDialect() {
179 if (AssemblerDialect == ~0U)
180 return MAI.getAssemblerDialect();
182 return AssemblerDialect;
184 virtual void setAssemblerDialect(unsigned i) {
185 AssemblerDialect = i;
188 virtual bool Warning(SMLoc L, const Twine &Msg,
189 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
190 virtual bool Error(SMLoc L, const Twine &Msg,
191 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
193 virtual const AsmToken &Lex();
195 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
196 bool isParsingInlineAsm() { return ParsingInlineAsm; }
198 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
199 unsigned &NumOutputs, unsigned &NumInputs,
200 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
201 SmallVectorImpl<std::string> &Constraints,
202 SmallVectorImpl<std::string> &Clobbers,
203 const MCInstrInfo *MII,
204 const MCInstPrinter *IP,
205 MCAsmParserSemaCallback &SI);
207 bool ParseExpression(const MCExpr *&Res);
208 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
209 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
210 virtual bool ParseAbsoluteExpression(int64_t &Res);
212 bool ParseMacroArgument(MCAsmMacroArgument &MA,
213 AsmToken::TokenKind &ArgumentDelimiter);
215 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
216 /// and set \p Res to the identifier contents.
217 virtual bool ParseIdentifier(StringRef &Res);
218 virtual void EatToEndOfStatement();
220 virtual bool MacrosEnabled() {return MacrosEnabledFlag;}
221 virtual void SetMacrosEnabled(bool flag) {MacrosEnabledFlag = flag;}
223 virtual const MCAsmMacro* LookupMacro(StringRef Name);
224 virtual void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
225 virtual void UndefineMacro(StringRef Name);
227 virtual bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
228 virtual bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
229 void HandleMacroExit();
231 virtual void CheckForValidSection();
236 bool ParseStatement(ParseStatementInfo &Info);
237 void EatToEndOfLine();
238 bool ParseCppHashLineFilenameComment(const SMLoc &L);
240 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
241 const MCAsmMacroParameters &Parameters,
242 const MCAsmMacroArguments &A,
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 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
268 /// \brief Parse up to the end of statement and a return the contents from the
269 /// current token until the end of the statement; the current token on exit
270 /// will be either the EndOfStatement or EOF.
271 virtual StringRef ParseStringToEndOfStatement();
273 /// \brief Parse until the end of a statement or a comma is encountered,
274 /// return the contents from the current token up to the end or comma.
275 StringRef ParseStringToComma();
277 bool ParseAssignment(StringRef Name, bool allow_redef,
278 bool NoDeadStrip = false);
280 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
281 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
282 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
283 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
285 // Directive Parsing.
288 DK_NO_DIRECTIVE, // Placeholder
289 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
290 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
291 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
292 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
293 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
294 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
295 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
296 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
297 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
298 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
299 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
300 DK_ELSEIF, DK_ELSE, DK_ENDIF
303 StringMap<DirectiveKind> DirectiveKindMapping;
305 // ".ascii", ".asciz", ".string"
306 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
307 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
308 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
309 bool ParseDirectiveFill(); // ".fill"
310 bool ParseDirectiveZero(); // ".zero"
311 // ".set", ".equ", ".equiv"
312 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
313 bool ParseDirectiveOrg(); // ".org"
314 // ".align{,32}", ".p2align{,w,l}"
315 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
317 // ".bundle_align_mode"
318 bool ParseDirectiveBundleAlignMode();
320 bool ParseDirectiveBundleLock();
322 bool ParseDirectiveBundleUnlock();
324 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
325 /// accepts a single symbol (which should be a label or an external).
326 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
328 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
330 bool ParseDirectiveAbort(); // ".abort"
331 bool ParseDirectiveInclude(); // ".include"
332 bool ParseDirectiveIncbin(); // ".incbin"
334 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
335 // ".ifb" or ".ifnb", depending on ExpectBlank.
336 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
337 // ".ifc" or ".ifnc", depending on ExpectEqual.
338 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
339 // ".ifdef" or ".ifndef", depending on expect_defined
340 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
341 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
342 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
343 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
345 /// ParseEscapedString - Parse the current token as a string which may include
346 /// escaped characters and return the string contents.
347 bool ParseEscapedString(std::string &Data);
349 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
350 MCSymbolRefExpr::VariantKind Variant);
352 // Macro-like directives
353 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
354 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
355 raw_svector_ostream &OS);
356 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
357 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
358 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
359 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
362 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
364 void initializeDirectiveKindMapping();
367 /// \brief Generic implementation of directive handling, etc. which is shared
368 /// (or the default, at least) for all assembler parsers.
369 class GenericAsmParser : public MCAsmParserExtension {
370 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
371 void AddDirectiveHandler(StringRef Directive) {
372 getParser().AddDirectiveHandler(this, Directive,
373 HandleDirective<GenericAsmParser, Handler>);
376 GenericAsmParser() {}
378 AsmParser &getParser() {
379 return (AsmParser&) this->MCAsmParserExtension::getParser();
382 virtual void Initialize(MCAsmParser &Parser) {
383 // Call the base implementation.
384 this->MCAsmParserExtension::Initialize(Parser);
386 // Debugging directives.
387 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
388 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
389 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
390 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
392 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveSpace>(".space");
393 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveSpace>(".skip");
396 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
398 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
400 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
402 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
404 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
405 ".cfi_def_cfa_offset");
406 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
407 ".cfi_adjust_cfa_offset");
408 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
409 ".cfi_def_cfa_register");
410 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
412 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
415 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
417 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
419 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
421 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
423 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
425 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
427 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
429 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
431 &GenericAsmParser::ParseDirectiveCFIUndefined>(".cfi_undefined");
433 &GenericAsmParser::ParseDirectiveCFIRegister>(".cfi_register");
436 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
438 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
440 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
441 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
442 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
443 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
445 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
446 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
449 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
451 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
452 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
453 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
454 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
455 bool ParseDirectiveSpace(StringRef, SMLoc DirectiveLoc);
456 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
457 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
458 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
459 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
460 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
461 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
462 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
463 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
464 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
465 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
466 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
467 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
468 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
469 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
470 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
471 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
472 bool ParseDirectiveCFIUndefined(StringRef, SMLoc DirectiveLoc);
473 bool ParseDirectiveCFIRegister(StringRef, SMLoc DirectiveLoc);
475 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
476 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
477 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
478 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
480 bool ParseDirectiveLEB128(StringRef, SMLoc);
487 extern MCAsmParserExtension *createDarwinAsmParser();
488 extern MCAsmParserExtension *createELFAsmParser();
489 extern MCAsmParserExtension *createCOFFAsmParser();
493 enum { DEFAULT_ADDRSPACE = 0 };
495 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
496 MCStreamer &_Out, const MCAsmInfo &_MAI)
497 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
498 GenericParser(new GenericAsmParser), PlatformParser(0),
499 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
500 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
501 // Save the old handler.
502 SavedDiagHandler = SrcMgr.getDiagHandler();
503 SavedDiagContext = SrcMgr.getDiagContext();
504 // Set our own handler which calls the saved handler.
505 SrcMgr.setDiagHandler(DiagHandler, this);
506 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
508 // Initialize the generic parser.
509 GenericParser->Initialize(*this);
511 // Initialize the platform / file format parser.
513 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
515 if (_MAI.hasMicrosoftFastStdCallMangling()) {
516 PlatformParser = createCOFFAsmParser();
517 PlatformParser->Initialize(*this);
518 } else if (_MAI.hasSubsectionsViaSymbols()) {
519 PlatformParser = createDarwinAsmParser();
520 PlatformParser->Initialize(*this);
523 PlatformParser = createELFAsmParser();
524 PlatformParser->Initialize(*this);
527 initializeDirectiveKindMapping();
530 AsmParser::~AsmParser() {
531 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
533 // Destroy any macros.
534 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
535 ie = MacroMap.end(); it != ie; ++it)
536 delete it->getValue();
538 delete PlatformParser;
539 delete GenericParser;
542 void AsmParser::PrintMacroInstantiations() {
543 // Print the active macro instantiation stack.
544 for (std::vector<MacroInstantiation*>::const_reverse_iterator
545 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
546 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
547 "while in macro instantiation");
550 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
551 if (FatalAssemblerWarnings)
552 return Error(L, Msg, Ranges);
553 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
554 PrintMacroInstantiations();
558 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
560 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
561 PrintMacroInstantiations();
565 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
566 std::string IncludedFile;
567 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
573 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
578 /// Process the specified .incbin file by seaching for it in the include paths
579 /// then just emitting the byte contents of the file to the streamer. This
580 /// returns true on failure.
581 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
582 std::string IncludedFile;
583 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
587 // Pick up the bytes from the file and emit them.
588 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
593 void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
594 if (InBuffer != -1) {
595 CurBuffer = InBuffer;
597 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
599 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
602 const AsmToken &AsmParser::Lex() {
603 const AsmToken *tok = &Lexer.Lex();
605 if (tok->is(AsmToken::Eof)) {
606 // If this is the end of an included file, pop the parent file off the
608 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
609 if (ParentIncludeLoc != SMLoc()) {
610 JumpToLoc(ParentIncludeLoc);
615 if (tok->is(AsmToken::Error))
616 Error(Lexer.getErrLoc(), Lexer.getErr());
621 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
622 // Create the initial section, if requested.
623 if (!NoInitialTextSection)
630 AsmCond StartingCondState = TheCondState;
632 // If we are generating dwarf for assembly source files save the initial text
633 // section and generate a .file directive.
634 if (getContext().getGenDwarfForAssembly()) {
635 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
636 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
637 getStreamer().EmitLabel(SectionStartSym);
638 getContext().setGenDwarfSectionStartSym(SectionStartSym);
639 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
641 getContext().getMainFileName());
644 // While we have input, parse each statement.
645 while (Lexer.isNot(AsmToken::Eof)) {
646 ParseStatementInfo Info;
647 if (!ParseStatement(Info)) continue;
649 // We had an error, validate that one was emitted and recover by skipping to
651 assert(HadError && "Parse statement returned an error, but none emitted!");
652 EatToEndOfStatement();
655 if (TheCondState.TheCond != StartingCondState.TheCond ||
656 TheCondState.Ignore != StartingCondState.Ignore)
657 return TokError("unmatched .ifs or .elses");
659 // Check to see there are no empty DwarfFile slots.
660 const std::vector<MCDwarfFile *> &MCDwarfFiles =
661 getContext().getMCDwarfFiles();
662 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
663 if (!MCDwarfFiles[i])
664 TokError("unassigned file number: " + Twine(i) + " for .file directives");
667 // Check to see that all assembler local symbols were actually defined.
668 // Targets that don't do subsections via symbols may not want this, though,
669 // so conservatively exclude them. Only do this if we're finalizing, though,
670 // as otherwise we won't necessarilly have seen everything yet.
671 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
672 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
673 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
676 MCSymbol *Sym = i->getValue();
677 // Variable symbols may not be marked as defined, so check those
678 // explicitly. If we know it's a variable, we have a definition for
679 // the purposes of this check.
680 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
681 // FIXME: We would really like to refer back to where the symbol was
682 // first referenced for a source location. We need to add something
683 // to track that. Currently, we just point to the end of the file.
684 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
685 "assembler local symbol '" + Sym->getName() +
691 // Finalize the output stream if there are no errors and if the client wants
693 if (!HadError && !NoFinalize)
699 void AsmParser::CheckForValidSection() {
700 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
701 TokError("expected section directive before assembly directive");
702 Out.InitToTextSection();
706 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
707 void AsmParser::EatToEndOfStatement() {
708 while (Lexer.isNot(AsmToken::EndOfStatement) &&
709 Lexer.isNot(AsmToken::Eof))
713 if (Lexer.is(AsmToken::EndOfStatement))
717 StringRef AsmParser::ParseStringToEndOfStatement() {
718 const char *Start = getTok().getLoc().getPointer();
720 while (Lexer.isNot(AsmToken::EndOfStatement) &&
721 Lexer.isNot(AsmToken::Eof))
724 const char *End = getTok().getLoc().getPointer();
725 return StringRef(Start, End - Start);
728 StringRef AsmParser::ParseStringToComma() {
729 const char *Start = getTok().getLoc().getPointer();
731 while (Lexer.isNot(AsmToken::EndOfStatement) &&
732 Lexer.isNot(AsmToken::Comma) &&
733 Lexer.isNot(AsmToken::Eof))
736 const char *End = getTok().getLoc().getPointer();
737 return StringRef(Start, End - Start);
740 /// ParseParenExpr - Parse a paren expression and return it.
741 /// NOTE: This assumes the leading '(' has already been consumed.
743 /// parenexpr ::= expr)
745 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
746 if (ParseExpression(Res)) return true;
747 if (Lexer.isNot(AsmToken::RParen))
748 return TokError("expected ')' in parentheses expression");
749 EndLoc = Lexer.getTok().getEndLoc();
754 /// ParseBracketExpr - Parse a bracket expression and return it.
755 /// NOTE: This assumes the leading '[' has already been consumed.
757 /// bracketexpr ::= expr]
759 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
760 if (ParseExpression(Res)) return true;
761 if (Lexer.isNot(AsmToken::RBrac))
762 return TokError("expected ']' in brackets expression");
763 EndLoc = Lexer.getTok().getEndLoc();
768 /// ParsePrimaryExpr - Parse a primary expression and return it.
769 /// primaryexpr ::= (parenexpr
770 /// primaryexpr ::= symbol
771 /// primaryexpr ::= number
772 /// primaryexpr ::= '.'
773 /// primaryexpr ::= ~,+,- primaryexpr
774 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
775 switch (Lexer.getKind()) {
777 return TokError("unknown token in expression");
778 // If we have an error assume that we've already handled it.
779 case AsmToken::Error:
781 case AsmToken::Exclaim:
782 Lex(); // Eat the operator.
783 if (ParsePrimaryExpr(Res, EndLoc))
785 Res = MCUnaryExpr::CreateLNot(Res, getContext());
787 case AsmToken::Dollar:
788 case AsmToken::String:
789 case AsmToken::Identifier: {
790 StringRef Identifier;
791 if (ParseIdentifier(Identifier))
794 EndLoc = SMLoc::getFromPointer(Identifier.end());
796 // This is a symbol reference.
797 std::pair<StringRef, StringRef> Split = Identifier.split('@');
798 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
800 // Lookup the symbol variant if used.
801 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
802 if (Split.first.size() != Identifier.size()) {
803 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
804 if (Variant == MCSymbolRefExpr::VK_Invalid) {
805 Variant = MCSymbolRefExpr::VK_None;
806 return TokError("invalid variant '" + Split.second + "'");
810 // If this is an absolute variable reference, substitute it now to preserve
811 // semantics in the face of reassignment.
812 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
814 return Error(EndLoc, "unexpected modifier on variable reference");
816 Res = Sym->getVariableValue();
820 // Otherwise create a symbol ref.
821 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
824 case AsmToken::Integer: {
825 SMLoc Loc = getTok().getLoc();
826 int64_t IntVal = getTok().getIntVal();
827 Res = MCConstantExpr::Create(IntVal, getContext());
828 EndLoc = Lexer.getTok().getEndLoc();
830 // Look for 'b' or 'f' following an Integer as a directional label
831 if (Lexer.getKind() == AsmToken::Identifier) {
832 StringRef IDVal = getTok().getString();
833 if (IDVal == "f" || IDVal == "b"){
834 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
835 IDVal == "f" ? 1 : 0);
836 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
838 if (IDVal == "b" && Sym->isUndefined())
839 return Error(Loc, "invalid reference to undefined symbol");
840 EndLoc = Lexer.getTok().getEndLoc();
841 Lex(); // Eat identifier.
846 case AsmToken::Real: {
847 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
848 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
849 Res = MCConstantExpr::Create(IntVal, getContext());
850 EndLoc = Lexer.getTok().getEndLoc();
854 case AsmToken::Dot: {
855 // This is a '.' reference, which references the current PC. Emit a
856 // temporary label to the streamer and refer to it.
857 MCSymbol *Sym = Ctx.CreateTempSymbol();
859 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
860 EndLoc = Lexer.getTok().getEndLoc();
861 Lex(); // Eat identifier.
864 case AsmToken::LParen:
865 Lex(); // Eat the '('.
866 return ParseParenExpr(Res, EndLoc);
867 case AsmToken::LBrac:
868 if (!PlatformParser->HasBracketExpressions())
869 return TokError("brackets expression not supported on this target");
870 Lex(); // Eat the '['.
871 return ParseBracketExpr(Res, EndLoc);
872 case AsmToken::Minus:
873 Lex(); // Eat the operator.
874 if (ParsePrimaryExpr(Res, EndLoc))
876 Res = MCUnaryExpr::CreateMinus(Res, getContext());
879 Lex(); // Eat the operator.
880 if (ParsePrimaryExpr(Res, EndLoc))
882 Res = MCUnaryExpr::CreatePlus(Res, getContext());
884 case AsmToken::Tilde:
885 Lex(); // Eat the operator.
886 if (ParsePrimaryExpr(Res, EndLoc))
888 Res = MCUnaryExpr::CreateNot(Res, getContext());
893 bool AsmParser::ParseExpression(const MCExpr *&Res) {
895 return ParseExpression(Res, EndLoc);
899 AsmParser::ApplyModifierToExpr(const MCExpr *E,
900 MCSymbolRefExpr::VariantKind Variant) {
901 // Recurse over the given expression, rebuilding it to apply the given variant
902 // if there is exactly one symbol.
903 switch (E->getKind()) {
905 case MCExpr::Constant:
908 case MCExpr::SymbolRef: {
909 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
911 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
912 TokError("invalid variant on expression '" +
913 getTok().getIdentifier() + "' (already modified)");
917 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
920 case MCExpr::Unary: {
921 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
922 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
925 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
928 case MCExpr::Binary: {
929 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
930 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
931 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
936 if (!LHS) LHS = BE->getLHS();
937 if (!RHS) RHS = BE->getRHS();
939 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
943 llvm_unreachable("Invalid expression kind!");
946 /// ParseExpression - Parse an expression and return it.
948 /// expr ::= expr &&,|| expr -> lowest.
949 /// expr ::= expr |,^,&,! expr
950 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
951 /// expr ::= expr <<,>> expr
952 /// expr ::= expr +,- expr
953 /// expr ::= expr *,/,% expr -> highest.
954 /// expr ::= primaryexpr
956 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
957 // Parse the expression.
959 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
962 // As a special case, we support 'a op b @ modifier' by rewriting the
963 // expression to include the modifier. This is inefficient, but in general we
964 // expect users to use 'a@modifier op b'.
965 if (Lexer.getKind() == AsmToken::At) {
968 if (Lexer.isNot(AsmToken::Identifier))
969 return TokError("unexpected symbol modifier following '@'");
971 MCSymbolRefExpr::VariantKind Variant =
972 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
973 if (Variant == MCSymbolRefExpr::VK_Invalid)
974 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
976 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
978 return TokError("invalid modifier '" + getTok().getIdentifier() +
979 "' (no symbols present)");
986 // Try to constant fold it up front, if possible.
988 if (Res->EvaluateAsAbsolute(Value))
989 Res = MCConstantExpr::Create(Value, getContext());
994 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
996 return ParseParenExpr(Res, EndLoc) ||
997 ParseBinOpRHS(1, Res, EndLoc);
1000 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
1003 SMLoc StartLoc = Lexer.getLoc();
1004 if (ParseExpression(Expr))
1007 if (!Expr->EvaluateAsAbsolute(Res))
1008 return Error(StartLoc, "expected absolute expression");
1013 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1014 MCBinaryExpr::Opcode &Kind) {
1017 return 0; // not a binop.
1019 // Lowest Precedence: &&, ||
1020 case AsmToken::AmpAmp:
1021 Kind = MCBinaryExpr::LAnd;
1023 case AsmToken::PipePipe:
1024 Kind = MCBinaryExpr::LOr;
1028 // Low Precedence: |, &, ^
1030 // FIXME: gas seems to support '!' as an infix operator?
1031 case AsmToken::Pipe:
1032 Kind = MCBinaryExpr::Or;
1034 case AsmToken::Caret:
1035 Kind = MCBinaryExpr::Xor;
1038 Kind = MCBinaryExpr::And;
1041 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1042 case AsmToken::EqualEqual:
1043 Kind = MCBinaryExpr::EQ;
1045 case AsmToken::ExclaimEqual:
1046 case AsmToken::LessGreater:
1047 Kind = MCBinaryExpr::NE;
1049 case AsmToken::Less:
1050 Kind = MCBinaryExpr::LT;
1052 case AsmToken::LessEqual:
1053 Kind = MCBinaryExpr::LTE;
1055 case AsmToken::Greater:
1056 Kind = MCBinaryExpr::GT;
1058 case AsmToken::GreaterEqual:
1059 Kind = MCBinaryExpr::GTE;
1062 // Intermediate Precedence: <<, >>
1063 case AsmToken::LessLess:
1064 Kind = MCBinaryExpr::Shl;
1066 case AsmToken::GreaterGreater:
1067 Kind = MCBinaryExpr::Shr;
1070 // High Intermediate Precedence: +, -
1071 case AsmToken::Plus:
1072 Kind = MCBinaryExpr::Add;
1074 case AsmToken::Minus:
1075 Kind = MCBinaryExpr::Sub;
1078 // Highest Precedence: *, /, %
1079 case AsmToken::Star:
1080 Kind = MCBinaryExpr::Mul;
1082 case AsmToken::Slash:
1083 Kind = MCBinaryExpr::Div;
1085 case AsmToken::Percent:
1086 Kind = MCBinaryExpr::Mod;
1092 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1093 /// Res contains the LHS of the expression on input.
1094 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1097 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1098 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1100 // If the next token is lower precedence than we are allowed to eat, return
1101 // successfully with what we ate already.
1102 if (TokPrec < Precedence)
1107 // Eat the next primary expression.
1109 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1111 // If BinOp binds less tightly with RHS than the operator after RHS, let
1112 // the pending operator take RHS as its LHS.
1113 MCBinaryExpr::Opcode Dummy;
1114 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1115 if (TokPrec < NextTokPrec) {
1116 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1119 // Merge LHS and RHS according to operator.
1120 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1125 /// ::= EndOfStatement
1126 /// ::= Label* Directive ...Operands... EndOfStatement
1127 /// ::= Label* Identifier OperandList* EndOfStatement
1128 bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
1129 if (Lexer.is(AsmToken::EndOfStatement)) {
1135 // Statements always start with an identifier or are a full line comment.
1136 AsmToken ID = getTok();
1137 SMLoc IDLoc = ID.getLoc();
1139 int64_t LocalLabelVal = -1;
1140 // A full line comment is a '#' as the first token.
1141 if (Lexer.is(AsmToken::Hash))
1142 return ParseCppHashLineFilenameComment(IDLoc);
1144 // Allow an integer followed by a ':' as a directional local label.
1145 if (Lexer.is(AsmToken::Integer)) {
1146 LocalLabelVal = getTok().getIntVal();
1147 if (LocalLabelVal < 0) {
1148 if (!TheCondState.Ignore)
1149 return TokError("unexpected token at start of statement");
1153 IDVal = getTok().getString();
1154 Lex(); // Consume the integer token to be used as an identifier token.
1155 if (Lexer.getKind() != AsmToken::Colon) {
1156 if (!TheCondState.Ignore)
1157 return TokError("unexpected token at start of statement");
1161 } else if (Lexer.is(AsmToken::Dot)) {
1162 // Treat '.' as a valid identifier in this context.
1166 } else if (ParseIdentifier(IDVal)) {
1167 if (!TheCondState.Ignore)
1168 return TokError("unexpected token at start of statement");
1172 // Handle conditional assembly here before checking for skipping. We
1173 // have to do this so that .endif isn't skipped in a ".if 0" block for
1175 StringMap<DirectiveKind>::const_iterator DirKindIt =
1176 DirectiveKindMapping.find(IDVal);
1177 DirectiveKind DirKind =
1178 (DirKindIt == DirectiveKindMapping.end()) ? DK_NO_DIRECTIVE :
1179 DirKindIt->getValue();
1184 return ParseDirectiveIf(IDLoc);
1186 return ParseDirectiveIfb(IDLoc, true);
1188 return ParseDirectiveIfb(IDLoc, false);
1190 return ParseDirectiveIfc(IDLoc, true);
1192 return ParseDirectiveIfc(IDLoc, false);
1194 return ParseDirectiveIfdef(IDLoc, true);
1197 return ParseDirectiveIfdef(IDLoc, false);
1199 return ParseDirectiveElseIf(IDLoc);
1201 return ParseDirectiveElse(IDLoc);
1203 return ParseDirectiveEndIf(IDLoc);
1206 // If we are in a ".if 0" block, ignore this statement.
1207 if (TheCondState.Ignore) {
1208 EatToEndOfStatement();
1212 // FIXME: Recurse on local labels?
1214 // See what kind of statement we have.
1215 switch (Lexer.getKind()) {
1216 case AsmToken::Colon: {
1217 CheckForValidSection();
1219 // identifier ':' -> Label.
1222 // Diagnose attempt to use '.' as a label.
1224 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1226 // Diagnose attempt to use a variable as a label.
1228 // FIXME: Diagnostics. Note the location of the definition as a label.
1229 // FIXME: This doesn't diagnose assignment to a symbol which has been
1230 // implicitly marked as external.
1232 if (LocalLabelVal == -1)
1233 Sym = getContext().GetOrCreateSymbol(IDVal);
1235 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1236 if (!Sym->isUndefined() || Sym->isVariable())
1237 return Error(IDLoc, "invalid symbol redefinition");
1240 if (!ParsingInlineAsm)
1243 // If we are generating dwarf for assembly source files then gather the
1244 // info to make a dwarf label entry for this label if needed.
1245 if (getContext().getGenDwarfForAssembly())
1246 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1249 // Consume any end of statement token, if present, to avoid spurious
1250 // AddBlankLine calls().
1251 if (Lexer.is(AsmToken::EndOfStatement)) {
1253 if (Lexer.is(AsmToken::Eof))
1260 case AsmToken::Equal:
1261 // identifier '=' ... -> assignment statement
1264 return ParseAssignment(IDVal, true);
1266 default: // Normal instruction or directive.
1270 // If macros are enabled, check to see if this is a macro instantiation.
1271 if (MacrosEnabled())
1272 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1273 return HandleMacroEntry(M, IDLoc);
1276 // Otherwise, we have a normal instruction or directive.
1277 if (IDVal[0] == '.' && IDVal != ".") {
1279 // Target hook for parsing target specific directives.
1280 if (!getTargetParser().ParseDirective(ID))
1288 return ParseDirectiveSet(IDVal, true);
1290 return ParseDirectiveSet(IDVal, false);
1292 return ParseDirectiveAscii(IDVal, false);
1295 return ParseDirectiveAscii(IDVal, true);
1297 return ParseDirectiveValue(1);
1301 return ParseDirectiveValue(2);
1305 return ParseDirectiveValue(4);
1308 return ParseDirectiveValue(8);
1311 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1313 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1315 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1316 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1319 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1320 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1323 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1325 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1327 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1329 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1331 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1333 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1335 return ParseDirectiveOrg();
1337 return ParseDirectiveFill();
1339 return ParseDirectiveZero();
1341 EatToEndOfStatement(); // .extern is the default, ignore it.
1345 return ParseDirectiveSymbolAttribute(MCSA_Global);
1346 case DK_INDIRECT_SYMBOL:
1347 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1348 case DK_LAZY_REFERENCE:
1349 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1350 case DK_NO_DEAD_STRIP:
1351 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1352 case DK_SYMBOL_RESOLVER:
1353 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1354 case DK_PRIVATE_EXTERN:
1355 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1357 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1358 case DK_WEAK_DEFINITION:
1359 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1360 case DK_WEAK_REFERENCE:
1361 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1362 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1363 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1366 return ParseDirectiveComm(/*IsLocal=*/false);
1368 return ParseDirectiveComm(/*IsLocal=*/true);
1370 return ParseDirectiveAbort();
1372 return ParseDirectiveInclude();
1374 return ParseDirectiveIncbin();
1377 return TokError(Twine(IDVal) + " not supported yet");
1379 return ParseDirectiveRept(IDLoc);
1381 return ParseDirectiveIrp(IDLoc);
1383 return ParseDirectiveIrpc(IDLoc);
1385 return ParseDirectiveEndr(IDLoc);
1386 case DK_BUNDLE_ALIGN_MODE:
1387 return ParseDirectiveBundleAlignMode();
1388 case DK_BUNDLE_LOCK:
1389 return ParseDirectiveBundleLock();
1390 case DK_BUNDLE_UNLOCK:
1391 return ParseDirectiveBundleUnlock();
1394 // Look up the handler in the extension handler table.
1395 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1396 DirectiveMap.lookup(IDVal);
1398 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1400 return Error(IDLoc, "unknown directive");
1404 if (ParsingInlineAsm && IDVal == "_emit")
1405 return ParseDirectiveEmit(IDLoc, Info);
1407 CheckForValidSection();
1409 // Canonicalize the opcode to lower case.
1410 SmallString<128> OpcodeStr;
1411 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1412 OpcodeStr.push_back(tolower(IDVal[i]));
1414 ParseInstructionInfo IInfo(Info.AsmRewrites);
1415 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1416 IDLoc,Info.ParsedOperands);
1417 Info.ParseError = HadError;
1419 // Dump the parsed representation, if requested.
1420 if (getShowParsedOperands()) {
1421 SmallString<256> Str;
1422 raw_svector_ostream OS(Str);
1423 OS << "parsed instruction: [";
1424 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1427 Info.ParsedOperands[i]->print(OS);
1431 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1434 // If we are generating dwarf for assembly source files and the current
1435 // section is the initial text section then generate a .loc directive for
1437 if (!HadError && getContext().getGenDwarfForAssembly() &&
1438 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
1440 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1442 // If we previously parsed a cpp hash file line comment then make sure the
1443 // current Dwarf File is for the CppHashFilename if not then emit the
1444 // Dwarf File table for it and adjust the line number for the .loc.
1445 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1446 getContext().getMCDwarfFiles();
1447 if (CppHashFilename.size() != 0) {
1448 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1450 getStreamer().EmitDwarfFileDirective(
1451 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1453 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
1454 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1457 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1458 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1459 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1463 // If parsing succeeded, match the instruction.
1466 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1467 Info.ParsedOperands,
1472 // Don't skip the rest of the line, the instruction parser is responsible for
1477 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1478 /// since they may not be able to be tokenized to get to the end of line token.
1479 void AsmParser::EatToEndOfLine() {
1480 if (!Lexer.is(AsmToken::EndOfStatement))
1481 Lexer.LexUntilEndOfLine();
1486 /// ParseCppHashLineFilenameComment as this:
1487 /// ::= # number "filename"
1488 /// or just as a full line comment if it doesn't have a number and a string.
1489 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1490 Lex(); // Eat the hash token.
1492 if (getLexer().isNot(AsmToken::Integer)) {
1493 // Consume the line since in cases it is not a well-formed line directive,
1494 // as if were simply a full line comment.
1499 int64_t LineNumber = getTok().getIntVal();
1502 if (getLexer().isNot(AsmToken::String)) {
1507 StringRef Filename = getTok().getString();
1508 // Get rid of the enclosing quotes.
1509 Filename = Filename.substr(1, Filename.size()-2);
1511 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1513 CppHashFilename = Filename;
1514 CppHashLineNumber = LineNumber;
1515 CppHashBuf = CurBuffer;
1517 // Ignore any trailing characters, they're just comment.
1522 /// DiagHandler - will use the last parsed cpp hash line filename comment
1523 /// for the Filename and LineNo if any in the diagnostic.
1524 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1525 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1526 raw_ostream &OS = errs();
1528 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1529 const SMLoc &DiagLoc = Diag.getLoc();
1530 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1531 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1533 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1534 // before printing the message.
1535 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1536 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1537 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1538 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1541 // If we have not parsed a cpp hash line filename comment or the source
1542 // manager changed or buffer changed (like in a nested include) then just
1543 // print the normal diagnostic using its Filename and LineNo.
1544 if (!Parser->CppHashLineNumber ||
1545 &DiagSrcMgr != &Parser->SrcMgr ||
1546 DiagBuf != CppHashBuf) {
1547 if (Parser->SavedDiagHandler)
1548 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1554 // Use the CppHashFilename and calculate a line number based on the
1555 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1557 const std::string Filename = Parser->CppHashFilename;
1559 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1560 int CppHashLocLineNo =
1561 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1562 int LineNo = Parser->CppHashLineNumber - 1 +
1563 (DiagLocLineNo - CppHashLocLineNo);
1565 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1566 Filename, LineNo, Diag.getColumnNo(),
1567 Diag.getKind(), Diag.getMessage(),
1568 Diag.getLineContents(), Diag.getRanges());
1570 if (Parser->SavedDiagHandler)
1571 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1573 NewDiag.print(0, OS);
1576 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1577 // difference being that that function accepts '@' as part of identifiers and
1578 // we can't do that. AsmLexer.cpp should probably be changed to handle
1579 // '@' as a special case when needed.
1580 static bool isIdentifierChar(char c) {
1581 return isalnum(c) || c == '_' || c == '$' || c == '.';
1584 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1585 const MCAsmMacroParameters &Parameters,
1586 const MCAsmMacroArguments &A,
1588 unsigned NParameters = Parameters.size();
1589 if (NParameters != 0 && NParameters != A.size())
1590 return Error(L, "Wrong number of arguments");
1592 // A macro without parameters is handled differently on Darwin:
1593 // gas accepts no arguments and does no substitutions
1594 while (!Body.empty()) {
1595 // Scan for the next substitution.
1596 std::size_t End = Body.size(), Pos = 0;
1597 for (; Pos != End; ++Pos) {
1598 // Check for a substitution or escape.
1600 // This macro has no parameters, look for $0, $1, etc.
1601 if (Body[Pos] != '$' || Pos + 1 == End)
1604 char Next = Body[Pos + 1];
1605 if (Next == '$' || Next == 'n' || isdigit(Next))
1608 // This macro has parameters, look for \foo, \bar, etc.
1609 if (Body[Pos] == '\\' && Pos + 1 != End)
1615 OS << Body.slice(0, Pos);
1617 // Check if we reached the end.
1622 switch (Body[Pos+1]) {
1628 // $n => number of arguments
1633 // $[0-9] => argument
1635 // Missing arguments are ignored.
1636 unsigned Index = Body[Pos+1] - '0';
1637 if (Index >= A.size())
1640 // Otherwise substitute with the token values, with spaces eliminated.
1641 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1642 ie = A[Index].end(); it != ie; ++it)
1643 OS << it->getString();
1649 unsigned I = Pos + 1;
1650 while (isIdentifierChar(Body[I]) && I + 1 != End)
1653 const char *Begin = Body.data() + Pos +1;
1654 StringRef Argument(Begin, I - (Pos +1));
1656 for (; Index < NParameters; ++Index)
1657 if (Parameters[Index].first == Argument)
1660 if (Index == NParameters) {
1661 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1664 OS << '\\' << Argument;
1668 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1669 ie = A[Index].end(); it != ie; ++it)
1670 if (it->getKind() == AsmToken::String)
1671 OS << it->getStringContents();
1673 OS << it->getString();
1675 Pos += 1 + Argument.size();
1678 // Update the scan point.
1679 Body = Body.substr(Pos);
1685 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
1688 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1693 static bool IsOperator(AsmToken::TokenKind kind)
1699 case AsmToken::Plus:
1700 case AsmToken::Minus:
1701 case AsmToken::Tilde:
1702 case AsmToken::Slash:
1703 case AsmToken::Star:
1705 case AsmToken::Equal:
1706 case AsmToken::EqualEqual:
1707 case AsmToken::Pipe:
1708 case AsmToken::PipePipe:
1709 case AsmToken::Caret:
1711 case AsmToken::AmpAmp:
1712 case AsmToken::Exclaim:
1713 case AsmToken::ExclaimEqual:
1714 case AsmToken::Percent:
1715 case AsmToken::Less:
1716 case AsmToken::LessEqual:
1717 case AsmToken::LessLess:
1718 case AsmToken::LessGreater:
1719 case AsmToken::Greater:
1720 case AsmToken::GreaterEqual:
1721 case AsmToken::GreaterGreater:
1726 bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
1727 AsmToken::TokenKind &ArgumentDelimiter) {
1728 unsigned ParenLevel = 0;
1729 unsigned AddTokens = 0;
1731 // gas accepts arguments separated by whitespace, except on Darwin
1733 Lexer.setSkipSpace(false);
1736 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1737 Lexer.setSkipSpace(true);
1738 return TokError("unexpected token in macro instantiation");
1741 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1742 // Spaces and commas cannot be mixed to delimit parameters
1743 if (ArgumentDelimiter == AsmToken::Eof)
1744 ArgumentDelimiter = AsmToken::Comma;
1745 else if (ArgumentDelimiter != AsmToken::Comma) {
1746 Lexer.setSkipSpace(true);
1747 return TokError("expected ' ' for macro argument separator");
1752 if (Lexer.is(AsmToken::Space)) {
1753 Lex(); // Eat spaces
1755 // Spaces can delimit parameters, but could also be part an expression.
1756 // If the token after a space is an operator, add the token and the next
1757 // one into this argument
1758 if (ArgumentDelimiter == AsmToken::Space ||
1759 ArgumentDelimiter == AsmToken::Eof) {
1760 if (IsOperator(Lexer.getKind())) {
1761 // Check to see whether the token is used as an operator,
1762 // or part of an identifier
1763 const char *NextChar = getTok().getEndLoc().getPointer();
1764 if (*NextChar == ' ')
1768 if (!AddTokens && ParenLevel == 0) {
1769 if (ArgumentDelimiter == AsmToken::Eof &&
1770 !IsOperator(Lexer.getKind()))
1771 ArgumentDelimiter = AsmToken::Space;
1777 // HandleMacroEntry relies on not advancing the lexer here
1778 // to be able to fill in the remaining default parameter values
1779 if (Lexer.is(AsmToken::EndOfStatement))
1782 // Adjust the current parentheses level.
1783 if (Lexer.is(AsmToken::LParen))
1785 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1788 // Append the token to the current argument list.
1789 MA.push_back(getTok());
1795 Lexer.setSkipSpace(true);
1796 if (ParenLevel != 0)
1797 return TokError("unbalanced parentheses in macro argument");
1801 // Parse the macro instantiation arguments.
1802 bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
1803 const unsigned NParameters = M ? M->Parameters.size() : 0;
1804 // Argument delimiter is initially unknown. It will be set by
1805 // ParseMacroArgument()
1806 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1808 // Parse two kinds of macro invocations:
1809 // - macros defined without any parameters accept an arbitrary number of them
1810 // - macros defined with parameters accept at most that many of them
1811 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1813 MCAsmMacroArgument MA;
1815 if (ParseMacroArgument(MA, ArgumentDelimiter))
1818 if (!MA.empty() || !NParameters)
1820 else if (NParameters) {
1821 if (!M->Parameters[Parameter].second.empty())
1822 A.push_back(M->Parameters[Parameter].second);
1825 // At the end of the statement, fill in remaining arguments that have
1826 // default values. If there aren't any, then the next argument is
1827 // required but missing
1828 if (Lexer.is(AsmToken::EndOfStatement)) {
1829 if (NParameters && Parameter < NParameters - 1) {
1830 if (M->Parameters[Parameter + 1].second.empty())
1831 return TokError("macro argument '" +
1832 Twine(M->Parameters[Parameter + 1].first) +
1840 if (Lexer.is(AsmToken::Comma))
1843 return TokError("Too many arguments");
1846 const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1847 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1848 return (I == MacroMap.end()) ? NULL : I->getValue();
1851 void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1852 MacroMap[Name] = new MCAsmMacro(Macro);
1855 void AsmParser::UndefineMacro(StringRef Name) {
1856 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1857 if (I != MacroMap.end()) {
1858 delete I->getValue();
1863 bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
1864 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1865 // this, although we should protect against infinite loops.
1866 if (ActiveMacros.size() == 20)
1867 return TokError("macros cannot be nested more than 20 levels deep");
1869 MCAsmMacroArguments A;
1870 if (ParseMacroArguments(M, A))
1873 // Remove any trailing empty arguments. Do this after-the-fact as we have
1874 // to keep empty arguments in the middle of the list or positionality
1875 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1876 while (!A.empty() && A.back().empty())
1879 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1880 // to hold the macro body with substitutions.
1881 SmallString<256> Buf;
1882 StringRef Body = M->Body;
1883 raw_svector_ostream OS(Buf);
1885 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1888 // We include the .endmacro in the buffer as our cue to exit the macro
1890 OS << ".endmacro\n";
1892 MemoryBuffer *Instantiation =
1893 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1895 // Create the macro instantiation object and add to the current macro
1896 // instantiation stack.
1897 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1901 ActiveMacros.push_back(MI);
1903 // Jump to the macro instantiation and prime the lexer.
1904 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1905 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1911 void AsmParser::HandleMacroExit() {
1912 // Jump to the EndOfStatement we should return to, and consume it.
1913 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
1916 // Pop the instantiation entry.
1917 delete ActiveMacros.back();
1918 ActiveMacros.pop_back();
1921 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1922 switch (Value->getKind()) {
1923 case MCExpr::Binary: {
1924 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1925 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1928 case MCExpr::Target:
1929 case MCExpr::Constant:
1931 case MCExpr::SymbolRef: {
1932 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1934 return IsUsedIn(Sym, S.getVariableValue());
1938 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1941 llvm_unreachable("Unknown expr kind!");
1944 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1946 // FIXME: Use better location, we should use proper tokens.
1947 SMLoc EqualLoc = Lexer.getLoc();
1949 const MCExpr *Value;
1950 if (ParseExpression(Value))
1953 // Note: we don't count b as used in "a = b". This is to allow
1957 if (Lexer.isNot(AsmToken::EndOfStatement))
1958 return TokError("unexpected token in assignment");
1960 // Error on assignment to '.'.
1962 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1963 "(use '.space' or '.org').)"));
1966 // Eat the end of statement marker.
1969 // Validate that the LHS is allowed to be a variable (either it has not been
1970 // used as a symbol, or it is an absolute symbol).
1971 MCSymbol *Sym = getContext().LookupSymbol(Name);
1973 // Diagnose assignment to a label.
1975 // FIXME: Diagnostics. Note the location of the definition as a label.
1976 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1977 if (IsUsedIn(Sym, Value))
1978 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1979 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1980 ; // Allow redefinitions of undefined symbols only used in directives.
1981 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1982 ; // Allow redefinitions of variables that haven't yet been used.
1983 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1984 return Error(EqualLoc, "redefinition of '" + Name + "'");
1985 else if (!Sym->isVariable())
1986 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1987 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1988 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1991 // Don't count these checks as uses.
1992 Sym->setUsed(false);
1994 Sym = getContext().GetOrCreateSymbol(Name);
1996 // FIXME: Handle '.'.
1998 // Do the assignment.
1999 Out.EmitAssignment(Sym, Value);
2001 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2007 /// ParseIdentifier:
2010 bool AsmParser::ParseIdentifier(StringRef &Res) {
2011 // The assembler has relaxed rules for accepting identifiers, in particular we
2012 // allow things like '.globl $foo', which would normally be separate
2013 // tokens. At this level, we have already lexed so we cannot (currently)
2014 // handle this as a context dependent token, instead we detect adjacent tokens
2015 // and return the combined identifier.
2016 if (Lexer.is(AsmToken::Dollar)) {
2017 SMLoc DollarLoc = getLexer().getLoc();
2019 // Consume the dollar sign, and check for a following identifier.
2021 if (Lexer.isNot(AsmToken::Identifier))
2024 // We have a '$' followed by an identifier, make sure they are adjacent.
2025 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2028 // Construct the joined identifier and consume the token.
2029 Res = StringRef(DollarLoc.getPointer(),
2030 getTok().getIdentifier().size() + 1);
2035 if (Lexer.isNot(AsmToken::Identifier) &&
2036 Lexer.isNot(AsmToken::String))
2039 Res = getTok().getIdentifier();
2041 Lex(); // Consume the identifier token.
2046 /// ParseDirectiveSet:
2047 /// ::= .equ identifier ',' expression
2048 /// ::= .equiv identifier ',' expression
2049 /// ::= .set identifier ',' expression
2050 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
2053 if (ParseIdentifier(Name))
2054 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2056 if (getLexer().isNot(AsmToken::Comma))
2057 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2060 return ParseAssignment(Name, allow_redef, true);
2063 bool AsmParser::ParseEscapedString(std::string &Data) {
2064 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2067 StringRef Str = getTok().getStringContents();
2068 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2069 if (Str[i] != '\\') {
2074 // Recognize escaped characters. Note that this escape semantics currently
2075 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2078 return TokError("unexpected backslash at end of string");
2080 // Recognize octal sequences.
2081 if ((unsigned) (Str[i] - '0') <= 7) {
2082 // Consume up to three octal characters.
2083 unsigned Value = Str[i] - '0';
2085 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2087 Value = Value * 8 + (Str[i] - '0');
2089 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2091 Value = Value * 8 + (Str[i] - '0');
2096 return TokError("invalid octal escape sequence (out of range)");
2098 Data += (unsigned char) Value;
2102 // Otherwise recognize individual escapes.
2105 // Just reject invalid escape sequences for now.
2106 return TokError("invalid escape sequence (unrecognized character)");
2108 case 'b': Data += '\b'; break;
2109 case 'f': Data += '\f'; break;
2110 case 'n': Data += '\n'; break;
2111 case 'r': Data += '\r'; break;
2112 case 't': Data += '\t'; break;
2113 case '"': Data += '"'; break;
2114 case '\\': Data += '\\'; break;
2121 /// ParseDirectiveAscii:
2122 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2123 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2124 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2125 CheckForValidSection();
2128 if (getLexer().isNot(AsmToken::String))
2129 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2132 if (ParseEscapedString(Data))
2135 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2137 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2141 if (getLexer().is(AsmToken::EndOfStatement))
2144 if (getLexer().isNot(AsmToken::Comma))
2145 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2154 /// ParseDirectiveValue
2155 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2156 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2157 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2158 CheckForValidSection();
2161 const MCExpr *Value;
2162 SMLoc ExprLoc = getLexer().getLoc();
2163 if (ParseExpression(Value))
2166 // Special case constant expressions to match code generator.
2167 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2168 assert(Size <= 8 && "Invalid size");
2169 uint64_t IntValue = MCE->getValue();
2170 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2171 return Error(ExprLoc, "literal value out of range for directive");
2172 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2174 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2176 if (getLexer().is(AsmToken::EndOfStatement))
2179 // FIXME: Improve diagnostic.
2180 if (getLexer().isNot(AsmToken::Comma))
2181 return TokError("unexpected token in directive");
2190 /// ParseDirectiveRealValue
2191 /// ::= (.single | .double) [ expression (, expression)* ]
2192 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2193 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2194 CheckForValidSection();
2197 // We don't truly support arithmetic on floating point expressions, so we
2198 // have to manually parse unary prefixes.
2200 if (getLexer().is(AsmToken::Minus)) {
2203 } else if (getLexer().is(AsmToken::Plus))
2206 if (getLexer().isNot(AsmToken::Integer) &&
2207 getLexer().isNot(AsmToken::Real) &&
2208 getLexer().isNot(AsmToken::Identifier))
2209 return TokError("unexpected token in directive");
2211 // Convert to an APFloat.
2212 APFloat Value(Semantics);
2213 StringRef IDVal = getTok().getString();
2214 if (getLexer().is(AsmToken::Identifier)) {
2215 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2216 Value = APFloat::getInf(Semantics);
2217 else if (!IDVal.compare_lower("nan"))
2218 Value = APFloat::getNaN(Semantics, false, ~0);
2220 return TokError("invalid floating point literal");
2221 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2222 APFloat::opInvalidOp)
2223 return TokError("invalid floating point literal");
2227 // Consume the numeric token.
2230 // Emit the value as an integer.
2231 APInt AsInt = Value.bitcastToAPInt();
2232 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2233 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2235 if (getLexer().is(AsmToken::EndOfStatement))
2238 if (getLexer().isNot(AsmToken::Comma))
2239 return TokError("unexpected token in directive");
2248 /// ParseDirectiveZero
2249 /// ::= .zero expression
2250 bool AsmParser::ParseDirectiveZero() {
2251 CheckForValidSection();
2254 if (ParseAbsoluteExpression(NumBytes))
2258 if (getLexer().is(AsmToken::Comma)) {
2260 if (ParseAbsoluteExpression(Val))
2264 if (getLexer().isNot(AsmToken::EndOfStatement))
2265 return TokError("unexpected token in '.zero' directive");
2269 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2274 /// ParseDirectiveFill
2275 /// ::= .fill expression , expression , expression
2276 bool AsmParser::ParseDirectiveFill() {
2277 CheckForValidSection();
2280 if (ParseAbsoluteExpression(NumValues))
2283 if (getLexer().isNot(AsmToken::Comma))
2284 return TokError("unexpected token in '.fill' directive");
2288 if (ParseAbsoluteExpression(FillSize))
2291 if (getLexer().isNot(AsmToken::Comma))
2292 return TokError("unexpected token in '.fill' directive");
2296 if (ParseAbsoluteExpression(FillExpr))
2299 if (getLexer().isNot(AsmToken::EndOfStatement))
2300 return TokError("unexpected token in '.fill' directive");
2304 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2305 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2307 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2308 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2313 /// ParseDirectiveOrg
2314 /// ::= .org expression [ , expression ]
2315 bool AsmParser::ParseDirectiveOrg() {
2316 CheckForValidSection();
2318 const MCExpr *Offset;
2319 SMLoc Loc = getTok().getLoc();
2320 if (ParseExpression(Offset))
2323 // Parse optional fill expression.
2324 int64_t FillExpr = 0;
2325 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2326 if (getLexer().isNot(AsmToken::Comma))
2327 return TokError("unexpected token in '.org' directive");
2330 if (ParseAbsoluteExpression(FillExpr))
2333 if (getLexer().isNot(AsmToken::EndOfStatement))
2334 return TokError("unexpected token in '.org' directive");
2339 // Only limited forms of relocatable expressions are accepted here, it
2340 // has to be relative to the current section. The streamer will return
2341 // 'true' if the expression wasn't evaluatable.
2342 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2343 return Error(Loc, "expected assembly-time absolute expression");
2348 /// ParseDirectiveAlign
2349 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2350 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2351 CheckForValidSection();
2353 SMLoc AlignmentLoc = getLexer().getLoc();
2355 if (ParseAbsoluteExpression(Alignment))
2359 bool HasFillExpr = false;
2360 int64_t FillExpr = 0;
2361 int64_t MaxBytesToFill = 0;
2362 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2363 if (getLexer().isNot(AsmToken::Comma))
2364 return TokError("unexpected token in directive");
2367 // The fill expression can be omitted while specifying a maximum number of
2368 // alignment bytes, e.g:
2370 if (getLexer().isNot(AsmToken::Comma)) {
2372 if (ParseAbsoluteExpression(FillExpr))
2376 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2377 if (getLexer().isNot(AsmToken::Comma))
2378 return TokError("unexpected token in directive");
2381 MaxBytesLoc = getLexer().getLoc();
2382 if (ParseAbsoluteExpression(MaxBytesToFill))
2385 if (getLexer().isNot(AsmToken::EndOfStatement))
2386 return TokError("unexpected token in directive");
2395 // Compute alignment in bytes.
2397 // FIXME: Diagnose overflow.
2398 if (Alignment >= 32) {
2399 Error(AlignmentLoc, "invalid alignment value");
2403 Alignment = 1ULL << Alignment;
2406 // Diagnose non-sensical max bytes to align.
2407 if (MaxBytesLoc.isValid()) {
2408 if (MaxBytesToFill < 1) {
2409 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2410 "many bytes, ignoring maximum bytes expression");
2414 if (MaxBytesToFill >= Alignment) {
2415 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2421 // Check whether we should use optimal code alignment for this .align
2423 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2424 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2425 ValueSize == 1 && UseCodeAlign) {
2426 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2428 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2429 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2437 /// ParseDirectiveBundleAlignMode
2438 /// ::= {.bundle_align_mode} expression
2439 bool AsmParser::ParseDirectiveBundleAlignMode() {
2440 CheckForValidSection();
2442 // Expect a single argument: an expression that evaluates to a constant
2443 // in the inclusive range 0-30.
2444 SMLoc ExprLoc = getLexer().getLoc();
2445 int64_t AlignSizePow2;
2446 if (ParseAbsoluteExpression(AlignSizePow2))
2448 else if (getLexer().isNot(AsmToken::EndOfStatement))
2449 return TokError("unexpected token after expression in"
2450 " '.bundle_align_mode' directive");
2451 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
2452 return Error(ExprLoc,
2453 "invalid bundle alignment size (expected between 0 and 30)");
2457 // Because of AlignSizePow2's verified range we can safely truncate it to
2459 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
2463 /// ParseDirectiveBundleLock
2464 /// ::= {.bundle_lock} [align_to_end]
2465 bool AsmParser::ParseDirectiveBundleLock() {
2466 CheckForValidSection();
2467 bool AlignToEnd = false;
2469 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2471 SMLoc Loc = getTok().getLoc();
2472 const char *kInvalidOptionError =
2473 "invalid option for '.bundle_lock' directive";
2475 if (ParseIdentifier(Option))
2476 return Error(Loc, kInvalidOptionError);
2478 if (Option != "align_to_end")
2479 return Error(Loc, kInvalidOptionError);
2480 else if (getLexer().isNot(AsmToken::EndOfStatement))
2482 "unexpected token after '.bundle_lock' directive option");
2488 getStreamer().EmitBundleLock(AlignToEnd);
2492 /// ParseDirectiveBundleLock
2493 /// ::= {.bundle_lock}
2494 bool AsmParser::ParseDirectiveBundleUnlock() {
2495 CheckForValidSection();
2497 if (getLexer().isNot(AsmToken::EndOfStatement))
2498 return TokError("unexpected token in '.bundle_unlock' directive");
2501 getStreamer().EmitBundleUnlock();
2505 /// ParseDirectiveSymbolAttribute
2506 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2507 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2508 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2511 SMLoc Loc = getTok().getLoc();
2513 if (ParseIdentifier(Name))
2514 return Error(Loc, "expected identifier in directive");
2516 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2518 // Assembler local symbols don't make any sense here. Complain loudly.
2519 if (Sym->isTemporary())
2520 return Error(Loc, "non-local symbol required in directive");
2522 getStreamer().EmitSymbolAttribute(Sym, Attr);
2524 if (getLexer().is(AsmToken::EndOfStatement))
2527 if (getLexer().isNot(AsmToken::Comma))
2528 return TokError("unexpected token in directive");
2537 /// ParseDirectiveComm
2538 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2539 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2540 CheckForValidSection();
2542 SMLoc IDLoc = getLexer().getLoc();
2544 if (ParseIdentifier(Name))
2545 return TokError("expected identifier in directive");
2547 // Handle the identifier as the key symbol.
2548 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2550 if (getLexer().isNot(AsmToken::Comma))
2551 return TokError("unexpected token in directive");
2555 SMLoc SizeLoc = getLexer().getLoc();
2556 if (ParseAbsoluteExpression(Size))
2559 int64_t Pow2Alignment = 0;
2560 SMLoc Pow2AlignmentLoc;
2561 if (getLexer().is(AsmToken::Comma)) {
2563 Pow2AlignmentLoc = getLexer().getLoc();
2564 if (ParseAbsoluteExpression(Pow2Alignment))
2567 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2568 if (IsLocal && LCOMM == LCOMM::NoAlignment)
2569 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2571 // If this target takes alignments in bytes (not log) validate and convert.
2572 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2573 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
2574 if (!isPowerOf2_64(Pow2Alignment))
2575 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2576 Pow2Alignment = Log2_64(Pow2Alignment);
2580 if (getLexer().isNot(AsmToken::EndOfStatement))
2581 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2585 // NOTE: a size of zero for a .comm should create a undefined symbol
2586 // but a size of .lcomm creates a bss symbol of size zero.
2588 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2589 "be less than zero");
2591 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2592 // may internally end up wanting an alignment in bytes.
2593 // FIXME: Diagnose overflow.
2594 if (Pow2Alignment < 0)
2595 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2596 "alignment, can't be less than zero");
2598 if (!Sym->isUndefined())
2599 return Error(IDLoc, "invalid symbol redefinition");
2601 // Create the Symbol as a common or local common with Size and Pow2Alignment
2603 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2607 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2611 /// ParseDirectiveAbort
2612 /// ::= .abort [... message ...]
2613 bool AsmParser::ParseDirectiveAbort() {
2614 // FIXME: Use loc from directive.
2615 SMLoc Loc = getLexer().getLoc();
2617 StringRef Str = ParseStringToEndOfStatement();
2618 if (getLexer().isNot(AsmToken::EndOfStatement))
2619 return TokError("unexpected token in '.abort' directive");
2624 Error(Loc, ".abort detected. Assembly stopping.");
2626 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2627 // FIXME: Actually abort assembly here.
2632 /// ParseDirectiveInclude
2633 /// ::= .include "filename"
2634 bool AsmParser::ParseDirectiveInclude() {
2635 if (getLexer().isNot(AsmToken::String))
2636 return TokError("expected string in '.include' directive");
2638 std::string Filename = getTok().getString();
2639 SMLoc IncludeLoc = getLexer().getLoc();
2642 if (getLexer().isNot(AsmToken::EndOfStatement))
2643 return TokError("unexpected token in '.include' directive");
2645 // Strip the quotes.
2646 Filename = Filename.substr(1, Filename.size()-2);
2648 // Attempt to switch the lexer to the included file before consuming the end
2649 // of statement to avoid losing it when we switch.
2650 if (EnterIncludeFile(Filename)) {
2651 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2658 /// ParseDirectiveIncbin
2659 /// ::= .incbin "filename"
2660 bool AsmParser::ParseDirectiveIncbin() {
2661 if (getLexer().isNot(AsmToken::String))
2662 return TokError("expected string in '.incbin' directive");
2664 std::string Filename = getTok().getString();
2665 SMLoc IncbinLoc = getLexer().getLoc();
2668 if (getLexer().isNot(AsmToken::EndOfStatement))
2669 return TokError("unexpected token in '.incbin' directive");
2671 // Strip the quotes.
2672 Filename = Filename.substr(1, Filename.size()-2);
2674 // Attempt to process the included file.
2675 if (ProcessIncbinFile(Filename)) {
2676 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2683 /// ParseDirectiveIf
2684 /// ::= .if expression
2685 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2686 TheCondStack.push_back(TheCondState);
2687 TheCondState.TheCond = AsmCond::IfCond;
2688 if (TheCondState.Ignore) {
2689 EatToEndOfStatement();
2692 if (ParseAbsoluteExpression(ExprValue))
2695 if (getLexer().isNot(AsmToken::EndOfStatement))
2696 return TokError("unexpected token in '.if' directive");
2700 TheCondState.CondMet = ExprValue;
2701 TheCondState.Ignore = !TheCondState.CondMet;
2707 /// ParseDirectiveIfb
2709 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2710 TheCondStack.push_back(TheCondState);
2711 TheCondState.TheCond = AsmCond::IfCond;
2713 if (TheCondState.Ignore) {
2714 EatToEndOfStatement();
2716 StringRef Str = ParseStringToEndOfStatement();
2718 if (getLexer().isNot(AsmToken::EndOfStatement))
2719 return TokError("unexpected token in '.ifb' directive");
2723 TheCondState.CondMet = ExpectBlank == Str.empty();
2724 TheCondState.Ignore = !TheCondState.CondMet;
2730 /// ParseDirectiveIfc
2731 /// ::= .ifc string1, string2
2732 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2733 TheCondStack.push_back(TheCondState);
2734 TheCondState.TheCond = AsmCond::IfCond;
2736 if (TheCondState.Ignore) {
2737 EatToEndOfStatement();
2739 StringRef Str1 = ParseStringToComma();
2741 if (getLexer().isNot(AsmToken::Comma))
2742 return TokError("unexpected token in '.ifc' directive");
2746 StringRef Str2 = ParseStringToEndOfStatement();
2748 if (getLexer().isNot(AsmToken::EndOfStatement))
2749 return TokError("unexpected token in '.ifc' directive");
2753 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2754 TheCondState.Ignore = !TheCondState.CondMet;
2760 /// ParseDirectiveIfdef
2761 /// ::= .ifdef symbol
2762 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2764 TheCondStack.push_back(TheCondState);
2765 TheCondState.TheCond = AsmCond::IfCond;
2767 if (TheCondState.Ignore) {
2768 EatToEndOfStatement();
2770 if (ParseIdentifier(Name))
2771 return TokError("expected identifier after '.ifdef'");
2775 MCSymbol *Sym = getContext().LookupSymbol(Name);
2778 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2780 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2781 TheCondState.Ignore = !TheCondState.CondMet;
2787 /// ParseDirectiveElseIf
2788 /// ::= .elseif expression
2789 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2790 if (TheCondState.TheCond != AsmCond::IfCond &&
2791 TheCondState.TheCond != AsmCond::ElseIfCond)
2792 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2794 TheCondState.TheCond = AsmCond::ElseIfCond;
2796 bool LastIgnoreState = false;
2797 if (!TheCondStack.empty())
2798 LastIgnoreState = TheCondStack.back().Ignore;
2799 if (LastIgnoreState || TheCondState.CondMet) {
2800 TheCondState.Ignore = true;
2801 EatToEndOfStatement();
2805 if (ParseAbsoluteExpression(ExprValue))
2808 if (getLexer().isNot(AsmToken::EndOfStatement))
2809 return TokError("unexpected token in '.elseif' directive");
2812 TheCondState.CondMet = ExprValue;
2813 TheCondState.Ignore = !TheCondState.CondMet;
2819 /// ParseDirectiveElse
2821 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2822 if (getLexer().isNot(AsmToken::EndOfStatement))
2823 return TokError("unexpected token in '.else' directive");
2827 if (TheCondState.TheCond != AsmCond::IfCond &&
2828 TheCondState.TheCond != AsmCond::ElseIfCond)
2829 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2831 TheCondState.TheCond = AsmCond::ElseCond;
2832 bool LastIgnoreState = false;
2833 if (!TheCondStack.empty())
2834 LastIgnoreState = TheCondStack.back().Ignore;
2835 if (LastIgnoreState || TheCondState.CondMet)
2836 TheCondState.Ignore = true;
2838 TheCondState.Ignore = false;
2843 /// ParseDirectiveEndIf
2845 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2846 if (getLexer().isNot(AsmToken::EndOfStatement))
2847 return TokError("unexpected token in '.endif' directive");
2851 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2852 TheCondStack.empty())
2853 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2855 if (!TheCondStack.empty()) {
2856 TheCondState = TheCondStack.back();
2857 TheCondStack.pop_back();
2863 void AsmParser::initializeDirectiveKindMapping() {
2864 DirectiveKindMapping[".set"] = DK_SET;
2865 DirectiveKindMapping[".equ"] = DK_EQU;
2866 DirectiveKindMapping[".equiv"] = DK_EQUIV;
2867 DirectiveKindMapping[".ascii"] = DK_ASCII;
2868 DirectiveKindMapping[".asciz"] = DK_ASCIZ;
2869 DirectiveKindMapping[".string"] = DK_STRING;
2870 DirectiveKindMapping[".byte"] = DK_BYTE;
2871 DirectiveKindMapping[".short"] = DK_SHORT;
2872 DirectiveKindMapping[".value"] = DK_VALUE;
2873 DirectiveKindMapping[".2byte"] = DK_2BYTE;
2874 DirectiveKindMapping[".long"] = DK_LONG;
2875 DirectiveKindMapping[".int"] = DK_INT;
2876 DirectiveKindMapping[".4byte"] = DK_4BYTE;
2877 DirectiveKindMapping[".quad"] = DK_QUAD;
2878 DirectiveKindMapping[".8byte"] = DK_8BYTE;
2879 DirectiveKindMapping[".single"] = DK_SINGLE;
2880 DirectiveKindMapping[".float"] = DK_FLOAT;
2881 DirectiveKindMapping[".double"] = DK_DOUBLE;
2882 DirectiveKindMapping[".align"] = DK_ALIGN;
2883 DirectiveKindMapping[".align32"] = DK_ALIGN32;
2884 DirectiveKindMapping[".balign"] = DK_BALIGN;
2885 DirectiveKindMapping[".balignw"] = DK_BALIGNW;
2886 DirectiveKindMapping[".balignl"] = DK_BALIGNL;
2887 DirectiveKindMapping[".p2align"] = DK_P2ALIGN;
2888 DirectiveKindMapping[".p2alignw"] = DK_P2ALIGNW;
2889 DirectiveKindMapping[".p2alignl"] = DK_P2ALIGNL;
2890 DirectiveKindMapping[".org"] = DK_ORG;
2891 DirectiveKindMapping[".fill"] = DK_FILL;
2892 DirectiveKindMapping[".zero"] = DK_ZERO;
2893 DirectiveKindMapping[".extern"] = DK_EXTERN;
2894 DirectiveKindMapping[".globl"] = DK_GLOBL;
2895 DirectiveKindMapping[".global"] = DK_GLOBAL;
2896 DirectiveKindMapping[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
2897 DirectiveKindMapping[".lazy_reference"] = DK_LAZY_REFERENCE;
2898 DirectiveKindMapping[".no_dead_strip"] = DK_NO_DEAD_STRIP;
2899 DirectiveKindMapping[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
2900 DirectiveKindMapping[".private_extern"] = DK_PRIVATE_EXTERN;
2901 DirectiveKindMapping[".reference"] = DK_REFERENCE;
2902 DirectiveKindMapping[".weak_definition"] = DK_WEAK_DEFINITION;
2903 DirectiveKindMapping[".weak_reference"] = DK_WEAK_REFERENCE;
2904 DirectiveKindMapping[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
2905 DirectiveKindMapping[".comm"] = DK_COMM;
2906 DirectiveKindMapping[".common"] = DK_COMMON;
2907 DirectiveKindMapping[".lcomm"] = DK_LCOMM;
2908 DirectiveKindMapping[".abort"] = DK_ABORT;
2909 DirectiveKindMapping[".include"] = DK_INCLUDE;
2910 DirectiveKindMapping[".incbin"] = DK_INCBIN;
2911 DirectiveKindMapping[".code16"] = DK_CODE16;
2912 DirectiveKindMapping[".code16gcc"] = DK_CODE16GCC;
2913 DirectiveKindMapping[".rept"] = DK_REPT;
2914 DirectiveKindMapping[".irp"] = DK_IRP;
2915 DirectiveKindMapping[".irpc"] = DK_IRPC;
2916 DirectiveKindMapping[".endr"] = DK_ENDR;
2917 DirectiveKindMapping[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
2918 DirectiveKindMapping[".bundle_lock"] = DK_BUNDLE_LOCK;
2919 DirectiveKindMapping[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
2920 DirectiveKindMapping[".if"] = DK_IF;
2921 DirectiveKindMapping[".ifb"] = DK_IFB;
2922 DirectiveKindMapping[".ifnb"] = DK_IFNB;
2923 DirectiveKindMapping[".ifc"] = DK_IFC;
2924 DirectiveKindMapping[".ifnc"] = DK_IFNC;
2925 DirectiveKindMapping[".ifdef"] = DK_IFDEF;
2926 DirectiveKindMapping[".ifndef"] = DK_IFNDEF;
2927 DirectiveKindMapping[".ifnotdef"] = DK_IFNOTDEF;
2928 DirectiveKindMapping[".elseif"] = DK_ELSEIF;
2929 DirectiveKindMapping[".else"] = DK_ELSE;
2930 DirectiveKindMapping[".endif"] = DK_ENDIF;
2933 /// ParseDirectiveFile
2934 /// ::= .file [number] filename
2935 /// ::= .file number directory filename
2936 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2937 // FIXME: I'm not sure what this is.
2938 int64_t FileNumber = -1;
2939 SMLoc FileNumberLoc = getLexer().getLoc();
2940 if (getLexer().is(AsmToken::Integer)) {
2941 FileNumber = getTok().getIntVal();
2945 return TokError("file number less than one");
2948 if (getLexer().isNot(AsmToken::String))
2949 return TokError("unexpected token in '.file' directive");
2951 // Usually the directory and filename together, otherwise just the directory.
2952 StringRef Path = getTok().getString();
2953 Path = Path.substr(1, Path.size()-2);
2956 StringRef Directory;
2958 if (getLexer().is(AsmToken::String)) {
2959 if (FileNumber == -1)
2960 return TokError("explicit path specified, but no file number");
2961 Filename = getTok().getString();
2962 Filename = Filename.substr(1, Filename.size()-2);
2969 if (getLexer().isNot(AsmToken::EndOfStatement))
2970 return TokError("unexpected token in '.file' directive");
2972 if (FileNumber == -1)
2973 getStreamer().EmitFileDirective(Filename);
2975 if (getContext().getGenDwarfForAssembly() == true)
2976 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2977 "used to generate dwarf debug info for assembly code");
2979 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2980 Error(FileNumberLoc, "file number already allocated");
2986 /// ParseDirectiveLine
2987 /// ::= .line [number]
2988 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2989 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2990 if (getLexer().isNot(AsmToken::Integer))
2991 return TokError("unexpected token in '.line' directive");
2993 int64_t LineNumber = getTok().getIntVal();
2997 // FIXME: Do something with the .line.
3000 if (getLexer().isNot(AsmToken::EndOfStatement))
3001 return TokError("unexpected token in '.line' directive");
3007 /// ParseDirectiveLoc
3008 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3009 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3010 /// The first number is a file number, must have been previously assigned with
3011 /// a .file directive, the second number is the line number and optionally the
3012 /// third number is a column position (zero if not specified). The remaining
3013 /// optional items are .loc sub-directives.
3014 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
3016 if (getLexer().isNot(AsmToken::Integer))
3017 return TokError("unexpected token in '.loc' directive");
3018 int64_t FileNumber = getTok().getIntVal();
3020 return TokError("file number less than one in '.loc' directive");
3021 if (!getContext().isValidDwarfFileNumber(FileNumber))
3022 return TokError("unassigned file number in '.loc' directive");
3025 int64_t LineNumber = 0;
3026 if (getLexer().is(AsmToken::Integer)) {
3027 LineNumber = getTok().getIntVal();
3029 return TokError("line number less than one in '.loc' directive");
3033 int64_t ColumnPos = 0;
3034 if (getLexer().is(AsmToken::Integer)) {
3035 ColumnPos = getTok().getIntVal();
3037 return TokError("column position less than zero in '.loc' directive");
3041 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3043 int64_t Discriminator = 0;
3044 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3046 if (getLexer().is(AsmToken::EndOfStatement))
3050 SMLoc Loc = getTok().getLoc();
3051 if (getParser().ParseIdentifier(Name))
3052 return TokError("unexpected token in '.loc' directive");
3054 if (Name == "basic_block")
3055 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3056 else if (Name == "prologue_end")
3057 Flags |= DWARF2_FLAG_PROLOGUE_END;
3058 else if (Name == "epilogue_begin")
3059 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3060 else if (Name == "is_stmt") {
3061 Loc = getTok().getLoc();
3062 const MCExpr *Value;
3063 if (getParser().ParseExpression(Value))
3065 // The expression must be the constant 0 or 1.
3066 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3067 int Value = MCE->getValue();
3069 Flags &= ~DWARF2_FLAG_IS_STMT;
3070 else if (Value == 1)
3071 Flags |= DWARF2_FLAG_IS_STMT;
3073 return Error(Loc, "is_stmt value not 0 or 1");
3076 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3079 else if (Name == "isa") {
3080 Loc = getTok().getLoc();
3081 const MCExpr *Value;
3082 if (getParser().ParseExpression(Value))
3084 // The expression must be a constant greater or equal to 0.
3085 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3086 int Value = MCE->getValue();
3088 return Error(Loc, "isa number less than zero");
3092 return Error(Loc, "isa number not a constant value");
3095 else if (Name == "discriminator") {
3096 if (getParser().ParseAbsoluteExpression(Discriminator))
3100 return Error(Loc, "unknown sub-directive in '.loc' directive");
3103 if (getLexer().is(AsmToken::EndOfStatement))
3108 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3109 Isa, Discriminator, StringRef());
3114 /// ParseDirectiveStabs
3115 /// ::= .stabs string, number, number, number
3116 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
3117 SMLoc DirectiveLoc) {
3118 return TokError("unsupported directive '" + Directive + "'");
3121 /// ParseDirectiveSpace
3122 /// ::= .space expression [ , expression ]
3123 bool GenericAsmParser::ParseDirectiveSpace(StringRef, SMLoc DirectiveLoc) {
3124 getParser().CheckForValidSection();
3127 if (getParser().ParseAbsoluteExpression(NumBytes))
3130 int64_t FillExpr = 0;
3131 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3132 if (getLexer().isNot(AsmToken::Comma))
3133 return TokError("unexpected token in '.space' directive");
3136 if (getParser().ParseAbsoluteExpression(FillExpr))
3139 if (getLexer().isNot(AsmToken::EndOfStatement))
3140 return TokError("unexpected token in '.space' directive");
3146 return TokError("invalid number of bytes in '.space' directive");
3148 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3149 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3154 /// ParseDirectiveCFISections
3155 /// ::= .cfi_sections section [, section]
3156 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
3157 SMLoc DirectiveLoc) {
3162 if (getParser().ParseIdentifier(Name))
3163 return TokError("Expected an identifier");
3165 if (Name == ".eh_frame")
3167 else if (Name == ".debug_frame")
3170 if (getLexer().is(AsmToken::Comma)) {
3173 if (getParser().ParseIdentifier(Name))
3174 return TokError("Expected an identifier");
3176 if (Name == ".eh_frame")
3178 else if (Name == ".debug_frame")
3182 getStreamer().EmitCFISections(EH, Debug);
3187 /// ParseDirectiveCFIStartProc
3188 /// ::= .cfi_startproc
3189 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
3190 SMLoc DirectiveLoc) {
3191 getStreamer().EmitCFIStartProc();
3195 /// ParseDirectiveCFIEndProc
3196 /// ::= .cfi_endproc
3197 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
3198 getStreamer().EmitCFIEndProc();
3202 /// ParseRegisterOrRegisterNumber - parse register name or number.
3203 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3204 SMLoc DirectiveLoc) {
3207 if (getLexer().isNot(AsmToken::Integer)) {
3208 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3211 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
3213 return getParser().ParseAbsoluteExpression(Register);
3218 /// ParseDirectiveCFIDefCfa
3219 /// ::= .cfi_def_cfa register, offset
3220 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3221 SMLoc DirectiveLoc) {
3222 int64_t Register = 0;
3223 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3226 if (getLexer().isNot(AsmToken::Comma))
3227 return TokError("unexpected token in directive");
3231 if (getParser().ParseAbsoluteExpression(Offset))
3234 getStreamer().EmitCFIDefCfa(Register, Offset);
3238 /// ParseDirectiveCFIDefCfaOffset
3239 /// ::= .cfi_def_cfa_offset offset
3240 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3241 SMLoc DirectiveLoc) {
3243 if (getParser().ParseAbsoluteExpression(Offset))
3246 getStreamer().EmitCFIDefCfaOffset(Offset);
3250 /// ParseDirectiveCFIAdjustCfaOffset
3251 /// ::= .cfi_adjust_cfa_offset adjustment
3252 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3253 SMLoc DirectiveLoc) {
3254 int64_t Adjustment = 0;
3255 if (getParser().ParseAbsoluteExpression(Adjustment))
3258 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3262 /// ParseDirectiveCFIDefCfaRegister
3263 /// ::= .cfi_def_cfa_register register
3264 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3265 SMLoc DirectiveLoc) {
3266 int64_t Register = 0;
3267 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3270 getStreamer().EmitCFIDefCfaRegister(Register);
3274 /// ParseDirectiveCFIOffset
3275 /// ::= .cfi_offset register, offset
3276 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3277 int64_t Register = 0;
3280 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3283 if (getLexer().isNot(AsmToken::Comma))
3284 return TokError("unexpected token in directive");
3287 if (getParser().ParseAbsoluteExpression(Offset))
3290 getStreamer().EmitCFIOffset(Register, Offset);
3294 /// ParseDirectiveCFIRelOffset
3295 /// ::= .cfi_rel_offset register, offset
3296 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3297 SMLoc DirectiveLoc) {
3298 int64_t Register = 0;
3300 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3303 if (getLexer().isNot(AsmToken::Comma))
3304 return TokError("unexpected token in directive");
3308 if (getParser().ParseAbsoluteExpression(Offset))
3311 getStreamer().EmitCFIRelOffset(Register, Offset);
3315 static bool isValidEncoding(int64_t Encoding) {
3316 if (Encoding & ~0xff)
3319 if (Encoding == dwarf::DW_EH_PE_omit)
3322 const unsigned Format = Encoding & 0xf;
3323 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3324 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3325 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3326 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3329 const unsigned Application = Encoding & 0x70;
3330 if (Application != dwarf::DW_EH_PE_absptr &&
3331 Application != dwarf::DW_EH_PE_pcrel)
3337 /// ParseDirectiveCFIPersonalityOrLsda
3338 /// ::= .cfi_personality encoding, [symbol_name]
3339 /// ::= .cfi_lsda encoding, [symbol_name]
3340 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
3341 SMLoc DirectiveLoc) {
3342 int64_t Encoding = 0;
3343 if (getParser().ParseAbsoluteExpression(Encoding))
3345 if (Encoding == dwarf::DW_EH_PE_omit)
3348 if (!isValidEncoding(Encoding))
3349 return TokError("unsupported encoding.");
3351 if (getLexer().isNot(AsmToken::Comma))
3352 return TokError("unexpected token in directive");
3356 if (getParser().ParseIdentifier(Name))
3357 return TokError("expected identifier in directive");
3359 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3361 if (IDVal == ".cfi_personality")
3362 getStreamer().EmitCFIPersonality(Sym, Encoding);
3364 assert(IDVal == ".cfi_lsda");
3365 getStreamer().EmitCFILsda(Sym, Encoding);
3370 /// ParseDirectiveCFIRememberState
3371 /// ::= .cfi_remember_state
3372 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3373 SMLoc DirectiveLoc) {
3374 getStreamer().EmitCFIRememberState();
3378 /// ParseDirectiveCFIRestoreState
3379 /// ::= .cfi_remember_state
3380 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3381 SMLoc DirectiveLoc) {
3382 getStreamer().EmitCFIRestoreState();
3386 /// ParseDirectiveCFISameValue
3387 /// ::= .cfi_same_value register
3388 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3389 SMLoc DirectiveLoc) {
3390 int64_t Register = 0;
3392 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3395 getStreamer().EmitCFISameValue(Register);
3400 /// ParseDirectiveCFIRestore
3401 /// ::= .cfi_restore register
3402 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
3403 SMLoc DirectiveLoc) {
3404 int64_t Register = 0;
3405 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3408 getStreamer().EmitCFIRestore(Register);
3413 /// ParseDirectiveCFIEscape
3414 /// ::= .cfi_escape expression[,...]
3415 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3416 SMLoc DirectiveLoc) {
3419 if (getParser().ParseAbsoluteExpression(CurrValue))
3422 Values.push_back((uint8_t)CurrValue);
3424 while (getLexer().is(AsmToken::Comma)) {
3427 if (getParser().ParseAbsoluteExpression(CurrValue))
3430 Values.push_back((uint8_t)CurrValue);
3433 getStreamer().EmitCFIEscape(Values);
3437 /// ParseDirectiveCFISignalFrame
3438 /// ::= .cfi_signal_frame
3439 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3440 SMLoc DirectiveLoc) {
3441 if (getLexer().isNot(AsmToken::EndOfStatement))
3442 return Error(getLexer().getLoc(),
3443 "unexpected token in '" + Directive + "' directive");
3445 getStreamer().EmitCFISignalFrame();
3450 /// ParseDirectiveCFIUndefined
3451 /// ::= .cfi_undefined register
3452 bool GenericAsmParser::ParseDirectiveCFIUndefined(StringRef Directive,
3453 SMLoc DirectiveLoc) {
3454 int64_t Register = 0;
3456 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3459 getStreamer().EmitCFIUndefined(Register);
3464 /// ParseDirectiveCFIRegister
3465 /// ::= .cfi_register register, register
3466 bool GenericAsmParser::ParseDirectiveCFIRegister(StringRef Directive,
3467 SMLoc DirectiveLoc) {
3468 int64_t Register1 = 0;
3470 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3473 if (getLexer().isNot(AsmToken::Comma))
3474 return TokError("unexpected token in directive");
3477 int64_t Register2 = 0;
3479 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3482 getStreamer().EmitCFIRegister(Register1, Register2);
3487 /// ParseDirectiveMacrosOnOff
3490 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3491 SMLoc DirectiveLoc) {
3492 if (getLexer().isNot(AsmToken::EndOfStatement))
3493 return Error(getLexer().getLoc(),
3494 "unexpected token in '" + Directive + "' directive");
3496 getParser().SetMacrosEnabled(Directive == ".macros_on");
3501 /// ParseDirectiveMacro
3502 /// ::= .macro name [parameters]
3503 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3504 SMLoc DirectiveLoc) {
3506 if (getParser().ParseIdentifier(Name))
3507 return TokError("expected identifier in '.macro' directive");
3509 MCAsmMacroParameters Parameters;
3510 // Argument delimiter is initially unknown. It will be set by
3511 // ParseMacroArgument()
3512 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3513 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3515 MCAsmMacroParameter Parameter;
3516 if (getParser().ParseIdentifier(Parameter.first))
3517 return TokError("expected identifier in '.macro' directive");
3519 if (getLexer().is(AsmToken::Equal)) {
3521 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3525 Parameters.push_back(Parameter);
3527 if (getLexer().is(AsmToken::Comma))
3529 else if (getLexer().is(AsmToken::EndOfStatement))
3534 // Eat the end of statement.
3537 AsmToken EndToken, StartToken = getTok();
3539 // Lex the macro definition.
3541 // Check whether we have reached the end of the file.
3542 if (getLexer().is(AsmToken::Eof))
3543 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3545 // Otherwise, check whether we have reach the .endmacro.
3546 if (getLexer().is(AsmToken::Identifier) &&
3547 (getTok().getIdentifier() == ".endm" ||
3548 getTok().getIdentifier() == ".endmacro")) {
3549 EndToken = getTok();
3551 if (getLexer().isNot(AsmToken::EndOfStatement))
3552 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3557 // Otherwise, scan til the end of the statement.
3558 getParser().EatToEndOfStatement();
3561 if (getParser().LookupMacro(Name)) {
3562 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3565 const char *BodyStart = StartToken.getLoc().getPointer();
3566 const char *BodyEnd = EndToken.getLoc().getPointer();
3567 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3568 getParser().DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3572 /// ParseDirectiveEndMacro
3575 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3576 SMLoc DirectiveLoc) {
3577 if (getLexer().isNot(AsmToken::EndOfStatement))
3578 return TokError("unexpected token in '" + Directive + "' directive");
3580 // If we are inside a macro instantiation, terminate the current
3582 if (getParser().InsideMacroInstantiation()) {
3583 getParser().HandleMacroExit();
3587 // Otherwise, this .endmacro is a stray entry in the file; well formed
3588 // .endmacro directives are handled during the macro definition parsing.
3589 return TokError("unexpected '" + Directive + "' in file, "
3590 "no current macro definition");
3593 /// ParseDirectivePurgeMacro
3595 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3596 SMLoc DirectiveLoc) {
3598 if (getParser().ParseIdentifier(Name))
3599 return TokError("expected identifier in '.purgem' directive");
3601 if (getLexer().isNot(AsmToken::EndOfStatement))
3602 return TokError("unexpected token in '.purgem' directive");
3604 if (!getParser().LookupMacro(Name))
3605 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3607 getParser().UndefineMacro(Name);
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 MCAsmMacro *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 MCAsmMacroParameters Parameters;
3672 return new MCAsmMacro(Name, Body, Parameters);
3675 void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *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 MCAsmMacro *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 MCAsmMacroParameters Parameters;
3719 MCAsmMacroArguments A;
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 MCAsmMacroParameters Parameters;
3734 MCAsmMacroParameter 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");
3746 MCAsmMacroArguments A;
3747 if (ParseMacroArguments(0, A))
3750 // Eat the end of statement.
3753 // Lex the irp definition.
3754 MCAsmMacro *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 (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3764 MCAsmMacroArguments 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 MCAsmMacroParameters Parameters;
3780 MCAsmMacroParameter 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");
3792 MCAsmMacroArguments A;
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 MCAsmMacro *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) {
3815 MCAsmMacroArgument Arg;
3816 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3818 MCAsmMacroArguments 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);