1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCDwarf.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInstPrinter.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCParser/AsmCond.h"
25 #include "llvm/MC/MCParser/AsmLexer.h"
26 #include "llvm/MC/MCParser/MCAsmParser.h"
27 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSectionMachO.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/MC/MCTargetAsmParser.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/raw_ostream.h"
46 FatalAssemblerWarnings("fatal-assembler-warnings",
47 cl::desc("Consider warnings as error"));
49 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
53 /// \brief Helper class for tracking macro definitions.
54 typedef std::vector<AsmToken> MacroArgument;
55 typedef std::vector<MacroArgument> MacroArguments;
56 typedef std::pair<StringRef, MacroArgument> MacroParameter;
57 typedef std::vector<MacroParameter> MacroParameters;
62 MacroParameters Parameters;
65 Macro(StringRef N, StringRef B, const MacroParameters &P) :
66 Name(N), Body(B), Parameters(P) {}
69 /// \brief Helper class for storing information about an active macro
71 struct MacroInstantiation {
72 /// The macro being instantiated.
73 const Macro *TheMacro;
75 /// The macro instantiation with substitutions.
76 MemoryBuffer *Instantiation;
78 /// The location of the instantiation.
79 SMLoc InstantiationLoc;
81 /// The location where parsing should resume upon instantiation completion.
85 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
89 /// \brief The concrete assembly parser instance.
90 class AsmParser : public MCAsmParser {
91 friend class GenericAsmParser;
93 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
94 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
101 SourceMgr::DiagHandlerTy SavedDiagHandler;
102 void *SavedDiagContext;
103 MCAsmParserExtension *GenericParser;
104 MCAsmParserExtension *PlatformParser;
106 /// This is the current buffer index we're lexing from as managed by the
107 /// SourceMgr object.
110 AsmCond TheCondState;
111 std::vector<AsmCond> TheCondStack;
113 /// DirectiveMap - This is a table handlers for directives. Each handler is
114 /// invoked after the directive identifier is read and is responsible for
115 /// parsing and validating the rest of the directive. The handler is passed
116 /// in the directive name and the location of the directive keyword.
117 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
119 /// MacroMap - Map of currently defined macros.
120 StringMap<Macro*> MacroMap;
122 /// ActiveMacros - Stack of active macro instantiations.
123 std::vector<MacroInstantiation*> ActiveMacros;
125 /// Boolean tracking whether macro substitution is enabled.
126 unsigned MacrosEnabled : 1;
128 /// Flag tracking whether any errors have been encountered.
129 unsigned HadError : 1;
131 /// The values from the last parsed cpp hash file line comment if any.
132 StringRef CppHashFilename;
133 int64_t CppHashLineNumber;
136 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
137 unsigned AssemblerDialect;
139 /// IsDarwin - is Darwin compatibility enabled?
142 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
143 bool ParsingInlineAsm;
145 /// ParsedOperands - The parsed operands from the last parsed statement.
146 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
148 /// Opcode - The opcode from the last parsed instruction. This is MS-style
149 /// inline asm specific.
153 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
154 const MCAsmInfo &MAI);
155 virtual ~AsmParser();
157 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
159 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
161 DirectiveHandler Handler) {
162 DirectiveMap[Directive] = std::make_pair(Object, Handler);
166 /// @name MCAsmParser Interface
169 virtual SourceMgr &getSourceManager() { return SrcMgr; }
170 virtual MCAsmLexer &getLexer() { return Lexer; }
171 virtual MCContext &getContext() { return Ctx; }
172 virtual MCStreamer &getStreamer() { return Out; }
173 virtual unsigned getAssemblerDialect() {
174 if (AssemblerDialect == ~0U)
175 return MAI.getAssemblerDialect();
177 return AssemblerDialect;
179 virtual void setAssemblerDialect(unsigned i) {
180 AssemblerDialect = i;
183 virtual bool Warning(SMLoc L, const Twine &Msg,
184 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
185 virtual bool Error(SMLoc L, const Twine &Msg,
186 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
188 virtual const AsmToken &Lex();
190 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
191 bool isParsingInlineAsm() { return ParsingInlineAsm; }
193 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
194 unsigned &NumOutputs, unsigned &NumInputs,
195 SmallVectorImpl<void *> &OpDecls,
196 SmallVectorImpl<std::string> &Constraints,
197 SmallVectorImpl<std::string> &Clobbers,
198 const MCInstrInfo *MII,
199 const MCInstPrinter *IP,
200 MCAsmParserSemaCallback &SI);
202 bool ParseExpression(const MCExpr *&Res);
203 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
204 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
205 virtual bool ParseAbsoluteExpression(int64_t &Res);
210 void CheckForValidSection();
212 bool ParseStatement();
213 void EatToEndOfLine();
214 bool ParseCppHashLineFilenameComment(const SMLoc &L);
216 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
217 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
218 const MacroParameters &Parameters,
219 const MacroArguments &A,
221 void HandleMacroExit();
223 void PrintMacroInstantiations();
224 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
225 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
226 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
228 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
230 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
231 bool EnterIncludeFile(const std::string &Filename);
232 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
233 /// This returns true on failure.
234 bool ProcessIncbinFile(const std::string &Filename);
236 /// \brief Reset the current lexer position to that given by \p Loc. The
237 /// current token is not set; clients should ensure Lex() is called
239 void JumpToLoc(SMLoc Loc);
241 virtual void EatToEndOfStatement();
243 bool ParseMacroArgument(MacroArgument &MA,
244 AsmToken::TokenKind &ArgumentDelimiter);
245 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
247 /// \brief Parse up to the end of statement and a return the contents from the
248 /// current token until the end of the statement; the current token on exit
249 /// will be either the EndOfStatement or EOF.
250 virtual StringRef ParseStringToEndOfStatement();
252 /// \brief Parse until the end of a statement or a comma is encountered,
253 /// return the contents from the current token up to the end or comma.
254 StringRef ParseStringToComma();
256 bool ParseAssignment(StringRef Name, bool allow_redef,
257 bool NoDeadStrip = false);
259 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
260 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
261 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
262 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
264 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
265 /// and set \p Res to the identifier contents.
266 virtual bool ParseIdentifier(StringRef &Res);
268 // Directive Parsing.
270 // ".ascii", ".asciiz", ".string"
271 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
272 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
273 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
274 bool ParseDirectiveFill(); // ".fill"
275 bool ParseDirectiveSpace(); // ".space"
276 bool ParseDirectiveZero(); // ".zero"
277 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
278 bool ParseDirectiveOrg(); // ".org"
279 // ".align{,32}", ".p2align{,w,l}"
280 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
282 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
283 /// accepts a single symbol (which should be a label or an external).
284 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
286 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
288 bool ParseDirectiveAbort(); // ".abort"
289 bool ParseDirectiveInclude(); // ".include"
290 bool ParseDirectiveIncbin(); // ".incbin"
292 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
293 // ".ifb" or ".ifnb", depending on ExpectBlank.
294 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
295 // ".ifc" or ".ifnc", depending on ExpectEqual.
296 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
297 // ".ifdef" or ".ifndef", depending on expect_defined
298 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
299 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
300 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
301 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
303 /// ParseEscapedString - Parse the current token as a string which may include
304 /// escaped characters and return the string contents.
305 bool ParseEscapedString(std::string &Data);
307 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
308 MCSymbolRefExpr::VariantKind Variant);
310 // Macro-like directives
311 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
312 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
313 raw_svector_ostream &OS);
314 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
315 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
316 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
317 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
319 // MS-style inline assembly parsing.
320 bool isInstruction() { return Opcode != (unsigned)~0x0; }
321 unsigned getOpcode() { return Opcode; }
324 /// \brief Generic implementations of directive handling, etc. which is shared
325 /// (or the default, at least) for all assembler parser.
326 class GenericAsmParser : public MCAsmParserExtension {
327 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
328 void AddDirectiveHandler(StringRef Directive) {
329 getParser().AddDirectiveHandler(this, Directive,
330 HandleDirective<GenericAsmParser, Handler>);
333 GenericAsmParser() {}
335 AsmParser &getParser() {
336 return (AsmParser&) this->MCAsmParserExtension::getParser();
339 virtual void Initialize(MCAsmParser &Parser) {
340 // Call the base implementation.
341 this->MCAsmParserExtension::Initialize(Parser);
343 // Debugging directives.
344 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
345 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
346 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
347 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
350 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
352 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
354 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
356 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
358 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
359 ".cfi_def_cfa_offset");
360 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
361 ".cfi_adjust_cfa_offset");
362 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
363 ".cfi_def_cfa_register");
364 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
366 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
369 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
371 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
373 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
375 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
377 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
379 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
381 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
383 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
386 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
388 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
390 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
391 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
392 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
393 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
395 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
396 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
399 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
401 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
402 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
403 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
404 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
405 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
406 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
407 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
408 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
409 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
410 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
411 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
412 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
413 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
414 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
415 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
416 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
417 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
418 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
419 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
420 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
422 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
423 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
424 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
425 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
427 bool ParseDirectiveLEB128(StringRef, SMLoc);
434 extern MCAsmParserExtension *createDarwinAsmParser();
435 extern MCAsmParserExtension *createELFAsmParser();
436 extern MCAsmParserExtension *createCOFFAsmParser();
440 enum { DEFAULT_ADDRSPACE = 0 };
442 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
443 MCStreamer &_Out, const MCAsmInfo &_MAI)
444 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
445 GenericParser(new GenericAsmParser), PlatformParser(0),
446 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
447 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false),
449 // Save the old handler.
450 SavedDiagHandler = SrcMgr.getDiagHandler();
451 SavedDiagContext = SrcMgr.getDiagContext();
452 // Set our own handler which calls the saved handler.
453 SrcMgr.setDiagHandler(DiagHandler, this);
454 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
456 // Initialize the generic parser.
457 GenericParser->Initialize(*this);
459 // Initialize the platform / file format parser.
461 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
463 if (_MAI.hasMicrosoftFastStdCallMangling()) {
464 PlatformParser = createCOFFAsmParser();
465 PlatformParser->Initialize(*this);
466 } else if (_MAI.hasSubsectionsViaSymbols()) {
467 PlatformParser = createDarwinAsmParser();
468 PlatformParser->Initialize(*this);
471 PlatformParser = createELFAsmParser();
472 PlatformParser->Initialize(*this);
476 AsmParser::~AsmParser() {
477 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
479 // Destroy any macros.
480 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
481 ie = MacroMap.end(); it != ie; ++it)
482 delete it->getValue();
484 delete PlatformParser;
485 delete GenericParser;
488 void AsmParser::PrintMacroInstantiations() {
489 // Print the active macro instantiation stack.
490 for (std::vector<MacroInstantiation*>::const_reverse_iterator
491 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
492 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
493 "while in macro instantiation");
496 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
497 if (FatalAssemblerWarnings)
498 return Error(L, Msg, Ranges);
499 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
500 PrintMacroInstantiations();
504 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
506 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
507 PrintMacroInstantiations();
511 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
512 std::string IncludedFile;
513 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
519 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
524 /// Process the specified .incbin file by seaching for it in the include paths
525 /// then just emitting the byte contents of the file to the streamer. This
526 /// returns true on failure.
527 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
528 std::string IncludedFile;
529 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
533 // Pick up the bytes from the file and emit them.
534 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
539 void AsmParser::JumpToLoc(SMLoc Loc) {
540 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
541 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
544 const AsmToken &AsmParser::Lex() {
545 const AsmToken *tok = &Lexer.Lex();
547 if (tok->is(AsmToken::Eof)) {
548 // If this is the end of an included file, pop the parent file off the
550 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
551 if (ParentIncludeLoc != SMLoc()) {
552 JumpToLoc(ParentIncludeLoc);
557 if (tok->is(AsmToken::Error))
558 Error(Lexer.getErrLoc(), Lexer.getErr());
563 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
564 // Create the initial section, if requested.
565 if (!NoInitialTextSection)
572 AsmCond StartingCondState = TheCondState;
574 // If we are generating dwarf for assembly source files save the initial text
575 // section and generate a .file directive.
576 if (getContext().getGenDwarfForAssembly()) {
577 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
578 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
579 getStreamer().EmitLabel(SectionStartSym);
580 getContext().setGenDwarfSectionStartSym(SectionStartSym);
581 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
582 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
585 // While we have input, parse each statement.
586 while (Lexer.isNot(AsmToken::Eof)) {
587 if (!ParseStatement()) continue;
589 // We had an error, validate that one was emitted and recover by skipping to
591 assert(HadError && "Parse statement returned an error, but none emitted!");
592 EatToEndOfStatement();
595 if (TheCondState.TheCond != StartingCondState.TheCond ||
596 TheCondState.Ignore != StartingCondState.Ignore)
597 return TokError("unmatched .ifs or .elses");
599 // Check to see there are no empty DwarfFile slots.
600 const std::vector<MCDwarfFile *> &MCDwarfFiles =
601 getContext().getMCDwarfFiles();
602 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
603 if (!MCDwarfFiles[i])
604 TokError("unassigned file number: " + Twine(i) + " for .file directives");
607 // Check to see that all assembler local symbols were actually defined.
608 // Targets that don't do subsections via symbols may not want this, though,
609 // so conservatively exclude them. Only do this if we're finalizing, though,
610 // as otherwise we won't necessarilly have seen everything yet.
611 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
612 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
613 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
616 MCSymbol *Sym = i->getValue();
617 // Variable symbols may not be marked as defined, so check those
618 // explicitly. If we know it's a variable, we have a definition for
619 // the purposes of this check.
620 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
621 // FIXME: We would really like to refer back to where the symbol was
622 // first referenced for a source location. We need to add something
623 // to track that. Currently, we just point to the end of the file.
624 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
625 "assembler local symbol '" + Sym->getName() +
631 // Finalize the output stream if there are no errors and if the client wants
633 if (!HadError && !NoFinalize)
639 void AsmParser::CheckForValidSection() {
640 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
641 TokError("expected section directive before assembly directive");
642 Out.SwitchSection(Ctx.getMachOSection(
644 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
645 0, SectionKind::getText()));
649 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
650 void AsmParser::EatToEndOfStatement() {
651 while (Lexer.isNot(AsmToken::EndOfStatement) &&
652 Lexer.isNot(AsmToken::Eof))
656 if (Lexer.is(AsmToken::EndOfStatement))
660 StringRef AsmParser::ParseStringToEndOfStatement() {
661 const char *Start = getTok().getLoc().getPointer();
663 while (Lexer.isNot(AsmToken::EndOfStatement) &&
664 Lexer.isNot(AsmToken::Eof))
667 const char *End = getTok().getLoc().getPointer();
668 return StringRef(Start, End - Start);
671 StringRef AsmParser::ParseStringToComma() {
672 const char *Start = getTok().getLoc().getPointer();
674 while (Lexer.isNot(AsmToken::EndOfStatement) &&
675 Lexer.isNot(AsmToken::Comma) &&
676 Lexer.isNot(AsmToken::Eof))
679 const char *End = getTok().getLoc().getPointer();
680 return StringRef(Start, End - Start);
683 /// ParseParenExpr - Parse a paren expression and return it.
684 /// NOTE: This assumes the leading '(' has already been consumed.
686 /// parenexpr ::= expr)
688 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
689 if (ParseExpression(Res)) return true;
690 if (Lexer.isNot(AsmToken::RParen))
691 return TokError("expected ')' in parentheses expression");
692 EndLoc = Lexer.getLoc();
697 /// ParseBracketExpr - Parse a bracket expression and return it.
698 /// NOTE: This assumes the leading '[' has already been consumed.
700 /// bracketexpr ::= expr]
702 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
703 if (ParseExpression(Res)) return true;
704 if (Lexer.isNot(AsmToken::RBrac))
705 return TokError("expected ']' in brackets expression");
706 EndLoc = Lexer.getLoc();
711 /// ParsePrimaryExpr - Parse a primary expression and return it.
712 /// primaryexpr ::= (parenexpr
713 /// primaryexpr ::= symbol
714 /// primaryexpr ::= number
715 /// primaryexpr ::= '.'
716 /// primaryexpr ::= ~,+,- primaryexpr
717 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
718 switch (Lexer.getKind()) {
720 return TokError("unknown token in expression");
721 // If we have an error assume that we've already handled it.
722 case AsmToken::Error:
724 case AsmToken::Exclaim:
725 Lex(); // Eat the operator.
726 if (ParsePrimaryExpr(Res, EndLoc))
728 Res = MCUnaryExpr::CreateLNot(Res, getContext());
730 case AsmToken::Dollar:
731 case AsmToken::String:
732 case AsmToken::Identifier: {
733 EndLoc = Lexer.getLoc();
735 StringRef Identifier;
736 if (ParseIdentifier(Identifier))
739 // This is a symbol reference.
740 std::pair<StringRef, StringRef> Split = Identifier.split('@');
741 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
743 // Lookup the symbol variant if used.
744 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
745 if (Split.first.size() != Identifier.size()) {
746 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
747 if (Variant == MCSymbolRefExpr::VK_Invalid) {
748 Variant = MCSymbolRefExpr::VK_None;
749 return TokError("invalid variant '" + Split.second + "'");
753 // If this is an absolute variable reference, substitute it now to preserve
754 // semantics in the face of reassignment.
755 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
757 return Error(EndLoc, "unexpected modifier on variable reference");
759 Res = Sym->getVariableValue();
763 // Otherwise create a symbol ref.
764 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
767 case AsmToken::Integer: {
768 SMLoc Loc = getTok().getLoc();
769 int64_t IntVal = getTok().getIntVal();
770 Res = MCConstantExpr::Create(IntVal, getContext());
771 EndLoc = Lexer.getLoc();
773 // Look for 'b' or 'f' following an Integer as a directional label
774 if (Lexer.getKind() == AsmToken::Identifier) {
775 StringRef IDVal = getTok().getString();
776 if (IDVal == "f" || IDVal == "b"){
777 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
778 IDVal == "f" ? 1 : 0);
779 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
781 if (IDVal == "b" && Sym->isUndefined())
782 return Error(Loc, "invalid reference to undefined symbol");
783 EndLoc = Lexer.getLoc();
784 Lex(); // Eat identifier.
789 case AsmToken::Real: {
790 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
791 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
792 Res = MCConstantExpr::Create(IntVal, getContext());
796 case AsmToken::Dot: {
797 // This is a '.' reference, which references the current PC. Emit a
798 // temporary label to the streamer and refer to it.
799 MCSymbol *Sym = Ctx.CreateTempSymbol();
801 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
802 EndLoc = Lexer.getLoc();
803 Lex(); // Eat identifier.
806 case AsmToken::LParen:
807 Lex(); // Eat the '('.
808 return ParseParenExpr(Res, EndLoc);
809 case AsmToken::LBrac:
810 if (!PlatformParser->HasBracketExpressions())
811 return TokError("brackets expression not supported on this target");
812 Lex(); // Eat the '['.
813 return ParseBracketExpr(Res, EndLoc);
814 case AsmToken::Minus:
815 Lex(); // Eat the operator.
816 if (ParsePrimaryExpr(Res, EndLoc))
818 Res = MCUnaryExpr::CreateMinus(Res, getContext());
821 Lex(); // Eat the operator.
822 if (ParsePrimaryExpr(Res, EndLoc))
824 Res = MCUnaryExpr::CreatePlus(Res, getContext());
826 case AsmToken::Tilde:
827 Lex(); // Eat the operator.
828 if (ParsePrimaryExpr(Res, EndLoc))
830 Res = MCUnaryExpr::CreateNot(Res, getContext());
835 bool AsmParser::ParseExpression(const MCExpr *&Res) {
837 return ParseExpression(Res, EndLoc);
841 AsmParser::ApplyModifierToExpr(const MCExpr *E,
842 MCSymbolRefExpr::VariantKind Variant) {
843 // Recurse over the given expression, rebuilding it to apply the given variant
844 // if there is exactly one symbol.
845 switch (E->getKind()) {
847 case MCExpr::Constant:
850 case MCExpr::SymbolRef: {
851 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
853 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
854 TokError("invalid variant on expression '" +
855 getTok().getIdentifier() + "' (already modified)");
859 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
862 case MCExpr::Unary: {
863 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
864 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
867 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
870 case MCExpr::Binary: {
871 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
872 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
873 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
878 if (!LHS) LHS = BE->getLHS();
879 if (!RHS) RHS = BE->getRHS();
881 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
885 llvm_unreachable("Invalid expression kind!");
888 /// ParseExpression - Parse an expression and return it.
890 /// expr ::= expr &&,|| expr -> lowest.
891 /// expr ::= expr |,^,&,! expr
892 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
893 /// expr ::= expr <<,>> expr
894 /// expr ::= expr +,- expr
895 /// expr ::= expr *,/,% expr -> highest.
896 /// expr ::= primaryexpr
898 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
899 // Parse the expression.
901 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
904 // As a special case, we support 'a op b @ modifier' by rewriting the
905 // expression to include the modifier. This is inefficient, but in general we
906 // expect users to use 'a@modifier op b'.
907 if (Lexer.getKind() == AsmToken::At) {
910 if (Lexer.isNot(AsmToken::Identifier))
911 return TokError("unexpected symbol modifier following '@'");
913 MCSymbolRefExpr::VariantKind Variant =
914 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
915 if (Variant == MCSymbolRefExpr::VK_Invalid)
916 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
918 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
920 return TokError("invalid modifier '" + getTok().getIdentifier() +
921 "' (no symbols present)");
928 // Try to constant fold it up front, if possible.
930 if (Res->EvaluateAsAbsolute(Value))
931 Res = MCConstantExpr::Create(Value, getContext());
936 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
938 return ParseParenExpr(Res, EndLoc) ||
939 ParseBinOpRHS(1, Res, EndLoc);
942 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
945 SMLoc StartLoc = Lexer.getLoc();
946 if (ParseExpression(Expr))
949 if (!Expr->EvaluateAsAbsolute(Res))
950 return Error(StartLoc, "expected absolute expression");
955 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
956 MCBinaryExpr::Opcode &Kind) {
959 return 0; // not a binop.
961 // Lowest Precedence: &&, ||
962 case AsmToken::AmpAmp:
963 Kind = MCBinaryExpr::LAnd;
965 case AsmToken::PipePipe:
966 Kind = MCBinaryExpr::LOr;
970 // Low Precedence: |, &, ^
972 // FIXME: gas seems to support '!' as an infix operator?
974 Kind = MCBinaryExpr::Or;
976 case AsmToken::Caret:
977 Kind = MCBinaryExpr::Xor;
980 Kind = MCBinaryExpr::And;
983 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
984 case AsmToken::EqualEqual:
985 Kind = MCBinaryExpr::EQ;
987 case AsmToken::ExclaimEqual:
988 case AsmToken::LessGreater:
989 Kind = MCBinaryExpr::NE;
992 Kind = MCBinaryExpr::LT;
994 case AsmToken::LessEqual:
995 Kind = MCBinaryExpr::LTE;
997 case AsmToken::Greater:
998 Kind = MCBinaryExpr::GT;
1000 case AsmToken::GreaterEqual:
1001 Kind = MCBinaryExpr::GTE;
1004 // Intermediate Precedence: <<, >>
1005 case AsmToken::LessLess:
1006 Kind = MCBinaryExpr::Shl;
1008 case AsmToken::GreaterGreater:
1009 Kind = MCBinaryExpr::Shr;
1012 // High Intermediate Precedence: +, -
1013 case AsmToken::Plus:
1014 Kind = MCBinaryExpr::Add;
1016 case AsmToken::Minus:
1017 Kind = MCBinaryExpr::Sub;
1020 // Highest Precedence: *, /, %
1021 case AsmToken::Star:
1022 Kind = MCBinaryExpr::Mul;
1024 case AsmToken::Slash:
1025 Kind = MCBinaryExpr::Div;
1027 case AsmToken::Percent:
1028 Kind = MCBinaryExpr::Mod;
1034 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1035 /// Res contains the LHS of the expression on input.
1036 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1039 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1040 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1042 // If the next token is lower precedence than we are allowed to eat, return
1043 // successfully with what we ate already.
1044 if (TokPrec < Precedence)
1049 // Eat the next primary expression.
1051 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1053 // If BinOp binds less tightly with RHS than the operator after RHS, let
1054 // the pending operator take RHS as its LHS.
1055 MCBinaryExpr::Opcode Dummy;
1056 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1057 if (TokPrec < NextTokPrec) {
1058 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1061 // Merge LHS and RHS according to operator.
1062 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1067 /// ::= EndOfStatement
1068 /// ::= Label* Directive ...Operands... EndOfStatement
1069 /// ::= Label* Identifier OperandList* EndOfStatement
1070 bool AsmParser::ParseStatement() {
1071 if (Lexer.is(AsmToken::EndOfStatement)) {
1077 // Statements always start with an identifier or are a full line comment.
1078 AsmToken ID = getTok();
1079 SMLoc IDLoc = ID.getLoc();
1081 int64_t LocalLabelVal = -1;
1082 // A full line comment is a '#' as the first token.
1083 if (Lexer.is(AsmToken::Hash))
1084 return ParseCppHashLineFilenameComment(IDLoc);
1086 // Allow an integer followed by a ':' as a directional local label.
1087 if (Lexer.is(AsmToken::Integer)) {
1088 LocalLabelVal = getTok().getIntVal();
1089 if (LocalLabelVal < 0) {
1090 if (!TheCondState.Ignore)
1091 return TokError("unexpected token at start of statement");
1095 IDVal = getTok().getString();
1096 Lex(); // Consume the integer token to be used as an identifier token.
1097 if (Lexer.getKind() != AsmToken::Colon) {
1098 if (!TheCondState.Ignore)
1099 return TokError("unexpected token at start of statement");
1103 } else if (Lexer.is(AsmToken::Dot)) {
1104 // Treat '.' as a valid identifier in this context.
1108 } else if (ParseIdentifier(IDVal)) {
1109 if (!TheCondState.Ignore)
1110 return TokError("unexpected token at start of statement");
1115 // Handle conditional assembly here before checking for skipping. We
1116 // have to do this so that .endif isn't skipped in a ".if 0" block for
1119 return ParseDirectiveIf(IDLoc);
1120 if (IDVal == ".ifb")
1121 return ParseDirectiveIfb(IDLoc, true);
1122 if (IDVal == ".ifnb")
1123 return ParseDirectiveIfb(IDLoc, false);
1124 if (IDVal == ".ifc")
1125 return ParseDirectiveIfc(IDLoc, true);
1126 if (IDVal == ".ifnc")
1127 return ParseDirectiveIfc(IDLoc, false);
1128 if (IDVal == ".ifdef")
1129 return ParseDirectiveIfdef(IDLoc, true);
1130 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1131 return ParseDirectiveIfdef(IDLoc, false);
1132 if (IDVal == ".elseif")
1133 return ParseDirectiveElseIf(IDLoc);
1134 if (IDVal == ".else")
1135 return ParseDirectiveElse(IDLoc);
1136 if (IDVal == ".endif")
1137 return ParseDirectiveEndIf(IDLoc);
1139 // If we are in a ".if 0" block, ignore this statement.
1140 if (TheCondState.Ignore) {
1141 EatToEndOfStatement();
1145 // FIXME: Recurse on local labels?
1147 // See what kind of statement we have.
1148 switch (Lexer.getKind()) {
1149 case AsmToken::Colon: {
1150 CheckForValidSection();
1152 // identifier ':' -> Label.
1155 // Diagnose attempt to use '.' as a label.
1157 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1159 // Diagnose attempt to use a variable as a label.
1161 // FIXME: Diagnostics. Note the location of the definition as a label.
1162 // FIXME: This doesn't diagnose assignment to a symbol which has been
1163 // implicitly marked as external.
1165 if (LocalLabelVal == -1)
1166 Sym = getContext().GetOrCreateSymbol(IDVal);
1168 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1169 if (!Sym->isUndefined() || Sym->isVariable())
1170 return Error(IDLoc, "invalid symbol redefinition");
1175 // If we are generating dwarf for assembly source files then gather the
1176 // info to make a dwarf label entry for this label if needed.
1177 if (getContext().getGenDwarfForAssembly())
1178 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1181 // Consume any end of statement token, if present, to avoid spurious
1182 // AddBlankLine calls().
1183 if (Lexer.is(AsmToken::EndOfStatement)) {
1185 if (Lexer.is(AsmToken::Eof))
1189 return ParseStatement();
1192 case AsmToken::Equal:
1193 // identifier '=' ... -> assignment statement
1196 return ParseAssignment(IDVal, true);
1198 default: // Normal instruction or directive.
1202 // If macros are enabled, check to see if this is a macro instantiation.
1204 if (const Macro *M = MacroMap.lookup(IDVal))
1205 return HandleMacroEntry(IDVal, IDLoc, M);
1207 // Otherwise, we have a normal instruction or directive.
1208 if (IDVal[0] == '.' && IDVal != ".") {
1210 // Target hook for parsing target specific directives.
1211 if (!getTargetParser().ParseDirective(ID))
1214 // Assembler features
1215 if (IDVal == ".set" || IDVal == ".equ")
1216 return ParseDirectiveSet(IDVal, true);
1217 if (IDVal == ".equiv")
1218 return ParseDirectiveSet(IDVal, false);
1222 if (IDVal == ".ascii")
1223 return ParseDirectiveAscii(IDVal, false);
1224 if (IDVal == ".asciz" || IDVal == ".string")
1225 return ParseDirectiveAscii(IDVal, true);
1227 if (IDVal == ".byte")
1228 return ParseDirectiveValue(1);
1229 if (IDVal == ".short")
1230 return ParseDirectiveValue(2);
1231 if (IDVal == ".value")
1232 return ParseDirectiveValue(2);
1233 if (IDVal == ".2byte")
1234 return ParseDirectiveValue(2);
1235 if (IDVal == ".long")
1236 return ParseDirectiveValue(4);
1237 if (IDVal == ".int")
1238 return ParseDirectiveValue(4);
1239 if (IDVal == ".4byte")
1240 return ParseDirectiveValue(4);
1241 if (IDVal == ".quad")
1242 return ParseDirectiveValue(8);
1243 if (IDVal == ".8byte")
1244 return ParseDirectiveValue(8);
1245 if (IDVal == ".single" || IDVal == ".float")
1246 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1247 if (IDVal == ".double")
1248 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1250 if (IDVal == ".align") {
1251 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1252 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1254 if (IDVal == ".align32") {
1255 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1256 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1258 if (IDVal == ".balign")
1259 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1260 if (IDVal == ".balignw")
1261 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1262 if (IDVal == ".balignl")
1263 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1264 if (IDVal == ".p2align")
1265 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1266 if (IDVal == ".p2alignw")
1267 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1268 if (IDVal == ".p2alignl")
1269 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1271 if (IDVal == ".org")
1272 return ParseDirectiveOrg();
1274 if (IDVal == ".fill")
1275 return ParseDirectiveFill();
1276 if (IDVal == ".space" || IDVal == ".skip")
1277 return ParseDirectiveSpace();
1278 if (IDVal == ".zero")
1279 return ParseDirectiveZero();
1281 // Symbol attribute directives
1283 if (IDVal == ".extern") {
1284 EatToEndOfStatement(); // .extern is the default, ignore it.
1287 if (IDVal == ".globl" || IDVal == ".global")
1288 return ParseDirectiveSymbolAttribute(MCSA_Global);
1289 if (IDVal == ".indirect_symbol")
1290 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1291 if (IDVal == ".lazy_reference")
1292 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1293 if (IDVal == ".no_dead_strip")
1294 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1295 if (IDVal == ".symbol_resolver")
1296 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1297 if (IDVal == ".private_extern")
1298 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1299 if (IDVal == ".reference")
1300 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1301 if (IDVal == ".weak_definition")
1302 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1303 if (IDVal == ".weak_reference")
1304 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1305 if (IDVal == ".weak_def_can_be_hidden")
1306 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1308 if (IDVal == ".comm" || IDVal == ".common")
1309 return ParseDirectiveComm(/*IsLocal=*/false);
1310 if (IDVal == ".lcomm")
1311 return ParseDirectiveComm(/*IsLocal=*/true);
1313 if (IDVal == ".abort")
1314 return ParseDirectiveAbort();
1315 if (IDVal == ".include")
1316 return ParseDirectiveInclude();
1317 if (IDVal == ".incbin")
1318 return ParseDirectiveIncbin();
1320 if (IDVal == ".code16" || IDVal == ".code16gcc")
1321 return TokError(Twine(IDVal) + " not supported yet");
1323 // Macro-like directives
1324 if (IDVal == ".rept")
1325 return ParseDirectiveRept(IDLoc);
1326 if (IDVal == ".irp")
1327 return ParseDirectiveIrp(IDLoc);
1328 if (IDVal == ".irpc")
1329 return ParseDirectiveIrpc(IDLoc);
1330 if (IDVal == ".endr")
1331 return ParseDirectiveEndr(IDLoc);
1333 // Look up the handler in the handler table.
1334 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1335 DirectiveMap.lookup(IDVal);
1337 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1340 return Error(IDLoc, "unknown directive");
1343 CheckForValidSection();
1345 // Canonicalize the opcode to lower case.
1346 SmallString<128> OpcodeStr;
1347 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1348 OpcodeStr.push_back(tolower(IDVal[i]));
1350 bool HadError = getTargetParser().ParseInstruction(OpcodeStr.str(), IDLoc,
1353 // Dump the parsed representation, if requested.
1354 if (getShowParsedOperands()) {
1355 SmallString<256> Str;
1356 raw_svector_ostream OS(Str);
1357 OS << "parsed instruction: [";
1358 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1361 ParsedOperands[i]->print(OS);
1365 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1368 // If we are generating dwarf for assembly source files and the current
1369 // section is the initial text section then generate a .loc directive for
1371 if (!HadError && getContext().getGenDwarfForAssembly() &&
1372 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1373 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1374 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1375 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1376 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1380 // If parsing succeeded, match the instruction.
1383 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Opcode,
1384 ParsedOperands, Out,
1389 // Free any parsed operands. If parsing ms-style inline assembly the operands
1390 // will be freed by the ParseMSInlineAsm() function.
1391 if (!ParsingInlineAsm) {
1392 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1393 delete ParsedOperands[i];
1394 ParsedOperands.clear();
1397 // Don't skip the rest of the line, the instruction parser is responsible for
1402 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1403 /// since they may not be able to be tokenized to get to the end of line token.
1404 void AsmParser::EatToEndOfLine() {
1405 if (!Lexer.is(AsmToken::EndOfStatement))
1406 Lexer.LexUntilEndOfLine();
1411 /// ParseCppHashLineFilenameComment as this:
1412 /// ::= # number "filename"
1413 /// or just as a full line comment if it doesn't have a number and a string.
1414 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1415 Lex(); // Eat the hash token.
1417 if (getLexer().isNot(AsmToken::Integer)) {
1418 // Consume the line since in cases it is not a well-formed line directive,
1419 // as if were simply a full line comment.
1424 int64_t LineNumber = getTok().getIntVal();
1427 if (getLexer().isNot(AsmToken::String)) {
1432 StringRef Filename = getTok().getString();
1433 // Get rid of the enclosing quotes.
1434 Filename = Filename.substr(1, Filename.size()-2);
1436 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1438 CppHashFilename = Filename;
1439 CppHashLineNumber = LineNumber;
1441 // Ignore any trailing characters, they're just comment.
1446 /// DiagHandler - will use the last parsed cpp hash line filename comment
1447 /// for the Filename and LineNo if any in the diagnostic.
1448 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1449 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1450 raw_ostream &OS = errs();
1452 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1453 const SMLoc &DiagLoc = Diag.getLoc();
1454 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1455 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1457 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1458 // before printing the message.
1459 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1460 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1461 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1462 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1465 // If we have not parsed a cpp hash line filename comment or the source
1466 // manager changed or buffer changed (like in a nested include) then just
1467 // print the normal diagnostic using its Filename and LineNo.
1468 if (!Parser->CppHashLineNumber ||
1469 &DiagSrcMgr != &Parser->SrcMgr ||
1470 DiagBuf != CppHashBuf) {
1471 if (Parser->SavedDiagHandler)
1472 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1478 // Use the CppHashFilename and calculate a line number based on the
1479 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1481 const std::string Filename = Parser->CppHashFilename;
1483 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1484 int CppHashLocLineNo =
1485 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1486 int LineNo = Parser->CppHashLineNumber - 1 +
1487 (DiagLocLineNo - CppHashLocLineNo);
1489 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1490 Filename, LineNo, Diag.getColumnNo(),
1491 Diag.getKind(), Diag.getMessage(),
1492 Diag.getLineContents(), Diag.getRanges());
1494 if (Parser->SavedDiagHandler)
1495 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1497 NewDiag.print(0, OS);
1500 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1501 // difference being that that function accepts '@' as part of identifiers and
1502 // we can't do that. AsmLexer.cpp should probably be changed to handle
1503 // '@' as a special case when needed.
1504 static bool isIdentifierChar(char c) {
1505 return isalnum(c) || c == '_' || c == '$' || c == '.';
1508 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1509 const MacroParameters &Parameters,
1510 const MacroArguments &A,
1512 unsigned NParameters = Parameters.size();
1513 if (NParameters != 0 && NParameters != A.size())
1514 return Error(L, "Wrong number of arguments");
1516 // A macro without parameters is handled differently on Darwin:
1517 // gas accepts no arguments and does no substitutions
1518 while (!Body.empty()) {
1519 // Scan for the next substitution.
1520 std::size_t End = Body.size(), Pos = 0;
1521 for (; Pos != End; ++Pos) {
1522 // Check for a substitution or escape.
1524 // This macro has no parameters, look for $0, $1, etc.
1525 if (Body[Pos] != '$' || Pos + 1 == End)
1528 char Next = Body[Pos + 1];
1529 if (Next == '$' || Next == 'n' || isdigit(Next))
1532 // This macro has parameters, look for \foo, \bar, etc.
1533 if (Body[Pos] == '\\' && Pos + 1 != End)
1539 OS << Body.slice(0, Pos);
1541 // Check if we reached the end.
1546 switch (Body[Pos+1]) {
1552 // $n => number of arguments
1557 // $[0-9] => argument
1559 // Missing arguments are ignored.
1560 unsigned Index = Body[Pos+1] - '0';
1561 if (Index >= A.size())
1564 // Otherwise substitute with the token values, with spaces eliminated.
1565 for (MacroArgument::const_iterator it = A[Index].begin(),
1566 ie = A[Index].end(); it != ie; ++it)
1567 OS << it->getString();
1573 unsigned I = Pos + 1;
1574 while (isIdentifierChar(Body[I]) && I + 1 != End)
1577 const char *Begin = Body.data() + Pos +1;
1578 StringRef Argument(Begin, I - (Pos +1));
1580 for (; Index < NParameters; ++Index)
1581 if (Parameters[Index].first == Argument)
1584 if (Index == NParameters) {
1585 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1588 OS << '\\' << Argument;
1592 for (MacroArgument::const_iterator it = A[Index].begin(),
1593 ie = A[Index].end(); it != ie; ++it)
1594 if (it->getKind() == AsmToken::String)
1595 OS << it->getStringContents();
1597 OS << it->getString();
1599 Pos += 1 + Argument.size();
1602 // Update the scan point.
1603 Body = Body.substr(Pos);
1609 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1611 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1615 static bool IsOperator(AsmToken::TokenKind kind)
1621 case AsmToken::Plus:
1622 case AsmToken::Minus:
1623 case AsmToken::Tilde:
1624 case AsmToken::Slash:
1625 case AsmToken::Star:
1627 case AsmToken::Equal:
1628 case AsmToken::EqualEqual:
1629 case AsmToken::Pipe:
1630 case AsmToken::PipePipe:
1631 case AsmToken::Caret:
1633 case AsmToken::AmpAmp:
1634 case AsmToken::Exclaim:
1635 case AsmToken::ExclaimEqual:
1636 case AsmToken::Percent:
1637 case AsmToken::Less:
1638 case AsmToken::LessEqual:
1639 case AsmToken::LessLess:
1640 case AsmToken::LessGreater:
1641 case AsmToken::Greater:
1642 case AsmToken::GreaterEqual:
1643 case AsmToken::GreaterGreater:
1648 /// ParseMacroArgument - Extract AsmTokens for a macro argument.
1649 /// This is used for both default macro parameter values and the
1650 /// arguments in macro invocations
1651 bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1652 AsmToken::TokenKind &ArgumentDelimiter) {
1653 unsigned ParenLevel = 0;
1654 unsigned AddTokens = 0;
1656 // gas accepts arguments separated by whitespace, except on Darwin
1658 Lexer.setSkipSpace(false);
1661 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1662 Lexer.setSkipSpace(true);
1663 return TokError("unexpected token in macro instantiation");
1666 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1667 // Spaces and commas cannot be mixed to delimit parameters
1668 if (ArgumentDelimiter == AsmToken::Eof)
1669 ArgumentDelimiter = AsmToken::Comma;
1670 else if (ArgumentDelimiter != AsmToken::Comma) {
1671 Lexer.setSkipSpace(true);
1672 return TokError("expected ' ' for macro argument separator");
1677 if (Lexer.is(AsmToken::Space)) {
1678 Lex(); // Eat spaces
1680 // Spaces can delimit parameters, but could also be part an expression.
1681 // If the token after a space is an operator, add the token and the next
1682 // one into this argument
1683 if (ArgumentDelimiter == AsmToken::Space ||
1684 ArgumentDelimiter == AsmToken::Eof) {
1685 if (IsOperator(Lexer.getKind())) {
1686 // Check to see whether the token is used as an operator,
1687 // or part of an identifier
1688 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1689 if (*NextChar == ' ')
1693 if (!AddTokens && ParenLevel == 0) {
1694 if (ArgumentDelimiter == AsmToken::Eof &&
1695 !IsOperator(Lexer.getKind()))
1696 ArgumentDelimiter = AsmToken::Space;
1702 // HandleMacroEntry relies on not advancing the lexer here
1703 // to be able to fill in the remaining default parameter values
1704 if (Lexer.is(AsmToken::EndOfStatement))
1707 // Adjust the current parentheses level.
1708 if (Lexer.is(AsmToken::LParen))
1710 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1713 // Append the token to the current argument list.
1714 MA.push_back(getTok());
1720 Lexer.setSkipSpace(true);
1721 if (ParenLevel != 0)
1722 return TokError("unbalanced parentheses in macro argument");
1726 // Parse the macro instantiation arguments.
1727 bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
1728 const unsigned NParameters = M ? M->Parameters.size() : 0;
1729 // Argument delimiter is initially unknown. It will be set by
1730 // ParseMacroArgument()
1731 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1733 // Parse two kinds of macro invocations:
1734 // - macros defined without any parameters accept an arbitrary number of them
1735 // - macros defined with parameters accept at most that many of them
1736 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1740 if (ParseMacroArgument(MA, ArgumentDelimiter))
1743 if (!MA.empty() || !NParameters)
1745 else if (NParameters) {
1746 if (!M->Parameters[Parameter].second.empty())
1747 A.push_back(M->Parameters[Parameter].second);
1750 // At the end of the statement, fill in remaining arguments that have
1751 // default values. If there aren't any, then the next argument is
1752 // required but missing
1753 if (Lexer.is(AsmToken::EndOfStatement)) {
1754 if (NParameters && Parameter < NParameters - 1) {
1755 if (M->Parameters[Parameter + 1].second.empty())
1756 return TokError("macro argument '" +
1757 Twine(M->Parameters[Parameter + 1].first) +
1765 if (Lexer.is(AsmToken::Comma))
1768 return TokError("Too many arguments");
1771 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1773 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1774 // this, although we should protect against infinite loops.
1775 if (ActiveMacros.size() == 20)
1776 return TokError("macros cannot be nested more than 20 levels deep");
1779 if (ParseMacroArguments(M, A))
1782 // Remove any trailing empty arguments. Do this after-the-fact as we have
1783 // to keep empty arguments in the middle of the list or positionality
1784 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1785 while (!A.empty() && A.back().empty())
1788 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1789 // to hold the macro body with substitutions.
1790 SmallString<256> Buf;
1791 StringRef Body = M->Body;
1792 raw_svector_ostream OS(Buf);
1794 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1797 // We include the .endmacro in the buffer as our queue to exit the macro
1799 OS << ".endmacro\n";
1801 MemoryBuffer *Instantiation =
1802 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1804 // Create the macro instantiation object and add to the current macro
1805 // instantiation stack.
1806 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1809 ActiveMacros.push_back(MI);
1811 // Jump to the macro instantiation and prime the lexer.
1812 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1813 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1819 void AsmParser::HandleMacroExit() {
1820 // Jump to the EndOfStatement we should return to, and consume it.
1821 JumpToLoc(ActiveMacros.back()->ExitLoc);
1824 // Pop the instantiation entry.
1825 delete ActiveMacros.back();
1826 ActiveMacros.pop_back();
1829 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1830 switch (Value->getKind()) {
1831 case MCExpr::Binary: {
1832 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1833 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1836 case MCExpr::Target:
1837 case MCExpr::Constant:
1839 case MCExpr::SymbolRef: {
1840 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1842 return IsUsedIn(Sym, S.getVariableValue());
1846 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1849 llvm_unreachable("Unknown expr kind!");
1852 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1854 // FIXME: Use better location, we should use proper tokens.
1855 SMLoc EqualLoc = Lexer.getLoc();
1857 const MCExpr *Value;
1858 if (ParseExpression(Value))
1861 // Note: we don't count b as used in "a = b". This is to allow
1865 if (Lexer.isNot(AsmToken::EndOfStatement))
1866 return TokError("unexpected token in assignment");
1868 // Error on assignment to '.'.
1870 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1871 "(use '.space' or '.org').)"));
1874 // Eat the end of statement marker.
1877 // Validate that the LHS is allowed to be a variable (either it has not been
1878 // used as a symbol, or it is an absolute symbol).
1879 MCSymbol *Sym = getContext().LookupSymbol(Name);
1881 // Diagnose assignment to a label.
1883 // FIXME: Diagnostics. Note the location of the definition as a label.
1884 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1885 if (IsUsedIn(Sym, Value))
1886 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1887 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1888 ; // Allow redefinitions of undefined symbols only used in directives.
1889 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1890 ; // Allow redefinitions of variables that haven't yet been used.
1891 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1892 return Error(EqualLoc, "redefinition of '" + Name + "'");
1893 else if (!Sym->isVariable())
1894 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1895 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1896 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1899 // Don't count these checks as uses.
1900 Sym->setUsed(false);
1902 Sym = getContext().GetOrCreateSymbol(Name);
1904 // FIXME: Handle '.'.
1906 // Do the assignment.
1907 Out.EmitAssignment(Sym, Value);
1909 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1915 /// ParseIdentifier:
1918 bool AsmParser::ParseIdentifier(StringRef &Res) {
1919 // The assembler has relaxed rules for accepting identifiers, in particular we
1920 // allow things like '.globl $foo', which would normally be separate
1921 // tokens. At this level, we have already lexed so we cannot (currently)
1922 // handle this as a context dependent token, instead we detect adjacent tokens
1923 // and return the combined identifier.
1924 if (Lexer.is(AsmToken::Dollar)) {
1925 SMLoc DollarLoc = getLexer().getLoc();
1927 // Consume the dollar sign, and check for a following identifier.
1929 if (Lexer.isNot(AsmToken::Identifier))
1932 // We have a '$' followed by an identifier, make sure they are adjacent.
1933 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1936 // Construct the joined identifier and consume the token.
1937 Res = StringRef(DollarLoc.getPointer(),
1938 getTok().getIdentifier().size() + 1);
1943 if (Lexer.isNot(AsmToken::Identifier) &&
1944 Lexer.isNot(AsmToken::String))
1947 Res = getTok().getIdentifier();
1949 Lex(); // Consume the identifier token.
1954 /// ParseDirectiveSet:
1955 /// ::= .equ identifier ',' expression
1956 /// ::= .equiv identifier ',' expression
1957 /// ::= .set identifier ',' expression
1958 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1961 if (ParseIdentifier(Name))
1962 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1964 if (getLexer().isNot(AsmToken::Comma))
1965 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1968 return ParseAssignment(Name, allow_redef, true);
1971 bool AsmParser::ParseEscapedString(std::string &Data) {
1972 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1975 StringRef Str = getTok().getStringContents();
1976 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1977 if (Str[i] != '\\') {
1982 // Recognize escaped characters. Note that this escape semantics currently
1983 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1986 return TokError("unexpected backslash at end of string");
1988 // Recognize octal sequences.
1989 if ((unsigned) (Str[i] - '0') <= 7) {
1990 // Consume up to three octal characters.
1991 unsigned Value = Str[i] - '0';
1993 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1995 Value = Value * 8 + (Str[i] - '0');
1997 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1999 Value = Value * 8 + (Str[i] - '0');
2004 return TokError("invalid octal escape sequence (out of range)");
2006 Data += (unsigned char) Value;
2010 // Otherwise recognize individual escapes.
2013 // Just reject invalid escape sequences for now.
2014 return TokError("invalid escape sequence (unrecognized character)");
2016 case 'b': Data += '\b'; break;
2017 case 'f': Data += '\f'; break;
2018 case 'n': Data += '\n'; break;
2019 case 'r': Data += '\r'; break;
2020 case 't': Data += '\t'; break;
2021 case '"': Data += '"'; break;
2022 case '\\': Data += '\\'; break;
2029 /// ParseDirectiveAscii:
2030 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2031 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2032 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2033 CheckForValidSection();
2036 if (getLexer().isNot(AsmToken::String))
2037 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2040 if (ParseEscapedString(Data))
2043 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2045 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2049 if (getLexer().is(AsmToken::EndOfStatement))
2052 if (getLexer().isNot(AsmToken::Comma))
2053 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2062 /// ParseDirectiveValue
2063 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2064 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2065 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2066 CheckForValidSection();
2069 const MCExpr *Value;
2070 SMLoc ExprLoc = getLexer().getLoc();
2071 if (ParseExpression(Value))
2074 // Special case constant expressions to match code generator.
2075 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2076 assert(Size <= 8 && "Invalid size");
2077 uint64_t IntValue = MCE->getValue();
2078 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2079 return Error(ExprLoc, "literal value out of range for directive");
2080 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2082 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2084 if (getLexer().is(AsmToken::EndOfStatement))
2087 // FIXME: Improve diagnostic.
2088 if (getLexer().isNot(AsmToken::Comma))
2089 return TokError("unexpected token in directive");
2098 /// ParseDirectiveRealValue
2099 /// ::= (.single | .double) [ expression (, expression)* ]
2100 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2101 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2102 CheckForValidSection();
2105 // We don't truly support arithmetic on floating point expressions, so we
2106 // have to manually parse unary prefixes.
2108 if (getLexer().is(AsmToken::Minus)) {
2111 } else if (getLexer().is(AsmToken::Plus))
2114 if (getLexer().isNot(AsmToken::Integer) &&
2115 getLexer().isNot(AsmToken::Real) &&
2116 getLexer().isNot(AsmToken::Identifier))
2117 return TokError("unexpected token in directive");
2119 // Convert to an APFloat.
2120 APFloat Value(Semantics);
2121 StringRef IDVal = getTok().getString();
2122 if (getLexer().is(AsmToken::Identifier)) {
2123 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2124 Value = APFloat::getInf(Semantics);
2125 else if (!IDVal.compare_lower("nan"))
2126 Value = APFloat::getNaN(Semantics, false, ~0);
2128 return TokError("invalid floating point literal");
2129 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2130 APFloat::opInvalidOp)
2131 return TokError("invalid floating point literal");
2135 // Consume the numeric token.
2138 // Emit the value as an integer.
2139 APInt AsInt = Value.bitcastToAPInt();
2140 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2141 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2143 if (getLexer().is(AsmToken::EndOfStatement))
2146 if (getLexer().isNot(AsmToken::Comma))
2147 return TokError("unexpected token in directive");
2156 /// ParseDirectiveSpace
2157 /// ::= .space expression [ , expression ]
2158 bool AsmParser::ParseDirectiveSpace() {
2159 CheckForValidSection();
2162 if (ParseAbsoluteExpression(NumBytes))
2165 int64_t FillExpr = 0;
2166 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2167 if (getLexer().isNot(AsmToken::Comma))
2168 return TokError("unexpected token in '.space' directive");
2171 if (ParseAbsoluteExpression(FillExpr))
2174 if (getLexer().isNot(AsmToken::EndOfStatement))
2175 return TokError("unexpected token in '.space' directive");
2181 return TokError("invalid number of bytes in '.space' directive");
2183 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
2184 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
2189 /// ParseDirectiveZero
2190 /// ::= .zero expression
2191 bool AsmParser::ParseDirectiveZero() {
2192 CheckForValidSection();
2195 if (ParseAbsoluteExpression(NumBytes))
2199 if (getLexer().is(AsmToken::Comma)) {
2201 if (ParseAbsoluteExpression(Val))
2205 if (getLexer().isNot(AsmToken::EndOfStatement))
2206 return TokError("unexpected token in '.zero' directive");
2210 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2215 /// ParseDirectiveFill
2216 /// ::= .fill expression , expression , expression
2217 bool AsmParser::ParseDirectiveFill() {
2218 CheckForValidSection();
2221 if (ParseAbsoluteExpression(NumValues))
2224 if (getLexer().isNot(AsmToken::Comma))
2225 return TokError("unexpected token in '.fill' directive");
2229 if (ParseAbsoluteExpression(FillSize))
2232 if (getLexer().isNot(AsmToken::Comma))
2233 return TokError("unexpected token in '.fill' directive");
2237 if (ParseAbsoluteExpression(FillExpr))
2240 if (getLexer().isNot(AsmToken::EndOfStatement))
2241 return TokError("unexpected token in '.fill' directive");
2245 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2246 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2248 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2249 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2254 /// ParseDirectiveOrg
2255 /// ::= .org expression [ , expression ]
2256 bool AsmParser::ParseDirectiveOrg() {
2257 CheckForValidSection();
2259 const MCExpr *Offset;
2260 SMLoc Loc = getTok().getLoc();
2261 if (ParseExpression(Offset))
2264 // Parse optional fill expression.
2265 int64_t FillExpr = 0;
2266 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2267 if (getLexer().isNot(AsmToken::Comma))
2268 return TokError("unexpected token in '.org' directive");
2271 if (ParseAbsoluteExpression(FillExpr))
2274 if (getLexer().isNot(AsmToken::EndOfStatement))
2275 return TokError("unexpected token in '.org' directive");
2280 // Only limited forms of relocatable expressions are accepted here, it
2281 // has to be relative to the current section. The streamer will return
2282 // 'true' if the expression wasn't evaluatable.
2283 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2284 return Error(Loc, "expected assembly-time absolute expression");
2289 /// ParseDirectiveAlign
2290 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2291 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2292 CheckForValidSection();
2294 SMLoc AlignmentLoc = getLexer().getLoc();
2296 if (ParseAbsoluteExpression(Alignment))
2300 bool HasFillExpr = false;
2301 int64_t FillExpr = 0;
2302 int64_t MaxBytesToFill = 0;
2303 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2304 if (getLexer().isNot(AsmToken::Comma))
2305 return TokError("unexpected token in directive");
2308 // The fill expression can be omitted while specifying a maximum number of
2309 // alignment bytes, e.g:
2311 if (getLexer().isNot(AsmToken::Comma)) {
2313 if (ParseAbsoluteExpression(FillExpr))
2317 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2318 if (getLexer().isNot(AsmToken::Comma))
2319 return TokError("unexpected token in directive");
2322 MaxBytesLoc = getLexer().getLoc();
2323 if (ParseAbsoluteExpression(MaxBytesToFill))
2326 if (getLexer().isNot(AsmToken::EndOfStatement))
2327 return TokError("unexpected token in directive");
2336 // Compute alignment in bytes.
2338 // FIXME: Diagnose overflow.
2339 if (Alignment >= 32) {
2340 Error(AlignmentLoc, "invalid alignment value");
2344 Alignment = 1ULL << Alignment;
2347 // Diagnose non-sensical max bytes to align.
2348 if (MaxBytesLoc.isValid()) {
2349 if (MaxBytesToFill < 1) {
2350 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2351 "many bytes, ignoring maximum bytes expression");
2355 if (MaxBytesToFill >= Alignment) {
2356 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2362 // Check whether we should use optimal code alignment for this .align
2364 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2365 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2366 ValueSize == 1 && UseCodeAlign) {
2367 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2369 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2370 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2377 /// ParseDirectiveSymbolAttribute
2378 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2379 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2380 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2383 SMLoc Loc = getTok().getLoc();
2385 if (ParseIdentifier(Name))
2386 return Error(Loc, "expected identifier in directive");
2388 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2390 // Assembler local symbols don't make any sense here. Complain loudly.
2391 if (Sym->isTemporary())
2392 return Error(Loc, "non-local symbol required in directive");
2394 getStreamer().EmitSymbolAttribute(Sym, Attr);
2396 if (getLexer().is(AsmToken::EndOfStatement))
2399 if (getLexer().isNot(AsmToken::Comma))
2400 return TokError("unexpected token in directive");
2409 /// ParseDirectiveComm
2410 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2411 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2412 CheckForValidSection();
2414 SMLoc IDLoc = getLexer().getLoc();
2416 if (ParseIdentifier(Name))
2417 return TokError("expected identifier in directive");
2419 // Handle the identifier as the key symbol.
2420 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2422 if (getLexer().isNot(AsmToken::Comma))
2423 return TokError("unexpected token in directive");
2427 SMLoc SizeLoc = getLexer().getLoc();
2428 if (ParseAbsoluteExpression(Size))
2431 int64_t Pow2Alignment = 0;
2432 SMLoc Pow2AlignmentLoc;
2433 if (getLexer().is(AsmToken::Comma)) {
2435 Pow2AlignmentLoc = getLexer().getLoc();
2436 if (ParseAbsoluteExpression(Pow2Alignment))
2439 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2440 if (IsLocal && LCOMM == LCOMM::NoAlignment)
2441 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2443 // If this target takes alignments in bytes (not log) validate and convert.
2444 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2445 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
2446 if (!isPowerOf2_64(Pow2Alignment))
2447 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2448 Pow2Alignment = Log2_64(Pow2Alignment);
2452 if (getLexer().isNot(AsmToken::EndOfStatement))
2453 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2457 // NOTE: a size of zero for a .comm should create a undefined symbol
2458 // but a size of .lcomm creates a bss symbol of size zero.
2460 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2461 "be less than zero");
2463 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2464 // may internally end up wanting an alignment in bytes.
2465 // FIXME: Diagnose overflow.
2466 if (Pow2Alignment < 0)
2467 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2468 "alignment, can't be less than zero");
2470 if (!Sym->isUndefined())
2471 return Error(IDLoc, "invalid symbol redefinition");
2473 // Create the Symbol as a common or local common with Size and Pow2Alignment
2475 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2479 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2483 /// ParseDirectiveAbort
2484 /// ::= .abort [... message ...]
2485 bool AsmParser::ParseDirectiveAbort() {
2486 // FIXME: Use loc from directive.
2487 SMLoc Loc = getLexer().getLoc();
2489 StringRef Str = ParseStringToEndOfStatement();
2490 if (getLexer().isNot(AsmToken::EndOfStatement))
2491 return TokError("unexpected token in '.abort' directive");
2496 Error(Loc, ".abort detected. Assembly stopping.");
2498 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2499 // FIXME: Actually abort assembly here.
2504 /// ParseDirectiveInclude
2505 /// ::= .include "filename"
2506 bool AsmParser::ParseDirectiveInclude() {
2507 if (getLexer().isNot(AsmToken::String))
2508 return TokError("expected string in '.include' directive");
2510 std::string Filename = getTok().getString();
2511 SMLoc IncludeLoc = getLexer().getLoc();
2514 if (getLexer().isNot(AsmToken::EndOfStatement))
2515 return TokError("unexpected token in '.include' directive");
2517 // Strip the quotes.
2518 Filename = Filename.substr(1, Filename.size()-2);
2520 // Attempt to switch the lexer to the included file before consuming the end
2521 // of statement to avoid losing it when we switch.
2522 if (EnterIncludeFile(Filename)) {
2523 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2530 /// ParseDirectiveIncbin
2531 /// ::= .incbin "filename"
2532 bool AsmParser::ParseDirectiveIncbin() {
2533 if (getLexer().isNot(AsmToken::String))
2534 return TokError("expected string in '.incbin' directive");
2536 std::string Filename = getTok().getString();
2537 SMLoc IncbinLoc = getLexer().getLoc();
2540 if (getLexer().isNot(AsmToken::EndOfStatement))
2541 return TokError("unexpected token in '.incbin' directive");
2543 // Strip the quotes.
2544 Filename = Filename.substr(1, Filename.size()-2);
2546 // Attempt to process the included file.
2547 if (ProcessIncbinFile(Filename)) {
2548 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2555 /// ParseDirectiveIf
2556 /// ::= .if expression
2557 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2558 TheCondStack.push_back(TheCondState);
2559 TheCondState.TheCond = AsmCond::IfCond;
2560 if (TheCondState.Ignore) {
2561 EatToEndOfStatement();
2564 if (ParseAbsoluteExpression(ExprValue))
2567 if (getLexer().isNot(AsmToken::EndOfStatement))
2568 return TokError("unexpected token in '.if' directive");
2572 TheCondState.CondMet = ExprValue;
2573 TheCondState.Ignore = !TheCondState.CondMet;
2579 /// ParseDirectiveIfb
2581 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2582 TheCondStack.push_back(TheCondState);
2583 TheCondState.TheCond = AsmCond::IfCond;
2585 if (TheCondState.Ignore) {
2586 EatToEndOfStatement();
2588 StringRef Str = ParseStringToEndOfStatement();
2590 if (getLexer().isNot(AsmToken::EndOfStatement))
2591 return TokError("unexpected token in '.ifb' directive");
2595 TheCondState.CondMet = ExpectBlank == Str.empty();
2596 TheCondState.Ignore = !TheCondState.CondMet;
2602 /// ParseDirectiveIfc
2603 /// ::= .ifc string1, string2
2604 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2605 TheCondStack.push_back(TheCondState);
2606 TheCondState.TheCond = AsmCond::IfCond;
2608 if (TheCondState.Ignore) {
2609 EatToEndOfStatement();
2611 StringRef Str1 = ParseStringToComma();
2613 if (getLexer().isNot(AsmToken::Comma))
2614 return TokError("unexpected token in '.ifc' directive");
2618 StringRef Str2 = ParseStringToEndOfStatement();
2620 if (getLexer().isNot(AsmToken::EndOfStatement))
2621 return TokError("unexpected token in '.ifc' directive");
2625 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2626 TheCondState.Ignore = !TheCondState.CondMet;
2632 /// ParseDirectiveIfdef
2633 /// ::= .ifdef symbol
2634 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2636 TheCondStack.push_back(TheCondState);
2637 TheCondState.TheCond = AsmCond::IfCond;
2639 if (TheCondState.Ignore) {
2640 EatToEndOfStatement();
2642 if (ParseIdentifier(Name))
2643 return TokError("expected identifier after '.ifdef'");
2647 MCSymbol *Sym = getContext().LookupSymbol(Name);
2650 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2652 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2653 TheCondState.Ignore = !TheCondState.CondMet;
2659 /// ParseDirectiveElseIf
2660 /// ::= .elseif expression
2661 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2662 if (TheCondState.TheCond != AsmCond::IfCond &&
2663 TheCondState.TheCond != AsmCond::ElseIfCond)
2664 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2666 TheCondState.TheCond = AsmCond::ElseIfCond;
2668 bool LastIgnoreState = false;
2669 if (!TheCondStack.empty())
2670 LastIgnoreState = TheCondStack.back().Ignore;
2671 if (LastIgnoreState || TheCondState.CondMet) {
2672 TheCondState.Ignore = true;
2673 EatToEndOfStatement();
2677 if (ParseAbsoluteExpression(ExprValue))
2680 if (getLexer().isNot(AsmToken::EndOfStatement))
2681 return TokError("unexpected token in '.elseif' directive");
2684 TheCondState.CondMet = ExprValue;
2685 TheCondState.Ignore = !TheCondState.CondMet;
2691 /// ParseDirectiveElse
2693 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2694 if (getLexer().isNot(AsmToken::EndOfStatement))
2695 return TokError("unexpected token in '.else' directive");
2699 if (TheCondState.TheCond != AsmCond::IfCond &&
2700 TheCondState.TheCond != AsmCond::ElseIfCond)
2701 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2703 TheCondState.TheCond = AsmCond::ElseCond;
2704 bool LastIgnoreState = false;
2705 if (!TheCondStack.empty())
2706 LastIgnoreState = TheCondStack.back().Ignore;
2707 if (LastIgnoreState || TheCondState.CondMet)
2708 TheCondState.Ignore = true;
2710 TheCondState.Ignore = false;
2715 /// ParseDirectiveEndIf
2717 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2718 if (getLexer().isNot(AsmToken::EndOfStatement))
2719 return TokError("unexpected token in '.endif' directive");
2723 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2724 TheCondStack.empty())
2725 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2727 if (!TheCondStack.empty()) {
2728 TheCondState = TheCondStack.back();
2729 TheCondStack.pop_back();
2735 /// ParseDirectiveFile
2736 /// ::= .file [number] filename
2737 /// ::= .file number directory filename
2738 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2739 // FIXME: I'm not sure what this is.
2740 int64_t FileNumber = -1;
2741 SMLoc FileNumberLoc = getLexer().getLoc();
2742 if (getLexer().is(AsmToken::Integer)) {
2743 FileNumber = getTok().getIntVal();
2747 return TokError("file number less than one");
2750 if (getLexer().isNot(AsmToken::String))
2751 return TokError("unexpected token in '.file' directive");
2753 // Usually the directory and filename together, otherwise just the directory.
2754 StringRef Path = getTok().getString();
2755 Path = Path.substr(1, Path.size()-2);
2758 StringRef Directory;
2760 if (getLexer().is(AsmToken::String)) {
2761 if (FileNumber == -1)
2762 return TokError("explicit path specified, but no file number");
2763 Filename = getTok().getString();
2764 Filename = Filename.substr(1, Filename.size()-2);
2771 if (getLexer().isNot(AsmToken::EndOfStatement))
2772 return TokError("unexpected token in '.file' directive");
2774 if (FileNumber == -1)
2775 getStreamer().EmitFileDirective(Filename);
2777 if (getContext().getGenDwarfForAssembly() == true)
2778 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2779 "used to generate dwarf debug info for assembly code");
2781 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2782 Error(FileNumberLoc, "file number already allocated");
2788 /// ParseDirectiveLine
2789 /// ::= .line [number]
2790 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2791 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2792 if (getLexer().isNot(AsmToken::Integer))
2793 return TokError("unexpected token in '.line' directive");
2795 int64_t LineNumber = getTok().getIntVal();
2799 // FIXME: Do something with the .line.
2802 if (getLexer().isNot(AsmToken::EndOfStatement))
2803 return TokError("unexpected token in '.line' directive");
2809 /// ParseDirectiveLoc
2810 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2811 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2812 /// The first number is a file number, must have been previously assigned with
2813 /// a .file directive, the second number is the line number and optionally the
2814 /// third number is a column position (zero if not specified). The remaining
2815 /// optional items are .loc sub-directives.
2816 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2818 if (getLexer().isNot(AsmToken::Integer))
2819 return TokError("unexpected token in '.loc' directive");
2820 int64_t FileNumber = getTok().getIntVal();
2822 return TokError("file number less than one in '.loc' directive");
2823 if (!getContext().isValidDwarfFileNumber(FileNumber))
2824 return TokError("unassigned file number in '.loc' directive");
2827 int64_t LineNumber = 0;
2828 if (getLexer().is(AsmToken::Integer)) {
2829 LineNumber = getTok().getIntVal();
2831 return TokError("line number less than one in '.loc' directive");
2835 int64_t ColumnPos = 0;
2836 if (getLexer().is(AsmToken::Integer)) {
2837 ColumnPos = getTok().getIntVal();
2839 return TokError("column position less than zero in '.loc' directive");
2843 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2845 int64_t Discriminator = 0;
2846 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2848 if (getLexer().is(AsmToken::EndOfStatement))
2852 SMLoc Loc = getTok().getLoc();
2853 if (getParser().ParseIdentifier(Name))
2854 return TokError("unexpected token in '.loc' directive");
2856 if (Name == "basic_block")
2857 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2858 else if (Name == "prologue_end")
2859 Flags |= DWARF2_FLAG_PROLOGUE_END;
2860 else if (Name == "epilogue_begin")
2861 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2862 else if (Name == "is_stmt") {
2863 SMLoc Loc = getTok().getLoc();
2864 const MCExpr *Value;
2865 if (getParser().ParseExpression(Value))
2867 // The expression must be the constant 0 or 1.
2868 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2869 int Value = MCE->getValue();
2871 Flags &= ~DWARF2_FLAG_IS_STMT;
2872 else if (Value == 1)
2873 Flags |= DWARF2_FLAG_IS_STMT;
2875 return Error(Loc, "is_stmt value not 0 or 1");
2878 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2881 else if (Name == "isa") {
2882 SMLoc Loc = getTok().getLoc();
2883 const MCExpr *Value;
2884 if (getParser().ParseExpression(Value))
2886 // The expression must be a constant greater or equal to 0.
2887 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2888 int Value = MCE->getValue();
2890 return Error(Loc, "isa number less than zero");
2894 return Error(Loc, "isa number not a constant value");
2897 else if (Name == "discriminator") {
2898 if (getParser().ParseAbsoluteExpression(Discriminator))
2902 return Error(Loc, "unknown sub-directive in '.loc' directive");
2905 if (getLexer().is(AsmToken::EndOfStatement))
2910 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2911 Isa, Discriminator, StringRef());
2916 /// ParseDirectiveStabs
2917 /// ::= .stabs string, number, number, number
2918 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2919 SMLoc DirectiveLoc) {
2920 return TokError("unsupported directive '" + Directive + "'");
2923 /// ParseDirectiveCFISections
2924 /// ::= .cfi_sections section [, section]
2925 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2926 SMLoc DirectiveLoc) {
2931 if (getParser().ParseIdentifier(Name))
2932 return TokError("Expected an identifier");
2934 if (Name == ".eh_frame")
2936 else if (Name == ".debug_frame")
2939 if (getLexer().is(AsmToken::Comma)) {
2942 if (getParser().ParseIdentifier(Name))
2943 return TokError("Expected an identifier");
2945 if (Name == ".eh_frame")
2947 else if (Name == ".debug_frame")
2951 getStreamer().EmitCFISections(EH, Debug);
2956 /// ParseDirectiveCFIStartProc
2957 /// ::= .cfi_startproc
2958 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2959 SMLoc DirectiveLoc) {
2960 getStreamer().EmitCFIStartProc();
2964 /// ParseDirectiveCFIEndProc
2965 /// ::= .cfi_endproc
2966 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2967 getStreamer().EmitCFIEndProc();
2971 /// ParseRegisterOrRegisterNumber - parse register name or number.
2972 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2973 SMLoc DirectiveLoc) {
2976 if (getLexer().isNot(AsmToken::Integer)) {
2977 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2980 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2982 return getParser().ParseAbsoluteExpression(Register);
2987 /// ParseDirectiveCFIDefCfa
2988 /// ::= .cfi_def_cfa register, offset
2989 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2990 SMLoc DirectiveLoc) {
2991 int64_t Register = 0;
2992 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2995 if (getLexer().isNot(AsmToken::Comma))
2996 return TokError("unexpected token in directive");
3000 if (getParser().ParseAbsoluteExpression(Offset))
3003 getStreamer().EmitCFIDefCfa(Register, Offset);
3007 /// ParseDirectiveCFIDefCfaOffset
3008 /// ::= .cfi_def_cfa_offset offset
3009 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3010 SMLoc DirectiveLoc) {
3012 if (getParser().ParseAbsoluteExpression(Offset))
3015 getStreamer().EmitCFIDefCfaOffset(Offset);
3019 /// ParseDirectiveCFIAdjustCfaOffset
3020 /// ::= .cfi_adjust_cfa_offset adjustment
3021 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3022 SMLoc DirectiveLoc) {
3023 int64_t Adjustment = 0;
3024 if (getParser().ParseAbsoluteExpression(Adjustment))
3027 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3031 /// ParseDirectiveCFIDefCfaRegister
3032 /// ::= .cfi_def_cfa_register register
3033 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3034 SMLoc DirectiveLoc) {
3035 int64_t Register = 0;
3036 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3039 getStreamer().EmitCFIDefCfaRegister(Register);
3043 /// ParseDirectiveCFIOffset
3044 /// ::= .cfi_offset register, offset
3045 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3046 int64_t Register = 0;
3049 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3052 if (getLexer().isNot(AsmToken::Comma))
3053 return TokError("unexpected token in directive");
3056 if (getParser().ParseAbsoluteExpression(Offset))
3059 getStreamer().EmitCFIOffset(Register, Offset);
3063 /// ParseDirectiveCFIRelOffset
3064 /// ::= .cfi_rel_offset register, offset
3065 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3066 SMLoc DirectiveLoc) {
3067 int64_t Register = 0;
3069 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3072 if (getLexer().isNot(AsmToken::Comma))
3073 return TokError("unexpected token in directive");
3077 if (getParser().ParseAbsoluteExpression(Offset))
3080 getStreamer().EmitCFIRelOffset(Register, Offset);
3084 static bool isValidEncoding(int64_t Encoding) {
3085 if (Encoding & ~0xff)
3088 if (Encoding == dwarf::DW_EH_PE_omit)
3091 const unsigned Format = Encoding & 0xf;
3092 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3093 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3094 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3095 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3098 const unsigned Application = Encoding & 0x70;
3099 if (Application != dwarf::DW_EH_PE_absptr &&
3100 Application != dwarf::DW_EH_PE_pcrel)
3106 /// ParseDirectiveCFIPersonalityOrLsda
3107 /// ::= .cfi_personality encoding, [symbol_name]
3108 /// ::= .cfi_lsda encoding, [symbol_name]
3109 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
3110 SMLoc DirectiveLoc) {
3111 int64_t Encoding = 0;
3112 if (getParser().ParseAbsoluteExpression(Encoding))
3114 if (Encoding == dwarf::DW_EH_PE_omit)
3117 if (!isValidEncoding(Encoding))
3118 return TokError("unsupported encoding.");
3120 if (getLexer().isNot(AsmToken::Comma))
3121 return TokError("unexpected token in directive");
3125 if (getParser().ParseIdentifier(Name))
3126 return TokError("expected identifier in directive");
3128 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3130 if (IDVal == ".cfi_personality")
3131 getStreamer().EmitCFIPersonality(Sym, Encoding);
3133 assert(IDVal == ".cfi_lsda");
3134 getStreamer().EmitCFILsda(Sym, Encoding);
3139 /// ParseDirectiveCFIRememberState
3140 /// ::= .cfi_remember_state
3141 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3142 SMLoc DirectiveLoc) {
3143 getStreamer().EmitCFIRememberState();
3147 /// ParseDirectiveCFIRestoreState
3148 /// ::= .cfi_remember_state
3149 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3150 SMLoc DirectiveLoc) {
3151 getStreamer().EmitCFIRestoreState();
3155 /// ParseDirectiveCFISameValue
3156 /// ::= .cfi_same_value register
3157 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3158 SMLoc DirectiveLoc) {
3159 int64_t Register = 0;
3161 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3164 getStreamer().EmitCFISameValue(Register);
3169 /// ParseDirectiveCFIRestore
3170 /// ::= .cfi_restore register
3171 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
3172 SMLoc DirectiveLoc) {
3173 int64_t Register = 0;
3174 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3177 getStreamer().EmitCFIRestore(Register);
3182 /// ParseDirectiveCFIEscape
3183 /// ::= .cfi_escape expression[,...]
3184 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3185 SMLoc DirectiveLoc) {
3188 if (getParser().ParseAbsoluteExpression(CurrValue))
3191 Values.push_back((uint8_t)CurrValue);
3193 while (getLexer().is(AsmToken::Comma)) {
3196 if (getParser().ParseAbsoluteExpression(CurrValue))
3199 Values.push_back((uint8_t)CurrValue);
3202 getStreamer().EmitCFIEscape(Values);
3206 /// ParseDirectiveCFISignalFrame
3207 /// ::= .cfi_signal_frame
3208 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3209 SMLoc DirectiveLoc) {
3210 if (getLexer().isNot(AsmToken::EndOfStatement))
3211 return Error(getLexer().getLoc(),
3212 "unexpected token in '" + Directive + "' directive");
3214 getStreamer().EmitCFISignalFrame();
3219 /// ParseDirectiveMacrosOnOff
3222 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3223 SMLoc DirectiveLoc) {
3224 if (getLexer().isNot(AsmToken::EndOfStatement))
3225 return Error(getLexer().getLoc(),
3226 "unexpected token in '" + Directive + "' directive");
3228 getParser().MacrosEnabled = Directive == ".macros_on";
3233 /// ParseDirectiveMacro
3234 /// ::= .macro name [parameters]
3235 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3236 SMLoc DirectiveLoc) {
3238 if (getParser().ParseIdentifier(Name))
3239 return TokError("expected identifier in '.macro' directive");
3241 MacroParameters Parameters;
3242 // Argument delimiter is initially unknown. It will be set by
3243 // ParseMacroArgument()
3244 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3245 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3247 MacroParameter Parameter;
3248 if (getParser().ParseIdentifier(Parameter.first))
3249 return TokError("expected identifier in '.macro' directive");
3251 if (getLexer().is(AsmToken::Equal)) {
3253 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3257 Parameters.push_back(Parameter);
3259 if (getLexer().is(AsmToken::Comma))
3261 else if (getLexer().is(AsmToken::EndOfStatement))
3266 // Eat the end of statement.
3269 AsmToken EndToken, StartToken = getTok();
3271 // Lex the macro definition.
3273 // Check whether we have reached the end of the file.
3274 if (getLexer().is(AsmToken::Eof))
3275 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3277 // Otherwise, check whether we have reach the .endmacro.
3278 if (getLexer().is(AsmToken::Identifier) &&
3279 (getTok().getIdentifier() == ".endm" ||
3280 getTok().getIdentifier() == ".endmacro")) {
3281 EndToken = getTok();
3283 if (getLexer().isNot(AsmToken::EndOfStatement))
3284 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3289 // Otherwise, scan til the end of the statement.
3290 getParser().EatToEndOfStatement();
3293 if (getParser().MacroMap.lookup(Name)) {
3294 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3297 const char *BodyStart = StartToken.getLoc().getPointer();
3298 const char *BodyEnd = EndToken.getLoc().getPointer();
3299 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3300 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3304 /// ParseDirectiveEndMacro
3307 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3308 SMLoc DirectiveLoc) {
3309 if (getLexer().isNot(AsmToken::EndOfStatement))
3310 return TokError("unexpected token in '" + Directive + "' directive");
3312 // If we are inside a macro instantiation, terminate the current
3314 if (!getParser().ActiveMacros.empty()) {
3315 getParser().HandleMacroExit();
3319 // Otherwise, this .endmacro is a stray entry in the file; well formed
3320 // .endmacro directives are handled during the macro definition parsing.
3321 return TokError("unexpected '" + Directive + "' in file, "
3322 "no current macro definition");
3325 /// ParseDirectivePurgeMacro
3327 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3328 SMLoc DirectiveLoc) {
3330 if (getParser().ParseIdentifier(Name))
3331 return TokError("expected identifier in '.purgem' directive");
3333 if (getLexer().isNot(AsmToken::EndOfStatement))
3334 return TokError("unexpected token in '.purgem' directive");
3336 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3337 if (I == getParser().MacroMap.end())
3338 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3340 // Undefine the macro.
3341 delete I->getValue();
3342 getParser().MacroMap.erase(I);
3346 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3347 getParser().CheckForValidSection();
3349 const MCExpr *Value;
3351 if (getParser().ParseExpression(Value))
3354 if (getLexer().isNot(AsmToken::EndOfStatement))
3355 return TokError("unexpected token in directive");
3357 if (DirName[1] == 's')
3358 getStreamer().EmitSLEB128Value(Value);
3360 getStreamer().EmitULEB128Value(Value);
3365 Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3366 AsmToken EndToken, StartToken = getTok();
3368 unsigned NestLevel = 0;
3370 // Check whether we have reached the end of the file.
3371 if (getLexer().is(AsmToken::Eof)) {
3372 Error(DirectiveLoc, "no matching '.endr' in definition");
3376 if (Lexer.is(AsmToken::Identifier) &&
3377 (getTok().getIdentifier() == ".rept")) {
3381 // Otherwise, check whether we have reached the .endr.
3382 if (Lexer.is(AsmToken::Identifier) &&
3383 getTok().getIdentifier() == ".endr") {
3384 if (NestLevel == 0) {
3385 EndToken = getTok();
3387 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3388 TokError("unexpected token in '.endr' directive");
3396 // Otherwise, scan till the end of the statement.
3397 EatToEndOfStatement();
3400 const char *BodyStart = StartToken.getLoc().getPointer();
3401 const char *BodyEnd = EndToken.getLoc().getPointer();
3402 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3404 // We Are Anonymous.
3406 MacroParameters Parameters;
3407 return new Macro(Name, Body, Parameters);
3410 void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3411 raw_svector_ostream &OS) {
3414 MemoryBuffer *Instantiation =
3415 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3417 // Create the macro instantiation object and add to the current macro
3418 // instantiation stack.
3419 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3422 ActiveMacros.push_back(MI);
3424 // Jump to the macro instantiation and prime the lexer.
3425 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3426 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3430 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3432 if (ParseAbsoluteExpression(Count))
3433 return TokError("unexpected token in '.rept' directive");
3436 return TokError("Count is negative");
3438 if (Lexer.isNot(AsmToken::EndOfStatement))
3439 return TokError("unexpected token in '.rept' directive");
3441 // Eat the end of statement.
3444 // Lex the rept definition.
3445 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3449 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3450 // to hold the macro body with substitutions.
3451 SmallString<256> Buf;
3452 MacroParameters Parameters;
3454 raw_svector_ostream OS(Buf);
3456 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3459 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3464 /// ParseDirectiveIrp
3465 /// ::= .irp symbol,values
3466 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3467 MacroParameters Parameters;
3468 MacroParameter Parameter;
3470 if (ParseIdentifier(Parameter.first))
3471 return TokError("expected identifier in '.irp' directive");
3473 Parameters.push_back(Parameter);
3475 if (Lexer.isNot(AsmToken::Comma))
3476 return TokError("expected comma in '.irp' directive");
3481 if (ParseMacroArguments(0, A))
3484 // Eat the end of statement.
3487 // Lex the irp definition.
3488 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3492 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3493 // to hold the macro body with substitutions.
3494 SmallString<256> Buf;
3495 raw_svector_ostream OS(Buf);
3497 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3498 MacroArguments Args;
3501 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3505 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3510 /// ParseDirectiveIrpc
3511 /// ::= .irpc symbol,values
3512 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3513 MacroParameters Parameters;
3514 MacroParameter Parameter;
3516 if (ParseIdentifier(Parameter.first))
3517 return TokError("expected identifier in '.irpc' directive");
3519 Parameters.push_back(Parameter);
3521 if (Lexer.isNot(AsmToken::Comma))
3522 return TokError("expected comma in '.irpc' directive");
3527 if (ParseMacroArguments(0, A))
3530 if (A.size() != 1 || A.front().size() != 1)
3531 return TokError("unexpected token in '.irpc' directive");
3533 // Eat the end of statement.
3536 // Lex the irpc definition.
3537 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3541 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3542 // to hold the macro body with substitutions.
3543 SmallString<256> Buf;
3544 raw_svector_ostream OS(Buf);
3546 StringRef Values = A.front().front().getString();
3547 std::size_t I, End = Values.size();
3548 for (I = 0; I < End; ++I) {
3550 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3552 MacroArguments Args;
3553 Args.push_back(Arg);
3555 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3559 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3564 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3565 if (ActiveMacros.empty())
3566 return TokError("unmatched '.endr' directive");
3568 // The only .repl that should get here are the ones created by
3569 // InstantiateMacroLikeBody.
3570 assert(getLexer().is(AsmToken::EndOfStatement));
3577 enum AsmOpRewriteKind {
3583 struct AsmOpRewrite {
3584 AsmOpRewriteKind Kind;
3589 AsmOpRewrite(AsmOpRewriteKind kind, SMLoc loc, unsigned len)
3590 : Kind(kind), Loc(loc), Len(len) { }
3594 bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3595 unsigned &NumOutputs, unsigned &NumInputs,
3596 SmallVectorImpl<void *> &OpDecls,
3597 SmallVectorImpl<std::string> &Constraints,
3598 SmallVectorImpl<std::string> &Clobbers,
3599 const MCInstrInfo *MII,
3600 const MCInstPrinter *IP,
3601 MCAsmParserSemaCallback &SI) {
3602 SmallVector<void*, 4> InputDecls;
3603 SmallVector<void*, 4> OutputDecls;
3604 SmallVector<std::string, 4> InputConstraints;
3605 SmallVector<std::string, 4> OutputConstraints;
3606 std::set<std::string> ClobberRegs;
3608 SmallVector<struct AsmOpRewrite, 4> AsmStrRewrites;
3613 // While we have input, parse each statement.
3614 unsigned InputIdx = 0;
3615 unsigned OutputIdx = 0;
3616 while (getLexer().isNot(AsmToken::Eof)) {
3617 if (ParseStatement()) return true;
3619 if (isInstruction()) {
3620 const MCInstrDesc &Desc = MII->get(getOpcode());
3622 // Build the list of clobbers, outputs and inputs.
3623 for (unsigned i = 1, e = ParsedOperands.size(); i != e; ++i) {
3624 MCParsedAsmOperand *Operand = ParsedOperands[i];
3627 if (Operand->isImm()) {
3628 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Imm,
3629 Operand->getStartLoc(),
3630 Operand->getNameLen()));
3634 // Register operand.
3635 if (Operand->isReg()) {
3636 unsigned NumDefs = Desc.getNumDefs();
3638 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3640 raw_string_ostream OS(Reg);
3641 IP->printRegName(OS, Operand->getReg());
3642 ClobberRegs.insert(StringRef(OS.str()));
3647 // Expr/Input or Output.
3649 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3652 bool isOutput = (i == 1) && Desc.mayStore();
3654 std::string Constraint = "=";
3656 OutputDecls.push_back(OpDecl);
3657 Constraint += Operand->getConstraint().str();
3658 OutputConstraints.push_back(Constraint);
3659 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Output,
3660 Operand->getStartLoc(),
3661 Operand->getNameLen()));
3663 InputDecls.push_back(OpDecl);
3664 InputConstraints.push_back(Operand->getConstraint().str());
3665 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Input,
3666 Operand->getStartLoc(),
3667 Operand->getNameLen()));
3671 // Free any parsed operands.
3672 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
3673 delete ParsedOperands[i];
3674 ParsedOperands.clear();
3678 // Set the number of Outputs and Inputs.
3679 NumOutputs = OutputDecls.size();
3680 NumInputs = InputDecls.size();
3682 // Set the unique clobbers.
3683 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3684 E = ClobberRegs.end(); I != E; ++I)
3685 Clobbers.push_back(*I);
3687 // Merge the various outputs and inputs. Output are expected first.
3688 if (NumOutputs || NumInputs) {
3689 unsigned NumExprs = NumOutputs + NumInputs;
3690 OpDecls.resize(NumExprs);
3691 Constraints.resize(NumExprs);
3692 for (unsigned i = 0; i < NumOutputs; ++i) {
3693 OpDecls[i] = OutputDecls[i];
3694 Constraints[i] = OutputConstraints[i];
3696 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
3697 OpDecls[j] = InputDecls[i];
3698 Constraints[j] = InputConstraints[i];
3702 // Build the IR assembly string.
3703 std::string AsmStringIR;
3704 raw_string_ostream OS(AsmStringIR);
3705 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
3706 for (SmallVectorImpl<struct AsmOpRewrite>::iterator
3707 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3708 const char *Loc = (*I).Loc.getPointer();
3710 // Emit everything up to the immediate/expression.
3711 OS << StringRef(Start, Loc - Start);
3713 // Rewrite expressions in $N notation.
3714 switch ((*I).Kind) {
3716 OS << Twine("$$") + StringRef(Loc, (*I).Len);
3728 // Skip the original expression.
3729 Start = Loc + (*I).Len;
3732 // Emit the remainder of the asm string.
3733 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3734 if (Start != AsmEnd)
3735 OS << StringRef(Start, AsmEnd - Start);
3737 AsmString = OS.str();
3741 /// \brief Create an MCAsmParser instance.
3742 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3743 MCContext &C, MCStreamer &Out,
3744 const MCAsmInfo &MAI) {
3745 return new AsmParser(SM, C, Out, MAI);