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"));
51 /// \brief Helper class for tracking macro definitions.
52 typedef std::vector<AsmToken> MacroArgument;
53 typedef std::vector<MacroArgument> MacroArguments;
54 typedef std::pair<StringRef, MacroArgument> MacroParameter;
55 typedef std::vector<MacroParameter> MacroParameters;
60 MacroParameters Parameters;
63 Macro(StringRef N, StringRef B, const MacroParameters &P) :
64 Name(N), Body(B), Parameters(P) {}
67 /// \brief Helper class for storing information about an active macro
69 struct MacroInstantiation {
70 /// The macro being instantiated.
71 const Macro *TheMacro;
73 /// The macro instantiation with substitutions.
74 MemoryBuffer *Instantiation;
76 /// The location of the instantiation.
77 SMLoc InstantiationLoc;
79 /// The location where parsing should resume upon instantiation completion.
83 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
87 /// \brief The concrete assembly parser instance.
88 class AsmParser : public MCAsmParser {
89 friend class GenericAsmParser;
91 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
92 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
99 SourceMgr::DiagHandlerTy SavedDiagHandler;
100 void *SavedDiagContext;
101 MCAsmParserExtension *GenericParser;
102 MCAsmParserExtension *PlatformParser;
104 /// This is the current buffer index we're lexing from as managed by the
105 /// SourceMgr object.
108 AsmCond TheCondState;
109 std::vector<AsmCond> TheCondStack;
111 /// DirectiveMap - This is a table handlers for directives. Each handler is
112 /// invoked after the directive identifier is read and is responsible for
113 /// parsing and validating the rest of the directive. The handler is passed
114 /// in the directive name and the location of the directive keyword.
115 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
117 /// MacroMap - Map of currently defined macros.
118 StringMap<Macro*> MacroMap;
120 /// ActiveMacros - Stack of active macro instantiations.
121 std::vector<MacroInstantiation*> ActiveMacros;
123 /// Boolean tracking whether macro substitution is enabled.
124 unsigned MacrosEnabled : 1;
126 /// Flag tracking whether any errors have been encountered.
127 unsigned HadError : 1;
129 /// The values from the last parsed cpp hash file line comment if any.
130 StringRef CppHashFilename;
131 int64_t CppHashLineNumber;
134 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
135 unsigned AssemblerDialect;
137 /// IsDarwin - is Darwin compatibility enabled?
140 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
141 bool ParsingInlineAsm;
143 /// ParsedOperands - The parsed operands from the last parsed statement.
144 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
146 /// Opcode - The opcode from the last parsed instruction. This is MS-style
147 /// inline asm specific.
151 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
152 const MCAsmInfo &MAI);
153 virtual ~AsmParser();
155 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
157 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
159 DirectiveHandler Handler) {
160 DirectiveMap[Directive] = std::make_pair(Object, Handler);
164 /// @name MCAsmParser Interface
167 virtual SourceMgr &getSourceManager() { return SrcMgr; }
168 virtual MCAsmLexer &getLexer() { return Lexer; }
169 virtual MCContext &getContext() { return Ctx; }
170 virtual MCStreamer &getStreamer() { return Out; }
171 virtual unsigned getAssemblerDialect() {
172 if (AssemblerDialect == ~0U)
173 return MAI.getAssemblerDialect();
175 return AssemblerDialect;
177 virtual void setAssemblerDialect(unsigned i) {
178 AssemblerDialect = i;
181 virtual bool Warning(SMLoc L, const Twine &Msg,
182 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
183 virtual bool Error(SMLoc L, const Twine &Msg,
184 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
186 virtual const AsmToken &Lex();
188 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
189 bool isParsingInlineAsm() { return ParsingInlineAsm; }
191 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
192 unsigned &NumOutputs, unsigned &NumInputs,
193 SmallVectorImpl<void *> &Names,
194 SmallVectorImpl<std::string> &Constraints,
195 SmallVectorImpl<void *> &Exprs,
196 SmallVectorImpl<std::string> &Clobbers,
197 const MCInstrInfo *MII,
198 const MCInstPrinter *IP,
199 MCAsmParserSemaCallback &SI);
201 bool ParseExpression(const MCExpr *&Res);
202 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
203 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
204 virtual bool ParseAbsoluteExpression(int64_t &Res);
209 void CheckForValidSection();
211 bool ParseStatement();
212 void EatToEndOfLine();
213 bool ParseCppHashLineFilenameComment(const SMLoc &L);
215 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
216 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
217 const MacroParameters &Parameters,
218 const MacroArguments &A,
220 void HandleMacroExit();
222 void PrintMacroInstantiations();
223 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
224 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
225 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
227 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
229 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
230 bool EnterIncludeFile(const std::string &Filename);
231 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
232 /// This returns true on failure.
233 bool ProcessIncbinFile(const std::string &Filename);
235 /// \brief Reset the current lexer position to that given by \p Loc. The
236 /// current token is not set; clients should ensure Lex() is called
238 void JumpToLoc(SMLoc Loc);
240 virtual void EatToEndOfStatement();
242 bool ParseMacroArgument(MacroArgument &MA,
243 AsmToken::TokenKind &ArgumentDelimiter);
244 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
246 /// \brief Parse up to the end of statement and a return the contents from the
247 /// current token until the end of the statement; the current token on exit
248 /// will be either the EndOfStatement or EOF.
249 virtual StringRef ParseStringToEndOfStatement();
251 /// \brief Parse until the end of a statement or a comma is encountered,
252 /// return the contents from the current token up to the end or comma.
253 StringRef ParseStringToComma();
255 bool ParseAssignment(StringRef Name, bool allow_redef,
256 bool NoDeadStrip = false);
258 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
259 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
260 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
261 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
263 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
264 /// and set \p Res to the identifier contents.
265 virtual bool ParseIdentifier(StringRef &Res);
267 // Directive Parsing.
269 // ".ascii", ".asciiz", ".string"
270 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
271 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
272 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
273 bool ParseDirectiveFill(); // ".fill"
274 bool ParseDirectiveSpace(); // ".space"
275 bool ParseDirectiveZero(); // ".zero"
276 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
277 bool ParseDirectiveOrg(); // ".org"
278 // ".align{,32}", ".p2align{,w,l}"
279 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
281 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
282 /// accepts a single symbol (which should be a label or an external).
283 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
285 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
287 bool ParseDirectiveAbort(); // ".abort"
288 bool ParseDirectiveInclude(); // ".include"
289 bool ParseDirectiveIncbin(); // ".incbin"
291 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
292 // ".ifb" or ".ifnb", depending on ExpectBlank.
293 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
294 // ".ifc" or ".ifnc", depending on ExpectEqual.
295 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
296 // ".ifdef" or ".ifndef", depending on expect_defined
297 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
298 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
299 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
300 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
302 /// ParseEscapedString - Parse the current token as a string which may include
303 /// escaped characters and return the string contents.
304 bool ParseEscapedString(std::string &Data);
306 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
307 MCSymbolRefExpr::VariantKind Variant);
309 // Macro-like directives
310 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
311 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
312 raw_svector_ostream &OS);
313 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
314 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
315 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
316 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
318 // MS-style inline assembly parsing.
319 bool isInstruction() { return Opcode != (unsigned)~0x0; }
320 unsigned getOpcode() { return Opcode; }
323 /// \brief Generic implementations of directive handling, etc. which is shared
324 /// (or the default, at least) for all assembler parser.
325 class GenericAsmParser : public MCAsmParserExtension {
326 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
327 void AddDirectiveHandler(StringRef Directive) {
328 getParser().AddDirectiveHandler(this, Directive,
329 HandleDirective<GenericAsmParser, Handler>);
332 GenericAsmParser() {}
334 AsmParser &getParser() {
335 return (AsmParser&) this->MCAsmParserExtension::getParser();
338 virtual void Initialize(MCAsmParser &Parser) {
339 // Call the base implementation.
340 this->MCAsmParserExtension::Initialize(Parser);
342 // Debugging directives.
343 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
344 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
345 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
346 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
349 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
351 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
353 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
355 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
357 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
358 ".cfi_def_cfa_offset");
359 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
360 ".cfi_adjust_cfa_offset");
361 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
362 ".cfi_def_cfa_register");
363 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
365 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
368 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
370 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
372 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
374 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
376 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
378 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
380 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
382 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
385 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
387 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
389 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
390 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
391 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
392 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
394 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
395 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
398 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
400 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
401 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
402 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
403 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
404 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
405 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
406 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
407 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
408 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
409 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
410 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
411 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
412 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
413 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
414 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
415 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
416 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
417 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
418 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
419 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
421 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
422 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
423 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
424 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
426 bool ParseDirectiveLEB128(StringRef, SMLoc);
433 extern MCAsmParserExtension *createDarwinAsmParser();
434 extern MCAsmParserExtension *createELFAsmParser();
435 extern MCAsmParserExtension *createCOFFAsmParser();
439 enum { DEFAULT_ADDRSPACE = 0 };
441 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
442 MCStreamer &_Out, const MCAsmInfo &_MAI)
443 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
444 GenericParser(new GenericAsmParser), PlatformParser(0),
445 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
446 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false),
448 // Save the old handler.
449 SavedDiagHandler = SrcMgr.getDiagHandler();
450 SavedDiagContext = SrcMgr.getDiagContext();
451 // Set our own handler which calls the saved handler.
452 SrcMgr.setDiagHandler(DiagHandler, this);
453 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
455 // Initialize the generic parser.
456 GenericParser->Initialize(*this);
458 // Initialize the platform / file format parser.
460 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
462 if (_MAI.hasMicrosoftFastStdCallMangling()) {
463 PlatformParser = createCOFFAsmParser();
464 PlatformParser->Initialize(*this);
465 } else if (_MAI.hasSubsectionsViaSymbols()) {
466 PlatformParser = createDarwinAsmParser();
467 PlatformParser->Initialize(*this);
470 PlatformParser = createELFAsmParser();
471 PlatformParser->Initialize(*this);
475 AsmParser::~AsmParser() {
476 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
478 // Destroy any macros.
479 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
480 ie = MacroMap.end(); it != ie; ++it)
481 delete it->getValue();
483 delete PlatformParser;
484 delete GenericParser;
487 void AsmParser::PrintMacroInstantiations() {
488 // Print the active macro instantiation stack.
489 for (std::vector<MacroInstantiation*>::const_reverse_iterator
490 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
491 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
492 "while in macro instantiation");
495 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
496 if (FatalAssemblerWarnings)
497 return Error(L, Msg, Ranges);
498 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
499 PrintMacroInstantiations();
503 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
505 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
506 PrintMacroInstantiations();
510 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
511 std::string IncludedFile;
512 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
518 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
523 /// Process the specified .incbin file by seaching for it in the include paths
524 /// then just emitting the byte contents of the file to the streamer. This
525 /// returns true on failure.
526 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
527 std::string IncludedFile;
528 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
532 // Pick up the bytes from the file and emit them.
533 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
538 void AsmParser::JumpToLoc(SMLoc Loc) {
539 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
540 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
543 const AsmToken &AsmParser::Lex() {
544 const AsmToken *tok = &Lexer.Lex();
546 if (tok->is(AsmToken::Eof)) {
547 // If this is the end of an included file, pop the parent file off the
549 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
550 if (ParentIncludeLoc != SMLoc()) {
551 JumpToLoc(ParentIncludeLoc);
556 if (tok->is(AsmToken::Error))
557 Error(Lexer.getErrLoc(), Lexer.getErr());
562 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
563 // Create the initial section, if requested.
564 if (!NoInitialTextSection)
571 AsmCond StartingCondState = TheCondState;
573 // If we are generating dwarf for assembly source files save the initial text
574 // section and generate a .file directive.
575 if (getContext().getGenDwarfForAssembly()) {
576 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
577 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
578 getStreamer().EmitLabel(SectionStartSym);
579 getContext().setGenDwarfSectionStartSym(SectionStartSym);
580 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
581 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
584 // While we have input, parse each statement.
585 while (Lexer.isNot(AsmToken::Eof)) {
586 if (!ParseStatement()) continue;
588 // We had an error, validate that one was emitted and recover by skipping to
590 assert(HadError && "Parse statement returned an error, but none emitted!");
591 EatToEndOfStatement();
594 if (TheCondState.TheCond != StartingCondState.TheCond ||
595 TheCondState.Ignore != StartingCondState.Ignore)
596 return TokError("unmatched .ifs or .elses");
598 // Check to see there are no empty DwarfFile slots.
599 const std::vector<MCDwarfFile *> &MCDwarfFiles =
600 getContext().getMCDwarfFiles();
601 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
602 if (!MCDwarfFiles[i])
603 TokError("unassigned file number: " + Twine(i) + " for .file directives");
606 // Check to see that all assembler local symbols were actually defined.
607 // Targets that don't do subsections via symbols may not want this, though,
608 // so conservatively exclude them. Only do this if we're finalizing, though,
609 // as otherwise we won't necessarilly have seen everything yet.
610 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
611 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
612 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
615 MCSymbol *Sym = i->getValue();
616 // Variable symbols may not be marked as defined, so check those
617 // explicitly. If we know it's a variable, we have a definition for
618 // the purposes of this check.
619 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
620 // FIXME: We would really like to refer back to where the symbol was
621 // first referenced for a source location. We need to add something
622 // to track that. Currently, we just point to the end of the file.
623 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
624 "assembler local symbol '" + Sym->getName() +
630 // Finalize the output stream if there are no errors and if the client wants
632 if (!HadError && !NoFinalize)
638 void AsmParser::CheckForValidSection() {
639 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
640 TokError("expected section directive before assembly directive");
641 Out.SwitchSection(Ctx.getMachOSection(
643 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
644 0, SectionKind::getText()));
648 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
649 void AsmParser::EatToEndOfStatement() {
650 while (Lexer.isNot(AsmToken::EndOfStatement) &&
651 Lexer.isNot(AsmToken::Eof))
655 if (Lexer.is(AsmToken::EndOfStatement))
659 StringRef AsmParser::ParseStringToEndOfStatement() {
660 const char *Start = getTok().getLoc().getPointer();
662 while (Lexer.isNot(AsmToken::EndOfStatement) &&
663 Lexer.isNot(AsmToken::Eof))
666 const char *End = getTok().getLoc().getPointer();
667 return StringRef(Start, End - Start);
670 StringRef AsmParser::ParseStringToComma() {
671 const char *Start = getTok().getLoc().getPointer();
673 while (Lexer.isNot(AsmToken::EndOfStatement) &&
674 Lexer.isNot(AsmToken::Comma) &&
675 Lexer.isNot(AsmToken::Eof))
678 const char *End = getTok().getLoc().getPointer();
679 return StringRef(Start, End - Start);
682 /// ParseParenExpr - Parse a paren expression and return it.
683 /// NOTE: This assumes the leading '(' has already been consumed.
685 /// parenexpr ::= expr)
687 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
688 if (ParseExpression(Res)) return true;
689 if (Lexer.isNot(AsmToken::RParen))
690 return TokError("expected ')' in parentheses expression");
691 EndLoc = Lexer.getLoc();
696 /// ParseBracketExpr - Parse a bracket expression and return it.
697 /// NOTE: This assumes the leading '[' has already been consumed.
699 /// bracketexpr ::= expr]
701 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
702 if (ParseExpression(Res)) return true;
703 if (Lexer.isNot(AsmToken::RBrac))
704 return TokError("expected ']' in brackets expression");
705 EndLoc = Lexer.getLoc();
710 /// ParsePrimaryExpr - Parse a primary expression and return it.
711 /// primaryexpr ::= (parenexpr
712 /// primaryexpr ::= symbol
713 /// primaryexpr ::= number
714 /// primaryexpr ::= '.'
715 /// primaryexpr ::= ~,+,- primaryexpr
716 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
717 switch (Lexer.getKind()) {
719 return TokError("unknown token in expression");
720 // If we have an error assume that we've already handled it.
721 case AsmToken::Error:
723 case AsmToken::Exclaim:
724 Lex(); // Eat the operator.
725 if (ParsePrimaryExpr(Res, EndLoc))
727 Res = MCUnaryExpr::CreateLNot(Res, getContext());
729 case AsmToken::Dollar:
730 case AsmToken::String:
731 case AsmToken::Identifier: {
732 EndLoc = Lexer.getLoc();
734 StringRef Identifier;
735 if (ParseIdentifier(Identifier))
738 // This is a symbol reference.
739 std::pair<StringRef, StringRef> Split = Identifier.split('@');
740 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
742 // Lookup the symbol variant if used.
743 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
744 if (Split.first.size() != Identifier.size()) {
745 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
746 if (Variant == MCSymbolRefExpr::VK_Invalid) {
747 Variant = MCSymbolRefExpr::VK_None;
748 return TokError("invalid variant '" + Split.second + "'");
752 // If this is an absolute variable reference, substitute it now to preserve
753 // semantics in the face of reassignment.
754 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
756 return Error(EndLoc, "unexpected modifier on variable reference");
758 Res = Sym->getVariableValue();
762 // Otherwise create a symbol ref.
763 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
766 case AsmToken::Integer: {
767 SMLoc Loc = getTok().getLoc();
768 int64_t IntVal = getTok().getIntVal();
769 Res = MCConstantExpr::Create(IntVal, getContext());
770 EndLoc = Lexer.getLoc();
772 // Look for 'b' or 'f' following an Integer as a directional label
773 if (Lexer.getKind() == AsmToken::Identifier) {
774 StringRef IDVal = getTok().getString();
775 if (IDVal == "f" || IDVal == "b"){
776 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
777 IDVal == "f" ? 1 : 0);
778 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
780 if (IDVal == "b" && Sym->isUndefined())
781 return Error(Loc, "invalid reference to undefined symbol");
782 EndLoc = Lexer.getLoc();
783 Lex(); // Eat identifier.
788 case AsmToken::Real: {
789 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
790 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
791 Res = MCConstantExpr::Create(IntVal, getContext());
795 case AsmToken::Dot: {
796 // This is a '.' reference, which references the current PC. Emit a
797 // temporary label to the streamer and refer to it.
798 MCSymbol *Sym = Ctx.CreateTempSymbol();
800 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
801 EndLoc = Lexer.getLoc();
802 Lex(); // Eat identifier.
805 case AsmToken::LParen:
806 Lex(); // Eat the '('.
807 return ParseParenExpr(Res, EndLoc);
808 case AsmToken::LBrac:
809 if (!PlatformParser->HasBracketExpressions())
810 return TokError("brackets expression not supported on this target");
811 Lex(); // Eat the '['.
812 return ParseBracketExpr(Res, EndLoc);
813 case AsmToken::Minus:
814 Lex(); // Eat the operator.
815 if (ParsePrimaryExpr(Res, EndLoc))
817 Res = MCUnaryExpr::CreateMinus(Res, getContext());
820 Lex(); // Eat the operator.
821 if (ParsePrimaryExpr(Res, EndLoc))
823 Res = MCUnaryExpr::CreatePlus(Res, getContext());
825 case AsmToken::Tilde:
826 Lex(); // Eat the operator.
827 if (ParsePrimaryExpr(Res, EndLoc))
829 Res = MCUnaryExpr::CreateNot(Res, getContext());
834 bool AsmParser::ParseExpression(const MCExpr *&Res) {
836 return ParseExpression(Res, EndLoc);
840 AsmParser::ApplyModifierToExpr(const MCExpr *E,
841 MCSymbolRefExpr::VariantKind Variant) {
842 // Recurse over the given expression, rebuilding it to apply the given variant
843 // if there is exactly one symbol.
844 switch (E->getKind()) {
846 case MCExpr::Constant:
849 case MCExpr::SymbolRef: {
850 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
852 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
853 TokError("invalid variant on expression '" +
854 getTok().getIdentifier() + "' (already modified)");
858 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
861 case MCExpr::Unary: {
862 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
863 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
866 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
869 case MCExpr::Binary: {
870 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
871 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
872 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
877 if (!LHS) LHS = BE->getLHS();
878 if (!RHS) RHS = BE->getRHS();
880 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
884 llvm_unreachable("Invalid expression kind!");
887 /// ParseExpression - Parse an expression and return it.
889 /// expr ::= expr &&,|| expr -> lowest.
890 /// expr ::= expr |,^,&,! expr
891 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
892 /// expr ::= expr <<,>> expr
893 /// expr ::= expr +,- expr
894 /// expr ::= expr *,/,% expr -> highest.
895 /// expr ::= primaryexpr
897 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
898 // Parse the expression.
900 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
903 // As a special case, we support 'a op b @ modifier' by rewriting the
904 // expression to include the modifier. This is inefficient, but in general we
905 // expect users to use 'a@modifier op b'.
906 if (Lexer.getKind() == AsmToken::At) {
909 if (Lexer.isNot(AsmToken::Identifier))
910 return TokError("unexpected symbol modifier following '@'");
912 MCSymbolRefExpr::VariantKind Variant =
913 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
914 if (Variant == MCSymbolRefExpr::VK_Invalid)
915 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
917 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
919 return TokError("invalid modifier '" + getTok().getIdentifier() +
920 "' (no symbols present)");
927 // Try to constant fold it up front, if possible.
929 if (Res->EvaluateAsAbsolute(Value))
930 Res = MCConstantExpr::Create(Value, getContext());
935 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
937 return ParseParenExpr(Res, EndLoc) ||
938 ParseBinOpRHS(1, Res, EndLoc);
941 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
944 SMLoc StartLoc = Lexer.getLoc();
945 if (ParseExpression(Expr))
948 if (!Expr->EvaluateAsAbsolute(Res))
949 return Error(StartLoc, "expected absolute expression");
954 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
955 MCBinaryExpr::Opcode &Kind) {
958 return 0; // not a binop.
960 // Lowest Precedence: &&, ||
961 case AsmToken::AmpAmp:
962 Kind = MCBinaryExpr::LAnd;
964 case AsmToken::PipePipe:
965 Kind = MCBinaryExpr::LOr;
969 // Low Precedence: |, &, ^
971 // FIXME: gas seems to support '!' as an infix operator?
973 Kind = MCBinaryExpr::Or;
975 case AsmToken::Caret:
976 Kind = MCBinaryExpr::Xor;
979 Kind = MCBinaryExpr::And;
982 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
983 case AsmToken::EqualEqual:
984 Kind = MCBinaryExpr::EQ;
986 case AsmToken::ExclaimEqual:
987 case AsmToken::LessGreater:
988 Kind = MCBinaryExpr::NE;
991 Kind = MCBinaryExpr::LT;
993 case AsmToken::LessEqual:
994 Kind = MCBinaryExpr::LTE;
996 case AsmToken::Greater:
997 Kind = MCBinaryExpr::GT;
999 case AsmToken::GreaterEqual:
1000 Kind = MCBinaryExpr::GTE;
1003 // Intermediate Precedence: <<, >>
1004 case AsmToken::LessLess:
1005 Kind = MCBinaryExpr::Shl;
1007 case AsmToken::GreaterGreater:
1008 Kind = MCBinaryExpr::Shr;
1011 // High Intermediate Precedence: +, -
1012 case AsmToken::Plus:
1013 Kind = MCBinaryExpr::Add;
1015 case AsmToken::Minus:
1016 Kind = MCBinaryExpr::Sub;
1019 // Highest Precedence: *, /, %
1020 case AsmToken::Star:
1021 Kind = MCBinaryExpr::Mul;
1023 case AsmToken::Slash:
1024 Kind = MCBinaryExpr::Div;
1026 case AsmToken::Percent:
1027 Kind = MCBinaryExpr::Mod;
1033 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1034 /// Res contains the LHS of the expression on input.
1035 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1038 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1039 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1041 // If the next token is lower precedence than we are allowed to eat, return
1042 // successfully with what we ate already.
1043 if (TokPrec < Precedence)
1048 // Eat the next primary expression.
1050 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1052 // If BinOp binds less tightly with RHS than the operator after RHS, let
1053 // the pending operator take RHS as its LHS.
1054 MCBinaryExpr::Opcode Dummy;
1055 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1056 if (TokPrec < NextTokPrec) {
1057 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1060 // Merge LHS and RHS according to operator.
1061 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1066 /// ::= EndOfStatement
1067 /// ::= Label* Directive ...Operands... EndOfStatement
1068 /// ::= Label* Identifier OperandList* EndOfStatement
1069 bool AsmParser::ParseStatement() {
1070 if (Lexer.is(AsmToken::EndOfStatement)) {
1076 // Statements always start with an identifier or are a full line comment.
1077 AsmToken ID = getTok();
1078 SMLoc IDLoc = ID.getLoc();
1080 int64_t LocalLabelVal = -1;
1081 // A full line comment is a '#' as the first token.
1082 if (Lexer.is(AsmToken::Hash))
1083 return ParseCppHashLineFilenameComment(IDLoc);
1085 // Allow an integer followed by a ':' as a directional local label.
1086 if (Lexer.is(AsmToken::Integer)) {
1087 LocalLabelVal = getTok().getIntVal();
1088 if (LocalLabelVal < 0) {
1089 if (!TheCondState.Ignore)
1090 return TokError("unexpected token at start of statement");
1094 IDVal = getTok().getString();
1095 Lex(); // Consume the integer token to be used as an identifier token.
1096 if (Lexer.getKind() != AsmToken::Colon) {
1097 if (!TheCondState.Ignore)
1098 return TokError("unexpected token at start of statement");
1102 } else if (Lexer.is(AsmToken::Dot)) {
1103 // Treat '.' as a valid identifier in this context.
1107 } else if (ParseIdentifier(IDVal)) {
1108 if (!TheCondState.Ignore)
1109 return TokError("unexpected token at start of statement");
1114 // Handle conditional assembly here before checking for skipping. We
1115 // have to do this so that .endif isn't skipped in a ".if 0" block for
1118 return ParseDirectiveIf(IDLoc);
1119 if (IDVal == ".ifb")
1120 return ParseDirectiveIfb(IDLoc, true);
1121 if (IDVal == ".ifnb")
1122 return ParseDirectiveIfb(IDLoc, false);
1123 if (IDVal == ".ifc")
1124 return ParseDirectiveIfc(IDLoc, true);
1125 if (IDVal == ".ifnc")
1126 return ParseDirectiveIfc(IDLoc, false);
1127 if (IDVal == ".ifdef")
1128 return ParseDirectiveIfdef(IDLoc, true);
1129 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1130 return ParseDirectiveIfdef(IDLoc, false);
1131 if (IDVal == ".elseif")
1132 return ParseDirectiveElseIf(IDLoc);
1133 if (IDVal == ".else")
1134 return ParseDirectiveElse(IDLoc);
1135 if (IDVal == ".endif")
1136 return ParseDirectiveEndIf(IDLoc);
1138 // If we are in a ".if 0" block, ignore this statement.
1139 if (TheCondState.Ignore) {
1140 EatToEndOfStatement();
1144 // FIXME: Recurse on local labels?
1146 // See what kind of statement we have.
1147 switch (Lexer.getKind()) {
1148 case AsmToken::Colon: {
1149 CheckForValidSection();
1151 // identifier ':' -> Label.
1154 // Diagnose attempt to use '.' as a label.
1156 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1158 // Diagnose attempt to use a variable as a label.
1160 // FIXME: Diagnostics. Note the location of the definition as a label.
1161 // FIXME: This doesn't diagnose assignment to a symbol which has been
1162 // implicitly marked as external.
1164 if (LocalLabelVal == -1)
1165 Sym = getContext().GetOrCreateSymbol(IDVal);
1167 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1168 if (!Sym->isUndefined() || Sym->isVariable())
1169 return Error(IDLoc, "invalid symbol redefinition");
1174 // If we are generating dwarf for assembly source files then gather the
1175 // info to make a dwarf label entry for this label if needed.
1176 if (getContext().getGenDwarfForAssembly())
1177 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1180 // Consume any end of statement token, if present, to avoid spurious
1181 // AddBlankLine calls().
1182 if (Lexer.is(AsmToken::EndOfStatement)) {
1184 if (Lexer.is(AsmToken::Eof))
1188 return ParseStatement();
1191 case AsmToken::Equal:
1192 // identifier '=' ... -> assignment statement
1195 return ParseAssignment(IDVal, true);
1197 default: // Normal instruction or directive.
1201 // If macros are enabled, check to see if this is a macro instantiation.
1203 if (const Macro *M = MacroMap.lookup(IDVal))
1204 return HandleMacroEntry(IDVal, IDLoc, M);
1206 // Otherwise, we have a normal instruction or directive.
1207 if (IDVal[0] == '.' && IDVal != ".") {
1209 // Target hook for parsing target specific directives.
1210 if (!getTargetParser().ParseDirective(ID))
1213 // Assembler features
1214 if (IDVal == ".set" || IDVal == ".equ")
1215 return ParseDirectiveSet(IDVal, true);
1216 if (IDVal == ".equiv")
1217 return ParseDirectiveSet(IDVal, false);
1221 if (IDVal == ".ascii")
1222 return ParseDirectiveAscii(IDVal, false);
1223 if (IDVal == ".asciz" || IDVal == ".string")
1224 return ParseDirectiveAscii(IDVal, true);
1226 if (IDVal == ".byte")
1227 return ParseDirectiveValue(1);
1228 if (IDVal == ".short")
1229 return ParseDirectiveValue(2);
1230 if (IDVal == ".value")
1231 return ParseDirectiveValue(2);
1232 if (IDVal == ".2byte")
1233 return ParseDirectiveValue(2);
1234 if (IDVal == ".long")
1235 return ParseDirectiveValue(4);
1236 if (IDVal == ".int")
1237 return ParseDirectiveValue(4);
1238 if (IDVal == ".4byte")
1239 return ParseDirectiveValue(4);
1240 if (IDVal == ".quad")
1241 return ParseDirectiveValue(8);
1242 if (IDVal == ".8byte")
1243 return ParseDirectiveValue(8);
1244 if (IDVal == ".single" || IDVal == ".float")
1245 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1246 if (IDVal == ".double")
1247 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1249 if (IDVal == ".align") {
1250 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1251 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1253 if (IDVal == ".align32") {
1254 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1255 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1257 if (IDVal == ".balign")
1258 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1259 if (IDVal == ".balignw")
1260 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1261 if (IDVal == ".balignl")
1262 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1263 if (IDVal == ".p2align")
1264 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1265 if (IDVal == ".p2alignw")
1266 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1267 if (IDVal == ".p2alignl")
1268 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1270 if (IDVal == ".org")
1271 return ParseDirectiveOrg();
1273 if (IDVal == ".fill")
1274 return ParseDirectiveFill();
1275 if (IDVal == ".space" || IDVal == ".skip")
1276 return ParseDirectiveSpace();
1277 if (IDVal == ".zero")
1278 return ParseDirectiveZero();
1280 // Symbol attribute directives
1282 if (IDVal == ".extern") {
1283 EatToEndOfStatement(); // .extern is the default, ignore it.
1286 if (IDVal == ".globl" || IDVal == ".global")
1287 return ParseDirectiveSymbolAttribute(MCSA_Global);
1288 if (IDVal == ".indirect_symbol")
1289 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1290 if (IDVal == ".lazy_reference")
1291 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1292 if (IDVal == ".no_dead_strip")
1293 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1294 if (IDVal == ".symbol_resolver")
1295 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1296 if (IDVal == ".private_extern")
1297 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1298 if (IDVal == ".reference")
1299 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1300 if (IDVal == ".weak_definition")
1301 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1302 if (IDVal == ".weak_reference")
1303 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1304 if (IDVal == ".weak_def_can_be_hidden")
1305 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1307 if (IDVal == ".comm" || IDVal == ".common")
1308 return ParseDirectiveComm(/*IsLocal=*/false);
1309 if (IDVal == ".lcomm")
1310 return ParseDirectiveComm(/*IsLocal=*/true);
1312 if (IDVal == ".abort")
1313 return ParseDirectiveAbort();
1314 if (IDVal == ".include")
1315 return ParseDirectiveInclude();
1316 if (IDVal == ".incbin")
1317 return ParseDirectiveIncbin();
1319 if (IDVal == ".code16" || IDVal == ".code16gcc")
1320 return TokError(Twine(IDVal) + " not supported yet");
1322 // Macro-like directives
1323 if (IDVal == ".rept")
1324 return ParseDirectiveRept(IDLoc);
1325 if (IDVal == ".irp")
1326 return ParseDirectiveIrp(IDLoc);
1327 if (IDVal == ".irpc")
1328 return ParseDirectiveIrpc(IDLoc);
1329 if (IDVal == ".endr")
1330 return ParseDirectiveEndr(IDLoc);
1332 // Look up the handler in the handler table.
1333 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1334 DirectiveMap.lookup(IDVal);
1336 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1339 return Error(IDLoc, "unknown directive");
1342 CheckForValidSection();
1344 // Canonicalize the opcode to lower case.
1345 SmallString<128> OpcodeStr;
1346 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1347 OpcodeStr.push_back(tolower(IDVal[i]));
1349 bool HadError = getTargetParser().ParseInstruction(OpcodeStr.str(), IDLoc,
1352 // Dump the parsed representation, if requested.
1353 if (getShowParsedOperands()) {
1354 SmallString<256> Str;
1355 raw_svector_ostream OS(Str);
1356 OS << "parsed instruction: [";
1357 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1360 ParsedOperands[i]->print(OS);
1364 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1367 // If we are generating dwarf for assembly source files and the current
1368 // section is the initial text section then generate a .loc directive for
1370 if (!HadError && getContext().getGenDwarfForAssembly() &&
1371 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1372 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1373 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1374 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1375 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1379 // If parsing succeeded, match the instruction.
1382 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Opcode,
1383 ParsedOperands, Out,
1388 // Free any parsed operands. If parsing ms-style inline assembly the operands
1389 // will be freed by the ParseMSInlineAsm() function.
1390 if (!ParsingInlineAsm) {
1391 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1392 delete ParsedOperands[i];
1393 ParsedOperands.clear();
1396 // Don't skip the rest of the line, the instruction parser is responsible for
1401 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1402 /// since they may not be able to be tokenized to get to the end of line token.
1403 void AsmParser::EatToEndOfLine() {
1404 if (!Lexer.is(AsmToken::EndOfStatement))
1405 Lexer.LexUntilEndOfLine();
1410 /// ParseCppHashLineFilenameComment as this:
1411 /// ::= # number "filename"
1412 /// or just as a full line comment if it doesn't have a number and a string.
1413 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1414 Lex(); // Eat the hash token.
1416 if (getLexer().isNot(AsmToken::Integer)) {
1417 // Consume the line since in cases it is not a well-formed line directive,
1418 // as if were simply a full line comment.
1423 int64_t LineNumber = getTok().getIntVal();
1426 if (getLexer().isNot(AsmToken::String)) {
1431 StringRef Filename = getTok().getString();
1432 // Get rid of the enclosing quotes.
1433 Filename = Filename.substr(1, Filename.size()-2);
1435 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1437 CppHashFilename = Filename;
1438 CppHashLineNumber = LineNumber;
1440 // Ignore any trailing characters, they're just comment.
1445 /// DiagHandler - will use the last parsed cpp hash line filename comment
1446 /// for the Filename and LineNo if any in the diagnostic.
1447 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1448 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1449 raw_ostream &OS = errs();
1451 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1452 const SMLoc &DiagLoc = Diag.getLoc();
1453 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1454 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1456 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1457 // before printing the message.
1458 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1459 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1460 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1461 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1464 // If we have not parsed a cpp hash line filename comment or the source
1465 // manager changed or buffer changed (like in a nested include) then just
1466 // print the normal diagnostic using its Filename and LineNo.
1467 if (!Parser->CppHashLineNumber ||
1468 &DiagSrcMgr != &Parser->SrcMgr ||
1469 DiagBuf != CppHashBuf) {
1470 if (Parser->SavedDiagHandler)
1471 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1477 // Use the CppHashFilename and calculate a line number based on the
1478 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1480 const std::string Filename = Parser->CppHashFilename;
1482 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1483 int CppHashLocLineNo =
1484 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1485 int LineNo = Parser->CppHashLineNumber - 1 +
1486 (DiagLocLineNo - CppHashLocLineNo);
1488 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1489 Filename, LineNo, Diag.getColumnNo(),
1490 Diag.getKind(), Diag.getMessage(),
1491 Diag.getLineContents(), Diag.getRanges());
1493 if (Parser->SavedDiagHandler)
1494 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1496 NewDiag.print(0, OS);
1499 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1500 // difference being that that function accepts '@' as part of identifiers and
1501 // we can't do that. AsmLexer.cpp should probably be changed to handle
1502 // '@' as a special case when needed.
1503 static bool isIdentifierChar(char c) {
1504 return isalnum(c) || c == '_' || c == '$' || c == '.';
1507 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1508 const MacroParameters &Parameters,
1509 const MacroArguments &A,
1511 unsigned NParameters = Parameters.size();
1512 if (NParameters != 0 && NParameters != A.size())
1513 return Error(L, "Wrong number of arguments");
1515 // A macro without parameters is handled differently on Darwin:
1516 // gas accepts no arguments and does no substitutions
1517 while (!Body.empty()) {
1518 // Scan for the next substitution.
1519 std::size_t End = Body.size(), Pos = 0;
1520 for (; Pos != End; ++Pos) {
1521 // Check for a substitution or escape.
1523 // This macro has no parameters, look for $0, $1, etc.
1524 if (Body[Pos] != '$' || Pos + 1 == End)
1527 char Next = Body[Pos + 1];
1528 if (Next == '$' || Next == 'n' || isdigit(Next))
1531 // This macro has parameters, look for \foo, \bar, etc.
1532 if (Body[Pos] == '\\' && Pos + 1 != End)
1538 OS << Body.slice(0, Pos);
1540 // Check if we reached the end.
1545 switch (Body[Pos+1]) {
1551 // $n => number of arguments
1556 // $[0-9] => argument
1558 // Missing arguments are ignored.
1559 unsigned Index = Body[Pos+1] - '0';
1560 if (Index >= A.size())
1563 // Otherwise substitute with the token values, with spaces eliminated.
1564 for (MacroArgument::const_iterator it = A[Index].begin(),
1565 ie = A[Index].end(); it != ie; ++it)
1566 OS << it->getString();
1572 unsigned I = Pos + 1;
1573 while (isIdentifierChar(Body[I]) && I + 1 != End)
1576 const char *Begin = Body.data() + Pos +1;
1577 StringRef Argument(Begin, I - (Pos +1));
1579 for (; Index < NParameters; ++Index)
1580 if (Parameters[Index].first == Argument)
1583 if (Index == NParameters) {
1584 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1587 OS << '\\' << Argument;
1591 for (MacroArgument::const_iterator it = A[Index].begin(),
1592 ie = A[Index].end(); it != ie; ++it)
1593 if (it->getKind() == AsmToken::String)
1594 OS << it->getStringContents();
1596 OS << it->getString();
1598 Pos += 1 + Argument.size();
1601 // Update the scan point.
1602 Body = Body.substr(Pos);
1608 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1610 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1614 static bool IsOperator(AsmToken::TokenKind kind)
1620 case AsmToken::Plus:
1621 case AsmToken::Minus:
1622 case AsmToken::Tilde:
1623 case AsmToken::Slash:
1624 case AsmToken::Star:
1626 case AsmToken::Equal:
1627 case AsmToken::EqualEqual:
1628 case AsmToken::Pipe:
1629 case AsmToken::PipePipe:
1630 case AsmToken::Caret:
1632 case AsmToken::AmpAmp:
1633 case AsmToken::Exclaim:
1634 case AsmToken::ExclaimEqual:
1635 case AsmToken::Percent:
1636 case AsmToken::Less:
1637 case AsmToken::LessEqual:
1638 case AsmToken::LessLess:
1639 case AsmToken::LessGreater:
1640 case AsmToken::Greater:
1641 case AsmToken::GreaterEqual:
1642 case AsmToken::GreaterGreater:
1647 /// ParseMacroArgument - Extract AsmTokens for a macro argument.
1648 /// This is used for both default macro parameter values and the
1649 /// arguments in macro invocations
1650 bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1651 AsmToken::TokenKind &ArgumentDelimiter) {
1652 unsigned ParenLevel = 0;
1653 unsigned AddTokens = 0;
1655 // gas accepts arguments separated by whitespace, except on Darwin
1657 Lexer.setSkipSpace(false);
1660 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1661 Lexer.setSkipSpace(true);
1662 return TokError("unexpected token in macro instantiation");
1665 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1666 // Spaces and commas cannot be mixed to delimit parameters
1667 if (ArgumentDelimiter == AsmToken::Eof)
1668 ArgumentDelimiter = AsmToken::Comma;
1669 else if (ArgumentDelimiter != AsmToken::Comma) {
1670 Lexer.setSkipSpace(true);
1671 return TokError("expected ' ' for macro argument separator");
1676 if (Lexer.is(AsmToken::Space)) {
1677 Lex(); // Eat spaces
1679 // Spaces can delimit parameters, but could also be part an expression.
1680 // If the token after a space is an operator, add the token and the next
1681 // one into this argument
1682 if (ArgumentDelimiter == AsmToken::Space ||
1683 ArgumentDelimiter == AsmToken::Eof) {
1684 if (IsOperator(Lexer.getKind())) {
1685 // Check to see whether the token is used as an operator,
1686 // or part of an identifier
1687 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1688 if (*NextChar == ' ')
1692 if (!AddTokens && ParenLevel == 0) {
1693 if (ArgumentDelimiter == AsmToken::Eof &&
1694 !IsOperator(Lexer.getKind()))
1695 ArgumentDelimiter = AsmToken::Space;
1701 // HandleMacroEntry relies on not advancing the lexer here
1702 // to be able to fill in the remaining default parameter values
1703 if (Lexer.is(AsmToken::EndOfStatement))
1706 // Adjust the current parentheses level.
1707 if (Lexer.is(AsmToken::LParen))
1709 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1712 // Append the token to the current argument list.
1713 MA.push_back(getTok());
1719 Lexer.setSkipSpace(true);
1720 if (ParenLevel != 0)
1721 return TokError("unbalanced parentheses in macro argument");
1725 // Parse the macro instantiation arguments.
1726 bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
1727 const unsigned NParameters = M ? M->Parameters.size() : 0;
1728 // Argument delimiter is initially unknown. It will be set by
1729 // ParseMacroArgument()
1730 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1732 // Parse two kinds of macro invocations:
1733 // - macros defined without any parameters accept an arbitrary number of them
1734 // - macros defined with parameters accept at most that many of them
1735 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1739 if (ParseMacroArgument(MA, ArgumentDelimiter))
1742 if (!MA.empty() || !NParameters)
1744 else if (NParameters) {
1745 if (!M->Parameters[Parameter].second.empty())
1746 A.push_back(M->Parameters[Parameter].second);
1749 // At the end of the statement, fill in remaining arguments that have
1750 // default values. If there aren't any, then the next argument is
1751 // required but missing
1752 if (Lexer.is(AsmToken::EndOfStatement)) {
1753 if (NParameters && Parameter < NParameters - 1) {
1754 if (M->Parameters[Parameter + 1].second.empty())
1755 return TokError("macro argument '" +
1756 Twine(M->Parameters[Parameter + 1].first) +
1764 if (Lexer.is(AsmToken::Comma))
1767 return TokError("Too many arguments");
1770 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1772 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1773 // this, although we should protect against infinite loops.
1774 if (ActiveMacros.size() == 20)
1775 return TokError("macros cannot be nested more than 20 levels deep");
1778 if (ParseMacroArguments(M, A))
1781 // Remove any trailing empty arguments. Do this after-the-fact as we have
1782 // to keep empty arguments in the middle of the list or positionality
1783 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1784 while (!A.empty() && A.back().empty())
1787 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1788 // to hold the macro body with substitutions.
1789 SmallString<256> Buf;
1790 StringRef Body = M->Body;
1791 raw_svector_ostream OS(Buf);
1793 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1796 // We include the .endmacro in the buffer as our queue to exit the macro
1798 OS << ".endmacro\n";
1800 MemoryBuffer *Instantiation =
1801 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1803 // Create the macro instantiation object and add to the current macro
1804 // instantiation stack.
1805 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1808 ActiveMacros.push_back(MI);
1810 // Jump to the macro instantiation and prime the lexer.
1811 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1812 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1818 void AsmParser::HandleMacroExit() {
1819 // Jump to the EndOfStatement we should return to, and consume it.
1820 JumpToLoc(ActiveMacros.back()->ExitLoc);
1823 // Pop the instantiation entry.
1824 delete ActiveMacros.back();
1825 ActiveMacros.pop_back();
1828 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1829 switch (Value->getKind()) {
1830 case MCExpr::Binary: {
1831 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1832 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1835 case MCExpr::Target:
1836 case MCExpr::Constant:
1838 case MCExpr::SymbolRef: {
1839 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1841 return IsUsedIn(Sym, S.getVariableValue());
1845 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1848 llvm_unreachable("Unknown expr kind!");
1851 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1853 // FIXME: Use better location, we should use proper tokens.
1854 SMLoc EqualLoc = Lexer.getLoc();
1856 const MCExpr *Value;
1857 if (ParseExpression(Value))
1860 // Note: we don't count b as used in "a = b". This is to allow
1864 if (Lexer.isNot(AsmToken::EndOfStatement))
1865 return TokError("unexpected token in assignment");
1867 // Error on assignment to '.'.
1869 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1870 "(use '.space' or '.org').)"));
1873 // Eat the end of statement marker.
1876 // Validate that the LHS is allowed to be a variable (either it has not been
1877 // used as a symbol, or it is an absolute symbol).
1878 MCSymbol *Sym = getContext().LookupSymbol(Name);
1880 // Diagnose assignment to a label.
1882 // FIXME: Diagnostics. Note the location of the definition as a label.
1883 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1884 if (IsUsedIn(Sym, Value))
1885 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1886 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1887 ; // Allow redefinitions of undefined symbols only used in directives.
1888 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1889 ; // Allow redefinitions of variables that haven't yet been used.
1890 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1891 return Error(EqualLoc, "redefinition of '" + Name + "'");
1892 else if (!Sym->isVariable())
1893 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1894 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1895 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1898 // Don't count these checks as uses.
1899 Sym->setUsed(false);
1901 Sym = getContext().GetOrCreateSymbol(Name);
1903 // FIXME: Handle '.'.
1905 // Do the assignment.
1906 Out.EmitAssignment(Sym, Value);
1908 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1914 /// ParseIdentifier:
1917 bool AsmParser::ParseIdentifier(StringRef &Res) {
1918 // The assembler has relaxed rules for accepting identifiers, in particular we
1919 // allow things like '.globl $foo', which would normally be separate
1920 // tokens. At this level, we have already lexed so we cannot (currently)
1921 // handle this as a context dependent token, instead we detect adjacent tokens
1922 // and return the combined identifier.
1923 if (Lexer.is(AsmToken::Dollar)) {
1924 SMLoc DollarLoc = getLexer().getLoc();
1926 // Consume the dollar sign, and check for a following identifier.
1928 if (Lexer.isNot(AsmToken::Identifier))
1931 // We have a '$' followed by an identifier, make sure they are adjacent.
1932 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1935 // Construct the joined identifier and consume the token.
1936 Res = StringRef(DollarLoc.getPointer(),
1937 getTok().getIdentifier().size() + 1);
1942 if (Lexer.isNot(AsmToken::Identifier) &&
1943 Lexer.isNot(AsmToken::String))
1946 Res = getTok().getIdentifier();
1948 Lex(); // Consume the identifier token.
1953 /// ParseDirectiveSet:
1954 /// ::= .equ identifier ',' expression
1955 /// ::= .equiv identifier ',' expression
1956 /// ::= .set identifier ',' expression
1957 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1960 if (ParseIdentifier(Name))
1961 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1963 if (getLexer().isNot(AsmToken::Comma))
1964 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1967 return ParseAssignment(Name, allow_redef, true);
1970 bool AsmParser::ParseEscapedString(std::string &Data) {
1971 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1974 StringRef Str = getTok().getStringContents();
1975 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1976 if (Str[i] != '\\') {
1981 // Recognize escaped characters. Note that this escape semantics currently
1982 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1985 return TokError("unexpected backslash at end of string");
1987 // Recognize octal sequences.
1988 if ((unsigned) (Str[i] - '0') <= 7) {
1989 // Consume up to three octal characters.
1990 unsigned Value = Str[i] - '0';
1992 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1994 Value = Value * 8 + (Str[i] - '0');
1996 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1998 Value = Value * 8 + (Str[i] - '0');
2003 return TokError("invalid octal escape sequence (out of range)");
2005 Data += (unsigned char) Value;
2009 // Otherwise recognize individual escapes.
2012 // Just reject invalid escape sequences for now.
2013 return TokError("invalid escape sequence (unrecognized character)");
2015 case 'b': Data += '\b'; break;
2016 case 'f': Data += '\f'; break;
2017 case 'n': Data += '\n'; break;
2018 case 'r': Data += '\r'; break;
2019 case 't': Data += '\t'; break;
2020 case '"': Data += '"'; break;
2021 case '\\': Data += '\\'; break;
2028 /// ParseDirectiveAscii:
2029 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2030 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2031 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2032 CheckForValidSection();
2035 if (getLexer().isNot(AsmToken::String))
2036 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2039 if (ParseEscapedString(Data))
2042 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2044 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2048 if (getLexer().is(AsmToken::EndOfStatement))
2051 if (getLexer().isNot(AsmToken::Comma))
2052 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2061 /// ParseDirectiveValue
2062 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2063 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2064 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2065 CheckForValidSection();
2068 const MCExpr *Value;
2069 SMLoc ExprLoc = getLexer().getLoc();
2070 if (ParseExpression(Value))
2073 // Special case constant expressions to match code generator.
2074 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2075 assert(Size <= 8 && "Invalid size");
2076 uint64_t IntValue = MCE->getValue();
2077 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2078 return Error(ExprLoc, "literal value out of range for directive");
2079 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2081 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2083 if (getLexer().is(AsmToken::EndOfStatement))
2086 // FIXME: Improve diagnostic.
2087 if (getLexer().isNot(AsmToken::Comma))
2088 return TokError("unexpected token in directive");
2097 /// ParseDirectiveRealValue
2098 /// ::= (.single | .double) [ expression (, expression)* ]
2099 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2100 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2101 CheckForValidSection();
2104 // We don't truly support arithmetic on floating point expressions, so we
2105 // have to manually parse unary prefixes.
2107 if (getLexer().is(AsmToken::Minus)) {
2110 } else if (getLexer().is(AsmToken::Plus))
2113 if (getLexer().isNot(AsmToken::Integer) &&
2114 getLexer().isNot(AsmToken::Real) &&
2115 getLexer().isNot(AsmToken::Identifier))
2116 return TokError("unexpected token in directive");
2118 // Convert to an APFloat.
2119 APFloat Value(Semantics);
2120 StringRef IDVal = getTok().getString();
2121 if (getLexer().is(AsmToken::Identifier)) {
2122 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2123 Value = APFloat::getInf(Semantics);
2124 else if (!IDVal.compare_lower("nan"))
2125 Value = APFloat::getNaN(Semantics, false, ~0);
2127 return TokError("invalid floating point literal");
2128 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2129 APFloat::opInvalidOp)
2130 return TokError("invalid floating point literal");
2134 // Consume the numeric token.
2137 // Emit the value as an integer.
2138 APInt AsInt = Value.bitcastToAPInt();
2139 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2140 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2142 if (getLexer().is(AsmToken::EndOfStatement))
2145 if (getLexer().isNot(AsmToken::Comma))
2146 return TokError("unexpected token in directive");
2155 /// ParseDirectiveSpace
2156 /// ::= .space expression [ , expression ]
2157 bool AsmParser::ParseDirectiveSpace() {
2158 CheckForValidSection();
2161 if (ParseAbsoluteExpression(NumBytes))
2164 int64_t FillExpr = 0;
2165 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2166 if (getLexer().isNot(AsmToken::Comma))
2167 return TokError("unexpected token in '.space' directive");
2170 if (ParseAbsoluteExpression(FillExpr))
2173 if (getLexer().isNot(AsmToken::EndOfStatement))
2174 return TokError("unexpected token in '.space' directive");
2180 return TokError("invalid number of bytes in '.space' directive");
2182 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
2183 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
2188 /// ParseDirectiveZero
2189 /// ::= .zero expression
2190 bool AsmParser::ParseDirectiveZero() {
2191 CheckForValidSection();
2194 if (ParseAbsoluteExpression(NumBytes))
2198 if (getLexer().is(AsmToken::Comma)) {
2200 if (ParseAbsoluteExpression(Val))
2204 if (getLexer().isNot(AsmToken::EndOfStatement))
2205 return TokError("unexpected token in '.zero' directive");
2209 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2214 /// ParseDirectiveFill
2215 /// ::= .fill expression , expression , expression
2216 bool AsmParser::ParseDirectiveFill() {
2217 CheckForValidSection();
2220 if (ParseAbsoluteExpression(NumValues))
2223 if (getLexer().isNot(AsmToken::Comma))
2224 return TokError("unexpected token in '.fill' directive");
2228 if (ParseAbsoluteExpression(FillSize))
2231 if (getLexer().isNot(AsmToken::Comma))
2232 return TokError("unexpected token in '.fill' directive");
2236 if (ParseAbsoluteExpression(FillExpr))
2239 if (getLexer().isNot(AsmToken::EndOfStatement))
2240 return TokError("unexpected token in '.fill' directive");
2244 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2245 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2247 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2248 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2253 /// ParseDirectiveOrg
2254 /// ::= .org expression [ , expression ]
2255 bool AsmParser::ParseDirectiveOrg() {
2256 CheckForValidSection();
2258 const MCExpr *Offset;
2259 SMLoc Loc = getTok().getLoc();
2260 if (ParseExpression(Offset))
2263 // Parse optional fill expression.
2264 int64_t FillExpr = 0;
2265 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2266 if (getLexer().isNot(AsmToken::Comma))
2267 return TokError("unexpected token in '.org' directive");
2270 if (ParseAbsoluteExpression(FillExpr))
2273 if (getLexer().isNot(AsmToken::EndOfStatement))
2274 return TokError("unexpected token in '.org' directive");
2279 // Only limited forms of relocatable expressions are accepted here, it
2280 // has to be relative to the current section. The streamer will return
2281 // 'true' if the expression wasn't evaluatable.
2282 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2283 return Error(Loc, "expected assembly-time absolute expression");
2288 /// ParseDirectiveAlign
2289 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2290 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2291 CheckForValidSection();
2293 SMLoc AlignmentLoc = getLexer().getLoc();
2295 if (ParseAbsoluteExpression(Alignment))
2299 bool HasFillExpr = false;
2300 int64_t FillExpr = 0;
2301 int64_t MaxBytesToFill = 0;
2302 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2303 if (getLexer().isNot(AsmToken::Comma))
2304 return TokError("unexpected token in directive");
2307 // The fill expression can be omitted while specifying a maximum number of
2308 // alignment bytes, e.g:
2310 if (getLexer().isNot(AsmToken::Comma)) {
2312 if (ParseAbsoluteExpression(FillExpr))
2316 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2317 if (getLexer().isNot(AsmToken::Comma))
2318 return TokError("unexpected token in directive");
2321 MaxBytesLoc = getLexer().getLoc();
2322 if (ParseAbsoluteExpression(MaxBytesToFill))
2325 if (getLexer().isNot(AsmToken::EndOfStatement))
2326 return TokError("unexpected token in directive");
2335 // Compute alignment in bytes.
2337 // FIXME: Diagnose overflow.
2338 if (Alignment >= 32) {
2339 Error(AlignmentLoc, "invalid alignment value");
2343 Alignment = 1ULL << Alignment;
2346 // Diagnose non-sensical max bytes to align.
2347 if (MaxBytesLoc.isValid()) {
2348 if (MaxBytesToFill < 1) {
2349 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2350 "many bytes, ignoring maximum bytes expression");
2354 if (MaxBytesToFill >= Alignment) {
2355 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2361 // Check whether we should use optimal code alignment for this .align
2363 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2364 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2365 ValueSize == 1 && UseCodeAlign) {
2366 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2368 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2369 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2376 /// ParseDirectiveSymbolAttribute
2377 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2378 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2379 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2382 SMLoc Loc = getTok().getLoc();
2384 if (ParseIdentifier(Name))
2385 return Error(Loc, "expected identifier in directive");
2387 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2389 // Assembler local symbols don't make any sense here. Complain loudly.
2390 if (Sym->isTemporary())
2391 return Error(Loc, "non-local symbol required in directive");
2393 getStreamer().EmitSymbolAttribute(Sym, Attr);
2395 if (getLexer().is(AsmToken::EndOfStatement))
2398 if (getLexer().isNot(AsmToken::Comma))
2399 return TokError("unexpected token in directive");
2408 /// ParseDirectiveComm
2409 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2410 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2411 CheckForValidSection();
2413 SMLoc IDLoc = getLexer().getLoc();
2415 if (ParseIdentifier(Name))
2416 return TokError("expected identifier in directive");
2418 // Handle the identifier as the key symbol.
2419 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2421 if (getLexer().isNot(AsmToken::Comma))
2422 return TokError("unexpected token in directive");
2426 SMLoc SizeLoc = getLexer().getLoc();
2427 if (ParseAbsoluteExpression(Size))
2430 int64_t Pow2Alignment = 0;
2431 SMLoc Pow2AlignmentLoc;
2432 if (getLexer().is(AsmToken::Comma)) {
2434 Pow2AlignmentLoc = getLexer().getLoc();
2435 if (ParseAbsoluteExpression(Pow2Alignment))
2438 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2439 if (IsLocal && LCOMM == LCOMM::NoAlignment)
2440 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2442 // If this target takes alignments in bytes (not log) validate and convert.
2443 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2444 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
2445 if (!isPowerOf2_64(Pow2Alignment))
2446 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2447 Pow2Alignment = Log2_64(Pow2Alignment);
2451 if (getLexer().isNot(AsmToken::EndOfStatement))
2452 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2456 // NOTE: a size of zero for a .comm should create a undefined symbol
2457 // but a size of .lcomm creates a bss symbol of size zero.
2459 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2460 "be less than zero");
2462 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2463 // may internally end up wanting an alignment in bytes.
2464 // FIXME: Diagnose overflow.
2465 if (Pow2Alignment < 0)
2466 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2467 "alignment, can't be less than zero");
2469 if (!Sym->isUndefined())
2470 return Error(IDLoc, "invalid symbol redefinition");
2472 // Create the Symbol as a common or local common with Size and Pow2Alignment
2474 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2478 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2482 /// ParseDirectiveAbort
2483 /// ::= .abort [... message ...]
2484 bool AsmParser::ParseDirectiveAbort() {
2485 // FIXME: Use loc from directive.
2486 SMLoc Loc = getLexer().getLoc();
2488 StringRef Str = ParseStringToEndOfStatement();
2489 if (getLexer().isNot(AsmToken::EndOfStatement))
2490 return TokError("unexpected token in '.abort' directive");
2495 Error(Loc, ".abort detected. Assembly stopping.");
2497 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2498 // FIXME: Actually abort assembly here.
2503 /// ParseDirectiveInclude
2504 /// ::= .include "filename"
2505 bool AsmParser::ParseDirectiveInclude() {
2506 if (getLexer().isNot(AsmToken::String))
2507 return TokError("expected string in '.include' directive");
2509 std::string Filename = getTok().getString();
2510 SMLoc IncludeLoc = getLexer().getLoc();
2513 if (getLexer().isNot(AsmToken::EndOfStatement))
2514 return TokError("unexpected token in '.include' directive");
2516 // Strip the quotes.
2517 Filename = Filename.substr(1, Filename.size()-2);
2519 // Attempt to switch the lexer to the included file before consuming the end
2520 // of statement to avoid losing it when we switch.
2521 if (EnterIncludeFile(Filename)) {
2522 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2529 /// ParseDirectiveIncbin
2530 /// ::= .incbin "filename"
2531 bool AsmParser::ParseDirectiveIncbin() {
2532 if (getLexer().isNot(AsmToken::String))
2533 return TokError("expected string in '.incbin' directive");
2535 std::string Filename = getTok().getString();
2536 SMLoc IncbinLoc = getLexer().getLoc();
2539 if (getLexer().isNot(AsmToken::EndOfStatement))
2540 return TokError("unexpected token in '.incbin' directive");
2542 // Strip the quotes.
2543 Filename = Filename.substr(1, Filename.size()-2);
2545 // Attempt to process the included file.
2546 if (ProcessIncbinFile(Filename)) {
2547 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2554 /// ParseDirectiveIf
2555 /// ::= .if expression
2556 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2557 TheCondStack.push_back(TheCondState);
2558 TheCondState.TheCond = AsmCond::IfCond;
2559 if (TheCondState.Ignore) {
2560 EatToEndOfStatement();
2563 if (ParseAbsoluteExpression(ExprValue))
2566 if (getLexer().isNot(AsmToken::EndOfStatement))
2567 return TokError("unexpected token in '.if' directive");
2571 TheCondState.CondMet = ExprValue;
2572 TheCondState.Ignore = !TheCondState.CondMet;
2578 /// ParseDirectiveIfb
2580 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2581 TheCondStack.push_back(TheCondState);
2582 TheCondState.TheCond = AsmCond::IfCond;
2584 if (TheCondState.Ignore) {
2585 EatToEndOfStatement();
2587 StringRef Str = ParseStringToEndOfStatement();
2589 if (getLexer().isNot(AsmToken::EndOfStatement))
2590 return TokError("unexpected token in '.ifb' directive");
2594 TheCondState.CondMet = ExpectBlank == Str.empty();
2595 TheCondState.Ignore = !TheCondState.CondMet;
2601 /// ParseDirectiveIfc
2602 /// ::= .ifc string1, string2
2603 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2604 TheCondStack.push_back(TheCondState);
2605 TheCondState.TheCond = AsmCond::IfCond;
2607 if (TheCondState.Ignore) {
2608 EatToEndOfStatement();
2610 StringRef Str1 = ParseStringToComma();
2612 if (getLexer().isNot(AsmToken::Comma))
2613 return TokError("unexpected token in '.ifc' directive");
2617 StringRef Str2 = ParseStringToEndOfStatement();
2619 if (getLexer().isNot(AsmToken::EndOfStatement))
2620 return TokError("unexpected token in '.ifc' directive");
2624 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2625 TheCondState.Ignore = !TheCondState.CondMet;
2631 /// ParseDirectiveIfdef
2632 /// ::= .ifdef symbol
2633 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2635 TheCondStack.push_back(TheCondState);
2636 TheCondState.TheCond = AsmCond::IfCond;
2638 if (TheCondState.Ignore) {
2639 EatToEndOfStatement();
2641 if (ParseIdentifier(Name))
2642 return TokError("expected identifier after '.ifdef'");
2646 MCSymbol *Sym = getContext().LookupSymbol(Name);
2649 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2651 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2652 TheCondState.Ignore = !TheCondState.CondMet;
2658 /// ParseDirectiveElseIf
2659 /// ::= .elseif expression
2660 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2661 if (TheCondState.TheCond != AsmCond::IfCond &&
2662 TheCondState.TheCond != AsmCond::ElseIfCond)
2663 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2665 TheCondState.TheCond = AsmCond::ElseIfCond;
2667 bool LastIgnoreState = false;
2668 if (!TheCondStack.empty())
2669 LastIgnoreState = TheCondStack.back().Ignore;
2670 if (LastIgnoreState || TheCondState.CondMet) {
2671 TheCondState.Ignore = true;
2672 EatToEndOfStatement();
2676 if (ParseAbsoluteExpression(ExprValue))
2679 if (getLexer().isNot(AsmToken::EndOfStatement))
2680 return TokError("unexpected token in '.elseif' directive");
2683 TheCondState.CondMet = ExprValue;
2684 TheCondState.Ignore = !TheCondState.CondMet;
2690 /// ParseDirectiveElse
2692 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2693 if (getLexer().isNot(AsmToken::EndOfStatement))
2694 return TokError("unexpected token in '.else' directive");
2698 if (TheCondState.TheCond != AsmCond::IfCond &&
2699 TheCondState.TheCond != AsmCond::ElseIfCond)
2700 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2702 TheCondState.TheCond = AsmCond::ElseCond;
2703 bool LastIgnoreState = false;
2704 if (!TheCondStack.empty())
2705 LastIgnoreState = TheCondStack.back().Ignore;
2706 if (LastIgnoreState || TheCondState.CondMet)
2707 TheCondState.Ignore = true;
2709 TheCondState.Ignore = false;
2714 /// ParseDirectiveEndIf
2716 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2717 if (getLexer().isNot(AsmToken::EndOfStatement))
2718 return TokError("unexpected token in '.endif' directive");
2722 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2723 TheCondStack.empty())
2724 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2726 if (!TheCondStack.empty()) {
2727 TheCondState = TheCondStack.back();
2728 TheCondStack.pop_back();
2734 /// ParseDirectiveFile
2735 /// ::= .file [number] filename
2736 /// ::= .file number directory filename
2737 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2738 // FIXME: I'm not sure what this is.
2739 int64_t FileNumber = -1;
2740 SMLoc FileNumberLoc = getLexer().getLoc();
2741 if (getLexer().is(AsmToken::Integer)) {
2742 FileNumber = getTok().getIntVal();
2746 return TokError("file number less than one");
2749 if (getLexer().isNot(AsmToken::String))
2750 return TokError("unexpected token in '.file' directive");
2752 // Usually the directory and filename together, otherwise just the directory.
2753 StringRef Path = getTok().getString();
2754 Path = Path.substr(1, Path.size()-2);
2757 StringRef Directory;
2759 if (getLexer().is(AsmToken::String)) {
2760 if (FileNumber == -1)
2761 return TokError("explicit path specified, but no file number");
2762 Filename = getTok().getString();
2763 Filename = Filename.substr(1, Filename.size()-2);
2770 if (getLexer().isNot(AsmToken::EndOfStatement))
2771 return TokError("unexpected token in '.file' directive");
2773 if (FileNumber == -1)
2774 getStreamer().EmitFileDirective(Filename);
2776 if (getContext().getGenDwarfForAssembly() == true)
2777 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2778 "used to generate dwarf debug info for assembly code");
2780 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2781 Error(FileNumberLoc, "file number already allocated");
2787 /// ParseDirectiveLine
2788 /// ::= .line [number]
2789 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2790 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2791 if (getLexer().isNot(AsmToken::Integer))
2792 return TokError("unexpected token in '.line' directive");
2794 int64_t LineNumber = getTok().getIntVal();
2798 // FIXME: Do something with the .line.
2801 if (getLexer().isNot(AsmToken::EndOfStatement))
2802 return TokError("unexpected token in '.line' directive");
2808 /// ParseDirectiveLoc
2809 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2810 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2811 /// The first number is a file number, must have been previously assigned with
2812 /// a .file directive, the second number is the line number and optionally the
2813 /// third number is a column position (zero if not specified). The remaining
2814 /// optional items are .loc sub-directives.
2815 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2817 if (getLexer().isNot(AsmToken::Integer))
2818 return TokError("unexpected token in '.loc' directive");
2819 int64_t FileNumber = getTok().getIntVal();
2821 return TokError("file number less than one in '.loc' directive");
2822 if (!getContext().isValidDwarfFileNumber(FileNumber))
2823 return TokError("unassigned file number in '.loc' directive");
2826 int64_t LineNumber = 0;
2827 if (getLexer().is(AsmToken::Integer)) {
2828 LineNumber = getTok().getIntVal();
2830 return TokError("line number less than one in '.loc' directive");
2834 int64_t ColumnPos = 0;
2835 if (getLexer().is(AsmToken::Integer)) {
2836 ColumnPos = getTok().getIntVal();
2838 return TokError("column position less than zero in '.loc' directive");
2842 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2844 int64_t Discriminator = 0;
2845 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2847 if (getLexer().is(AsmToken::EndOfStatement))
2851 SMLoc Loc = getTok().getLoc();
2852 if (getParser().ParseIdentifier(Name))
2853 return TokError("unexpected token in '.loc' directive");
2855 if (Name == "basic_block")
2856 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2857 else if (Name == "prologue_end")
2858 Flags |= DWARF2_FLAG_PROLOGUE_END;
2859 else if (Name == "epilogue_begin")
2860 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2861 else if (Name == "is_stmt") {
2862 SMLoc Loc = getTok().getLoc();
2863 const MCExpr *Value;
2864 if (getParser().ParseExpression(Value))
2866 // The expression must be the constant 0 or 1.
2867 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2868 int Value = MCE->getValue();
2870 Flags &= ~DWARF2_FLAG_IS_STMT;
2871 else if (Value == 1)
2872 Flags |= DWARF2_FLAG_IS_STMT;
2874 return Error(Loc, "is_stmt value not 0 or 1");
2877 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2880 else if (Name == "isa") {
2881 SMLoc Loc = getTok().getLoc();
2882 const MCExpr *Value;
2883 if (getParser().ParseExpression(Value))
2885 // The expression must be a constant greater or equal to 0.
2886 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2887 int Value = MCE->getValue();
2889 return Error(Loc, "isa number less than zero");
2893 return Error(Loc, "isa number not a constant value");
2896 else if (Name == "discriminator") {
2897 if (getParser().ParseAbsoluteExpression(Discriminator))
2901 return Error(Loc, "unknown sub-directive in '.loc' directive");
2904 if (getLexer().is(AsmToken::EndOfStatement))
2909 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2910 Isa, Discriminator, StringRef());
2915 /// ParseDirectiveStabs
2916 /// ::= .stabs string, number, number, number
2917 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2918 SMLoc DirectiveLoc) {
2919 return TokError("unsupported directive '" + Directive + "'");
2922 /// ParseDirectiveCFISections
2923 /// ::= .cfi_sections section [, section]
2924 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2925 SMLoc DirectiveLoc) {
2930 if (getParser().ParseIdentifier(Name))
2931 return TokError("Expected an identifier");
2933 if (Name == ".eh_frame")
2935 else if (Name == ".debug_frame")
2938 if (getLexer().is(AsmToken::Comma)) {
2941 if (getParser().ParseIdentifier(Name))
2942 return TokError("Expected an identifier");
2944 if (Name == ".eh_frame")
2946 else if (Name == ".debug_frame")
2950 getStreamer().EmitCFISections(EH, Debug);
2955 /// ParseDirectiveCFIStartProc
2956 /// ::= .cfi_startproc
2957 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2958 SMLoc DirectiveLoc) {
2959 getStreamer().EmitCFIStartProc();
2963 /// ParseDirectiveCFIEndProc
2964 /// ::= .cfi_endproc
2965 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2966 getStreamer().EmitCFIEndProc();
2970 /// ParseRegisterOrRegisterNumber - parse register name or number.
2971 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2972 SMLoc DirectiveLoc) {
2975 if (getLexer().isNot(AsmToken::Integer)) {
2976 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2979 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2981 return getParser().ParseAbsoluteExpression(Register);
2986 /// ParseDirectiveCFIDefCfa
2987 /// ::= .cfi_def_cfa register, offset
2988 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2989 SMLoc DirectiveLoc) {
2990 int64_t Register = 0;
2991 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2994 if (getLexer().isNot(AsmToken::Comma))
2995 return TokError("unexpected token in directive");
2999 if (getParser().ParseAbsoluteExpression(Offset))
3002 getStreamer().EmitCFIDefCfa(Register, Offset);
3006 /// ParseDirectiveCFIDefCfaOffset
3007 /// ::= .cfi_def_cfa_offset offset
3008 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3009 SMLoc DirectiveLoc) {
3011 if (getParser().ParseAbsoluteExpression(Offset))
3014 getStreamer().EmitCFIDefCfaOffset(Offset);
3018 /// ParseDirectiveCFIAdjustCfaOffset
3019 /// ::= .cfi_adjust_cfa_offset adjustment
3020 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3021 SMLoc DirectiveLoc) {
3022 int64_t Adjustment = 0;
3023 if (getParser().ParseAbsoluteExpression(Adjustment))
3026 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3030 /// ParseDirectiveCFIDefCfaRegister
3031 /// ::= .cfi_def_cfa_register register
3032 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3033 SMLoc DirectiveLoc) {
3034 int64_t Register = 0;
3035 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3038 getStreamer().EmitCFIDefCfaRegister(Register);
3042 /// ParseDirectiveCFIOffset
3043 /// ::= .cfi_offset register, offset
3044 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3045 int64_t Register = 0;
3048 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3051 if (getLexer().isNot(AsmToken::Comma))
3052 return TokError("unexpected token in directive");
3055 if (getParser().ParseAbsoluteExpression(Offset))
3058 getStreamer().EmitCFIOffset(Register, Offset);
3062 /// ParseDirectiveCFIRelOffset
3063 /// ::= .cfi_rel_offset register, offset
3064 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3065 SMLoc DirectiveLoc) {
3066 int64_t Register = 0;
3068 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3071 if (getLexer().isNot(AsmToken::Comma))
3072 return TokError("unexpected token in directive");
3076 if (getParser().ParseAbsoluteExpression(Offset))
3079 getStreamer().EmitCFIRelOffset(Register, Offset);
3083 static bool isValidEncoding(int64_t Encoding) {
3084 if (Encoding & ~0xff)
3087 if (Encoding == dwarf::DW_EH_PE_omit)
3090 const unsigned Format = Encoding & 0xf;
3091 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3092 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3093 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3094 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3097 const unsigned Application = Encoding & 0x70;
3098 if (Application != dwarf::DW_EH_PE_absptr &&
3099 Application != dwarf::DW_EH_PE_pcrel)
3105 /// ParseDirectiveCFIPersonalityOrLsda
3106 /// ::= .cfi_personality encoding, [symbol_name]
3107 /// ::= .cfi_lsda encoding, [symbol_name]
3108 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
3109 SMLoc DirectiveLoc) {
3110 int64_t Encoding = 0;
3111 if (getParser().ParseAbsoluteExpression(Encoding))
3113 if (Encoding == dwarf::DW_EH_PE_omit)
3116 if (!isValidEncoding(Encoding))
3117 return TokError("unsupported encoding.");
3119 if (getLexer().isNot(AsmToken::Comma))
3120 return TokError("unexpected token in directive");
3124 if (getParser().ParseIdentifier(Name))
3125 return TokError("expected identifier in directive");
3127 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3129 if (IDVal == ".cfi_personality")
3130 getStreamer().EmitCFIPersonality(Sym, Encoding);
3132 assert(IDVal == ".cfi_lsda");
3133 getStreamer().EmitCFILsda(Sym, Encoding);
3138 /// ParseDirectiveCFIRememberState
3139 /// ::= .cfi_remember_state
3140 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3141 SMLoc DirectiveLoc) {
3142 getStreamer().EmitCFIRememberState();
3146 /// ParseDirectiveCFIRestoreState
3147 /// ::= .cfi_remember_state
3148 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3149 SMLoc DirectiveLoc) {
3150 getStreamer().EmitCFIRestoreState();
3154 /// ParseDirectiveCFISameValue
3155 /// ::= .cfi_same_value register
3156 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3157 SMLoc DirectiveLoc) {
3158 int64_t Register = 0;
3160 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3163 getStreamer().EmitCFISameValue(Register);
3168 /// ParseDirectiveCFIRestore
3169 /// ::= .cfi_restore register
3170 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
3171 SMLoc DirectiveLoc) {
3172 int64_t Register = 0;
3173 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3176 getStreamer().EmitCFIRestore(Register);
3181 /// ParseDirectiveCFIEscape
3182 /// ::= .cfi_escape expression[,...]
3183 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3184 SMLoc DirectiveLoc) {
3187 if (getParser().ParseAbsoluteExpression(CurrValue))
3190 Values.push_back((uint8_t)CurrValue);
3192 while (getLexer().is(AsmToken::Comma)) {
3195 if (getParser().ParseAbsoluteExpression(CurrValue))
3198 Values.push_back((uint8_t)CurrValue);
3201 getStreamer().EmitCFIEscape(Values);
3205 /// ParseDirectiveCFISignalFrame
3206 /// ::= .cfi_signal_frame
3207 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3208 SMLoc DirectiveLoc) {
3209 if (getLexer().isNot(AsmToken::EndOfStatement))
3210 return Error(getLexer().getLoc(),
3211 "unexpected token in '" + Directive + "' directive");
3213 getStreamer().EmitCFISignalFrame();
3218 /// ParseDirectiveMacrosOnOff
3221 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3222 SMLoc DirectiveLoc) {
3223 if (getLexer().isNot(AsmToken::EndOfStatement))
3224 return Error(getLexer().getLoc(),
3225 "unexpected token in '" + Directive + "' directive");
3227 getParser().MacrosEnabled = Directive == ".macros_on";
3232 /// ParseDirectiveMacro
3233 /// ::= .macro name [parameters]
3234 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3235 SMLoc DirectiveLoc) {
3237 if (getParser().ParseIdentifier(Name))
3238 return TokError("expected identifier in '.macro' directive");
3240 MacroParameters Parameters;
3241 // Argument delimiter is initially unknown. It will be set by
3242 // ParseMacroArgument()
3243 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3244 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3246 MacroParameter Parameter;
3247 if (getParser().ParseIdentifier(Parameter.first))
3248 return TokError("expected identifier in '.macro' directive");
3250 if (getLexer().is(AsmToken::Equal)) {
3252 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3256 Parameters.push_back(Parameter);
3258 if (getLexer().is(AsmToken::Comma))
3260 else if (getLexer().is(AsmToken::EndOfStatement))
3265 // Eat the end of statement.
3268 AsmToken EndToken, StartToken = getTok();
3270 // Lex the macro definition.
3272 // Check whether we have reached the end of the file.
3273 if (getLexer().is(AsmToken::Eof))
3274 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3276 // Otherwise, check whether we have reach the .endmacro.
3277 if (getLexer().is(AsmToken::Identifier) &&
3278 (getTok().getIdentifier() == ".endm" ||
3279 getTok().getIdentifier() == ".endmacro")) {
3280 EndToken = getTok();
3282 if (getLexer().isNot(AsmToken::EndOfStatement))
3283 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3288 // Otherwise, scan til the end of the statement.
3289 getParser().EatToEndOfStatement();
3292 if (getParser().MacroMap.lookup(Name)) {
3293 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3296 const char *BodyStart = StartToken.getLoc().getPointer();
3297 const char *BodyEnd = EndToken.getLoc().getPointer();
3298 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3299 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3303 /// ParseDirectiveEndMacro
3306 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3307 SMLoc DirectiveLoc) {
3308 if (getLexer().isNot(AsmToken::EndOfStatement))
3309 return TokError("unexpected token in '" + Directive + "' directive");
3311 // If we are inside a macro instantiation, terminate the current
3313 if (!getParser().ActiveMacros.empty()) {
3314 getParser().HandleMacroExit();
3318 // Otherwise, this .endmacro is a stray entry in the file; well formed
3319 // .endmacro directives are handled during the macro definition parsing.
3320 return TokError("unexpected '" + Directive + "' in file, "
3321 "no current macro definition");
3324 /// ParseDirectivePurgeMacro
3326 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3327 SMLoc DirectiveLoc) {
3329 if (getParser().ParseIdentifier(Name))
3330 return TokError("expected identifier in '.purgem' directive");
3332 if (getLexer().isNot(AsmToken::EndOfStatement))
3333 return TokError("unexpected token in '.purgem' directive");
3335 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3336 if (I == getParser().MacroMap.end())
3337 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3339 // Undefine the macro.
3340 delete I->getValue();
3341 getParser().MacroMap.erase(I);
3345 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3346 getParser().CheckForValidSection();
3348 const MCExpr *Value;
3350 if (getParser().ParseExpression(Value))
3353 if (getLexer().isNot(AsmToken::EndOfStatement))
3354 return TokError("unexpected token in directive");
3356 if (DirName[1] == 's')
3357 getStreamer().EmitSLEB128Value(Value);
3359 getStreamer().EmitULEB128Value(Value);
3364 Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3365 AsmToken EndToken, StartToken = getTok();
3367 unsigned NestLevel = 0;
3369 // Check whether we have reached the end of the file.
3370 if (getLexer().is(AsmToken::Eof)) {
3371 Error(DirectiveLoc, "no matching '.endr' in definition");
3375 if (Lexer.is(AsmToken::Identifier) &&
3376 (getTok().getIdentifier() == ".rept")) {
3380 // Otherwise, check whether we have reached the .endr.
3381 if (Lexer.is(AsmToken::Identifier) &&
3382 getTok().getIdentifier() == ".endr") {
3383 if (NestLevel == 0) {
3384 EndToken = getTok();
3386 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3387 TokError("unexpected token in '.endr' directive");
3395 // Otherwise, scan till the end of the statement.
3396 EatToEndOfStatement();
3399 const char *BodyStart = StartToken.getLoc().getPointer();
3400 const char *BodyEnd = EndToken.getLoc().getPointer();
3401 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3403 // We Are Anonymous.
3405 MacroParameters Parameters;
3406 return new Macro(Name, Body, Parameters);
3409 void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3410 raw_svector_ostream &OS) {
3413 MemoryBuffer *Instantiation =
3414 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3416 // Create the macro instantiation object and add to the current macro
3417 // instantiation stack.
3418 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3421 ActiveMacros.push_back(MI);
3423 // Jump to the macro instantiation and prime the lexer.
3424 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3425 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3429 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3431 if (ParseAbsoluteExpression(Count))
3432 return TokError("unexpected token in '.rept' directive");
3435 return TokError("Count is negative");
3437 if (Lexer.isNot(AsmToken::EndOfStatement))
3438 return TokError("unexpected token in '.rept' directive");
3440 // Eat the end of statement.
3443 // Lex the rept definition.
3444 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3448 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3449 // to hold the macro body with substitutions.
3450 SmallString<256> Buf;
3451 MacroParameters Parameters;
3453 raw_svector_ostream OS(Buf);
3455 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3458 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3463 /// ParseDirectiveIrp
3464 /// ::= .irp symbol,values
3465 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3466 MacroParameters Parameters;
3467 MacroParameter Parameter;
3469 if (ParseIdentifier(Parameter.first))
3470 return TokError("expected identifier in '.irp' directive");
3472 Parameters.push_back(Parameter);
3474 if (Lexer.isNot(AsmToken::Comma))
3475 return TokError("expected comma in '.irp' directive");
3480 if (ParseMacroArguments(0, A))
3483 // Eat the end of statement.
3486 // Lex the irp definition.
3487 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3491 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3492 // to hold the macro body with substitutions.
3493 SmallString<256> Buf;
3494 raw_svector_ostream OS(Buf);
3496 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3497 MacroArguments Args;
3500 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3504 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3509 /// ParseDirectiveIrpc
3510 /// ::= .irpc symbol,values
3511 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3512 MacroParameters Parameters;
3513 MacroParameter Parameter;
3515 if (ParseIdentifier(Parameter.first))
3516 return TokError("expected identifier in '.irpc' directive");
3518 Parameters.push_back(Parameter);
3520 if (Lexer.isNot(AsmToken::Comma))
3521 return TokError("expected comma in '.irpc' directive");
3526 if (ParseMacroArguments(0, A))
3529 if (A.size() != 1 || A.front().size() != 1)
3530 return TokError("unexpected token in '.irpc' directive");
3532 // Eat the end of statement.
3535 // Lex the irpc definition.
3536 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3540 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3541 // to hold the macro body with substitutions.
3542 SmallString<256> Buf;
3543 raw_svector_ostream OS(Buf);
3545 StringRef Values = A.front().front().getString();
3546 std::size_t I, End = Values.size();
3547 for (I = 0; I < End; ++I) {
3549 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3551 MacroArguments Args;
3552 Args.push_back(Arg);
3554 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3558 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3563 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3564 if (ActiveMacros.empty())
3565 return TokError("unmatched '.endr' directive");
3567 // The only .repl that should get here are the ones created by
3568 // InstantiateMacroLikeBody.
3569 assert(getLexer().is(AsmToken::EndOfStatement));
3576 enum AsmOpRewriteKind {
3582 struct AsmOpRewrite {
3583 AsmOpRewriteKind Kind;
3588 AsmOpRewrite(AsmOpRewriteKind kind, SMLoc loc, unsigned len)
3589 : Kind(kind), Loc(loc), Len(len) { }
3593 bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3594 unsigned &NumOutputs, unsigned &NumInputs,
3595 SmallVectorImpl<void *> &Names,
3596 SmallVectorImpl<std::string> &Constraints,
3597 SmallVectorImpl<void *> &Exprs,
3598 SmallVectorImpl<std::string> &Clobbers,
3599 const MCInstrInfo *MII,
3600 const MCInstPrinter *IP,
3601 MCAsmParserSemaCallback &SI) {
3602 SmallVector<void*, 4> Inputs;
3603 SmallVector<void*, 4> Outputs;
3604 SmallVector<std::string, 4> InputConstraints;
3605 SmallVector<std::string, 4> OutputConstraints;
3606 SmallVector<void*, 4> InputExprs;
3607 SmallVector<void*, 4> OutputExprs;
3608 std::set<std::string> ClobberRegs;
3610 SmallVector<struct AsmOpRewrite, 4> AsmStrRewrites;
3615 // While we have input, parse each statement.
3616 unsigned InputIdx = 0;
3617 unsigned OutputIdx = 0;
3618 while (getLexer().isNot(AsmToken::Eof)) {
3619 if (ParseStatement()) return true;
3621 if (isInstruction()) {
3622 const MCInstrDesc &Desc = MII->get(getOpcode());
3624 // Build the list of clobbers, outputs and inputs.
3625 for (unsigned i = 1, e = ParsedOperands.size(); i != e; ++i) {
3626 MCParsedAsmOperand *Operand = ParsedOperands[i];
3629 if (Operand->isImm()) {
3630 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Imm,
3631 Operand->getStartLoc(),
3632 Operand->getNameLen()));
3636 // Register operand.
3637 if (Operand->isReg()) {
3638 unsigned NumDefs = Desc.getNumDefs();
3640 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3642 raw_string_ostream OS(Reg);
3643 IP->printRegName(OS, Operand->getReg());
3644 ClobberRegs.insert(StringRef(OS.str()));
3649 // Expr/Input or Output.
3651 void *ExprResult = SI.LookupInlineAsmIdentifier(Operand->getName(),
3654 bool isOutput = (i == 1) && Desc.mayStore();
3656 std::string Constraint = "=";
3658 Outputs.push_back(II);
3659 OutputExprs.push_back(ExprResult);
3660 Constraint += Operand->getConstraint().str();
3661 OutputConstraints.push_back(Constraint);
3662 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Output,
3663 Operand->getStartLoc(),
3664 Operand->getNameLen()));
3666 Inputs.push_back(II);
3667 InputExprs.push_back(ExprResult);
3668 InputConstraints.push_back(Operand->getConstraint().str());
3669 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Input,
3670 Operand->getStartLoc(),
3671 Operand->getNameLen()));
3675 // Free any parsed operands.
3676 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
3677 delete ParsedOperands[i];
3678 ParsedOperands.clear();
3682 // Set the number of Outputs and Inputs.
3683 NumOutputs = Outputs.size();
3684 NumInputs = Inputs.size();
3686 // Set the unique clobbers.
3687 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3688 E = ClobberRegs.end(); I != E; ++I)
3689 Clobbers.push_back(*I);
3691 // Merge the various outputs and inputs. Output are expected first.
3692 if (NumOutputs || NumInputs) {
3693 unsigned NumExprs = NumOutputs + NumInputs;
3694 Names.resize(NumExprs);
3695 Constraints.resize(NumExprs);
3696 Exprs.resize(NumExprs);
3697 for (unsigned i = 0; i < NumOutputs; ++i) {
3698 Names[i] = Outputs[i];
3699 Constraints[i] = OutputConstraints[i];
3700 Exprs[i] = OutputExprs[i];
3702 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
3703 Names[j] = Inputs[i];
3704 Constraints[j] = InputConstraints[i];
3705 Exprs[j] = InputExprs[i];
3709 // Build the IR assembly string.
3710 std::string AsmStringIR;
3711 raw_string_ostream OS(AsmStringIR);
3712 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
3713 for (SmallVectorImpl<struct AsmOpRewrite>::iterator
3714 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3715 const char *Loc = (*I).Loc.getPointer();
3717 // Emit everything up to the immediate/expression.
3718 OS << StringRef(Start, Loc - Start);
3720 // Rewrite expressions in $N notation.
3721 switch ((*I).Kind) {
3723 OS << Twine("$$") + StringRef(Loc, (*I).Len);
3735 // Skip the original expression.
3736 Start = Loc + (*I).Len;
3739 // Emit the remainder of the asm string.
3740 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3741 if (Start != AsmEnd)
3742 OS << StringRef(Start, AsmEnd - Start);
3744 AsmString = OS.str();
3748 /// \brief Create an MCAsmParser instance.
3749 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3750 MCContext &C, MCStreamer &Out,
3751 const MCAsmInfo &MAI) {
3752 return new AsmParser(SM, C, Out, MAI);