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; }
322 void setOpcode(unsigned Value) { Opcode = Value; }
325 /// \brief Generic implementations of directive handling, etc. which is shared
326 /// (or the default, at least) for all assembler parser.
327 class GenericAsmParser : public MCAsmParserExtension {
328 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
329 void AddDirectiveHandler(StringRef Directive) {
330 getParser().AddDirectiveHandler(this, Directive,
331 HandleDirective<GenericAsmParser, Handler>);
334 GenericAsmParser() {}
336 AsmParser &getParser() {
337 return (AsmParser&) this->MCAsmParserExtension::getParser();
340 virtual void Initialize(MCAsmParser &Parser) {
341 // Call the base implementation.
342 this->MCAsmParserExtension::Initialize(Parser);
344 // Debugging directives.
345 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
346 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
347 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
348 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
351 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
353 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
355 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
357 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
359 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
360 ".cfi_def_cfa_offset");
361 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
362 ".cfi_adjust_cfa_offset");
363 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
364 ".cfi_def_cfa_register");
365 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
367 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
370 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
372 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
374 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
376 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
378 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
380 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
382 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
384 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
387 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
389 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
391 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
392 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
393 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
394 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
396 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
397 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
400 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
402 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
403 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
404 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
405 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
406 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
407 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
408 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
409 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
410 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
411 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
412 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
413 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
414 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
415 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
416 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
417 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
418 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
419 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
420 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
421 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
423 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
424 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
425 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
426 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
428 bool ParseDirectiveLEB128(StringRef, SMLoc);
435 extern MCAsmParserExtension *createDarwinAsmParser();
436 extern MCAsmParserExtension *createELFAsmParser();
437 extern MCAsmParserExtension *createCOFFAsmParser();
441 enum { DEFAULT_ADDRSPACE = 0 };
443 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
444 MCStreamer &_Out, const MCAsmInfo &_MAI)
445 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
446 GenericParser(new GenericAsmParser), PlatformParser(0),
447 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
448 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false),
450 // Save the old handler.
451 SavedDiagHandler = SrcMgr.getDiagHandler();
452 SavedDiagContext = SrcMgr.getDiagContext();
453 // Set our own handler which calls the saved handler.
454 SrcMgr.setDiagHandler(DiagHandler, this);
455 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
457 // Initialize the generic parser.
458 GenericParser->Initialize(*this);
460 // Initialize the platform / file format parser.
462 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
464 if (_MAI.hasMicrosoftFastStdCallMangling()) {
465 PlatformParser = createCOFFAsmParser();
466 PlatformParser->Initialize(*this);
467 } else if (_MAI.hasSubsectionsViaSymbols()) {
468 PlatformParser = createDarwinAsmParser();
469 PlatformParser->Initialize(*this);
472 PlatformParser = createELFAsmParser();
473 PlatformParser->Initialize(*this);
477 AsmParser::~AsmParser() {
478 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
480 // Destroy any macros.
481 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
482 ie = MacroMap.end(); it != ie; ++it)
483 delete it->getValue();
485 delete PlatformParser;
486 delete GenericParser;
489 void AsmParser::PrintMacroInstantiations() {
490 // Print the active macro instantiation stack.
491 for (std::vector<MacroInstantiation*>::const_reverse_iterator
492 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
493 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
494 "while in macro instantiation");
497 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
498 if (FatalAssemblerWarnings)
499 return Error(L, Msg, Ranges);
500 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
501 PrintMacroInstantiations();
505 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
507 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
508 PrintMacroInstantiations();
512 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
513 std::string IncludedFile;
514 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
520 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
525 /// Process the specified .incbin file by seaching for it in the include paths
526 /// then just emitting the byte contents of the file to the streamer. This
527 /// returns true on failure.
528 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
529 std::string IncludedFile;
530 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
534 // Pick up the bytes from the file and emit them.
535 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
540 void AsmParser::JumpToLoc(SMLoc Loc) {
541 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
542 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
545 const AsmToken &AsmParser::Lex() {
546 const AsmToken *tok = &Lexer.Lex();
548 if (tok->is(AsmToken::Eof)) {
549 // If this is the end of an included file, pop the parent file off the
551 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
552 if (ParentIncludeLoc != SMLoc()) {
553 JumpToLoc(ParentIncludeLoc);
558 if (tok->is(AsmToken::Error))
559 Error(Lexer.getErrLoc(), Lexer.getErr());
564 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
565 // Create the initial section, if requested.
566 if (!NoInitialTextSection)
573 AsmCond StartingCondState = TheCondState;
575 // If we are generating dwarf for assembly source files save the initial text
576 // section and generate a .file directive.
577 if (getContext().getGenDwarfForAssembly()) {
578 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
579 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
580 getStreamer().EmitLabel(SectionStartSym);
581 getContext().setGenDwarfSectionStartSym(SectionStartSym);
582 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
583 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
586 // While we have input, parse each statement.
587 while (Lexer.isNot(AsmToken::Eof)) {
588 if (!ParseStatement()) continue;
590 // We had an error, validate that one was emitted and recover by skipping to
592 assert(HadError && "Parse statement returned an error, but none emitted!");
593 EatToEndOfStatement();
596 if (TheCondState.TheCond != StartingCondState.TheCond ||
597 TheCondState.Ignore != StartingCondState.Ignore)
598 return TokError("unmatched .ifs or .elses");
600 // Check to see there are no empty DwarfFile slots.
601 const std::vector<MCDwarfFile *> &MCDwarfFiles =
602 getContext().getMCDwarfFiles();
603 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
604 if (!MCDwarfFiles[i])
605 TokError("unassigned file number: " + Twine(i) + " for .file directives");
608 // Check to see that all assembler local symbols were actually defined.
609 // Targets that don't do subsections via symbols may not want this, though,
610 // so conservatively exclude them. Only do this if we're finalizing, though,
611 // as otherwise we won't necessarilly have seen everything yet.
612 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
613 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
614 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
617 MCSymbol *Sym = i->getValue();
618 // Variable symbols may not be marked as defined, so check those
619 // explicitly. If we know it's a variable, we have a definition for
620 // the purposes of this check.
621 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
622 // FIXME: We would really like to refer back to where the symbol was
623 // first referenced for a source location. We need to add something
624 // to track that. Currently, we just point to the end of the file.
625 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
626 "assembler local symbol '" + Sym->getName() +
632 // Finalize the output stream if there are no errors and if the client wants
634 if (!HadError && !NoFinalize)
640 void AsmParser::CheckForValidSection() {
641 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
642 TokError("expected section directive before assembly directive");
643 Out.SwitchSection(Ctx.getMachOSection(
645 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
646 0, SectionKind::getText()));
650 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
651 void AsmParser::EatToEndOfStatement() {
652 while (Lexer.isNot(AsmToken::EndOfStatement) &&
653 Lexer.isNot(AsmToken::Eof))
657 if (Lexer.is(AsmToken::EndOfStatement))
661 StringRef AsmParser::ParseStringToEndOfStatement() {
662 const char *Start = getTok().getLoc().getPointer();
664 while (Lexer.isNot(AsmToken::EndOfStatement) &&
665 Lexer.isNot(AsmToken::Eof))
668 const char *End = getTok().getLoc().getPointer();
669 return StringRef(Start, End - Start);
672 StringRef AsmParser::ParseStringToComma() {
673 const char *Start = getTok().getLoc().getPointer();
675 while (Lexer.isNot(AsmToken::EndOfStatement) &&
676 Lexer.isNot(AsmToken::Comma) &&
677 Lexer.isNot(AsmToken::Eof))
680 const char *End = getTok().getLoc().getPointer();
681 return StringRef(Start, End - Start);
684 /// ParseParenExpr - Parse a paren expression and return it.
685 /// NOTE: This assumes the leading '(' has already been consumed.
687 /// parenexpr ::= expr)
689 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
690 if (ParseExpression(Res)) return true;
691 if (Lexer.isNot(AsmToken::RParen))
692 return TokError("expected ')' in parentheses expression");
693 EndLoc = Lexer.getLoc();
698 /// ParseBracketExpr - Parse a bracket expression and return it.
699 /// NOTE: This assumes the leading '[' has already been consumed.
701 /// bracketexpr ::= expr]
703 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
704 if (ParseExpression(Res)) return true;
705 if (Lexer.isNot(AsmToken::RBrac))
706 return TokError("expected ']' in brackets expression");
707 EndLoc = Lexer.getLoc();
712 /// ParsePrimaryExpr - Parse a primary expression and return it.
713 /// primaryexpr ::= (parenexpr
714 /// primaryexpr ::= symbol
715 /// primaryexpr ::= number
716 /// primaryexpr ::= '.'
717 /// primaryexpr ::= ~,+,- primaryexpr
718 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
719 switch (Lexer.getKind()) {
721 return TokError("unknown token in expression");
722 // If we have an error assume that we've already handled it.
723 case AsmToken::Error:
725 case AsmToken::Exclaim:
726 Lex(); // Eat the operator.
727 if (ParsePrimaryExpr(Res, EndLoc))
729 Res = MCUnaryExpr::CreateLNot(Res, getContext());
731 case AsmToken::Dollar:
732 case AsmToken::String:
733 case AsmToken::Identifier: {
734 EndLoc = Lexer.getLoc();
736 StringRef Identifier;
737 if (ParseIdentifier(Identifier))
740 // This is a symbol reference.
741 std::pair<StringRef, StringRef> Split = Identifier.split('@');
742 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
744 // Lookup the symbol variant if used.
745 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
746 if (Split.first.size() != Identifier.size()) {
747 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
748 if (Variant == MCSymbolRefExpr::VK_Invalid) {
749 Variant = MCSymbolRefExpr::VK_None;
750 return TokError("invalid variant '" + Split.second + "'");
754 // If this is an absolute variable reference, substitute it now to preserve
755 // semantics in the face of reassignment.
756 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
758 return Error(EndLoc, "unexpected modifier on variable reference");
760 Res = Sym->getVariableValue();
764 // Otherwise create a symbol ref.
765 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
768 case AsmToken::Integer: {
769 SMLoc Loc = getTok().getLoc();
770 int64_t IntVal = getTok().getIntVal();
771 Res = MCConstantExpr::Create(IntVal, getContext());
772 EndLoc = Lexer.getLoc();
774 // Look for 'b' or 'f' following an Integer as a directional label
775 if (Lexer.getKind() == AsmToken::Identifier) {
776 StringRef IDVal = getTok().getString();
777 if (IDVal == "f" || IDVal == "b"){
778 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
779 IDVal == "f" ? 1 : 0);
780 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
782 if (IDVal == "b" && Sym->isUndefined())
783 return Error(Loc, "invalid reference to undefined symbol");
784 EndLoc = Lexer.getLoc();
785 Lex(); // Eat identifier.
790 case AsmToken::Real: {
791 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
792 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
793 Res = MCConstantExpr::Create(IntVal, getContext());
797 case AsmToken::Dot: {
798 // This is a '.' reference, which references the current PC. Emit a
799 // temporary label to the streamer and refer to it.
800 MCSymbol *Sym = Ctx.CreateTempSymbol();
802 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
803 EndLoc = Lexer.getLoc();
804 Lex(); // Eat identifier.
807 case AsmToken::LParen:
808 Lex(); // Eat the '('.
809 return ParseParenExpr(Res, EndLoc);
810 case AsmToken::LBrac:
811 if (!PlatformParser->HasBracketExpressions())
812 return TokError("brackets expression not supported on this target");
813 Lex(); // Eat the '['.
814 return ParseBracketExpr(Res, EndLoc);
815 case AsmToken::Minus:
816 Lex(); // Eat the operator.
817 if (ParsePrimaryExpr(Res, EndLoc))
819 Res = MCUnaryExpr::CreateMinus(Res, getContext());
822 Lex(); // Eat the operator.
823 if (ParsePrimaryExpr(Res, EndLoc))
825 Res = MCUnaryExpr::CreatePlus(Res, getContext());
827 case AsmToken::Tilde:
828 Lex(); // Eat the operator.
829 if (ParsePrimaryExpr(Res, EndLoc))
831 Res = MCUnaryExpr::CreateNot(Res, getContext());
836 bool AsmParser::ParseExpression(const MCExpr *&Res) {
838 return ParseExpression(Res, EndLoc);
842 AsmParser::ApplyModifierToExpr(const MCExpr *E,
843 MCSymbolRefExpr::VariantKind Variant) {
844 // Recurse over the given expression, rebuilding it to apply the given variant
845 // if there is exactly one symbol.
846 switch (E->getKind()) {
848 case MCExpr::Constant:
851 case MCExpr::SymbolRef: {
852 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
854 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
855 TokError("invalid variant on expression '" +
856 getTok().getIdentifier() + "' (already modified)");
860 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
863 case MCExpr::Unary: {
864 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
865 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
868 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
871 case MCExpr::Binary: {
872 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
873 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
874 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
879 if (!LHS) LHS = BE->getLHS();
880 if (!RHS) RHS = BE->getRHS();
882 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
886 llvm_unreachable("Invalid expression kind!");
889 /// ParseExpression - Parse an expression and return it.
891 /// expr ::= expr &&,|| expr -> lowest.
892 /// expr ::= expr |,^,&,! expr
893 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
894 /// expr ::= expr <<,>> expr
895 /// expr ::= expr +,- expr
896 /// expr ::= expr *,/,% expr -> highest.
897 /// expr ::= primaryexpr
899 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
900 // Parse the expression.
902 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
905 // As a special case, we support 'a op b @ modifier' by rewriting the
906 // expression to include the modifier. This is inefficient, but in general we
907 // expect users to use 'a@modifier op b'.
908 if (Lexer.getKind() == AsmToken::At) {
911 if (Lexer.isNot(AsmToken::Identifier))
912 return TokError("unexpected symbol modifier following '@'");
914 MCSymbolRefExpr::VariantKind Variant =
915 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
916 if (Variant == MCSymbolRefExpr::VK_Invalid)
917 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
919 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
921 return TokError("invalid modifier '" + getTok().getIdentifier() +
922 "' (no symbols present)");
929 // Try to constant fold it up front, if possible.
931 if (Res->EvaluateAsAbsolute(Value))
932 Res = MCConstantExpr::Create(Value, getContext());
937 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
939 return ParseParenExpr(Res, EndLoc) ||
940 ParseBinOpRHS(1, Res, EndLoc);
943 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
946 SMLoc StartLoc = Lexer.getLoc();
947 if (ParseExpression(Expr))
950 if (!Expr->EvaluateAsAbsolute(Res))
951 return Error(StartLoc, "expected absolute expression");
956 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
957 MCBinaryExpr::Opcode &Kind) {
960 return 0; // not a binop.
962 // Lowest Precedence: &&, ||
963 case AsmToken::AmpAmp:
964 Kind = MCBinaryExpr::LAnd;
966 case AsmToken::PipePipe:
967 Kind = MCBinaryExpr::LOr;
971 // Low Precedence: |, &, ^
973 // FIXME: gas seems to support '!' as an infix operator?
975 Kind = MCBinaryExpr::Or;
977 case AsmToken::Caret:
978 Kind = MCBinaryExpr::Xor;
981 Kind = MCBinaryExpr::And;
984 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
985 case AsmToken::EqualEqual:
986 Kind = MCBinaryExpr::EQ;
988 case AsmToken::ExclaimEqual:
989 case AsmToken::LessGreater:
990 Kind = MCBinaryExpr::NE;
993 Kind = MCBinaryExpr::LT;
995 case AsmToken::LessEqual:
996 Kind = MCBinaryExpr::LTE;
998 case AsmToken::Greater:
999 Kind = MCBinaryExpr::GT;
1001 case AsmToken::GreaterEqual:
1002 Kind = MCBinaryExpr::GTE;
1005 // Intermediate Precedence: <<, >>
1006 case AsmToken::LessLess:
1007 Kind = MCBinaryExpr::Shl;
1009 case AsmToken::GreaterGreater:
1010 Kind = MCBinaryExpr::Shr;
1013 // High Intermediate Precedence: +, -
1014 case AsmToken::Plus:
1015 Kind = MCBinaryExpr::Add;
1017 case AsmToken::Minus:
1018 Kind = MCBinaryExpr::Sub;
1021 // Highest Precedence: *, /, %
1022 case AsmToken::Star:
1023 Kind = MCBinaryExpr::Mul;
1025 case AsmToken::Slash:
1026 Kind = MCBinaryExpr::Div;
1028 case AsmToken::Percent:
1029 Kind = MCBinaryExpr::Mod;
1035 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1036 /// Res contains the LHS of the expression on input.
1037 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1040 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1041 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1043 // If the next token is lower precedence than we are allowed to eat, return
1044 // successfully with what we ate already.
1045 if (TokPrec < Precedence)
1050 // Eat the next primary expression.
1052 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1054 // If BinOp binds less tightly with RHS than the operator after RHS, let
1055 // the pending operator take RHS as its LHS.
1056 MCBinaryExpr::Opcode Dummy;
1057 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1058 if (TokPrec < NextTokPrec) {
1059 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1062 // Merge LHS and RHS according to operator.
1063 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1068 /// ::= EndOfStatement
1069 /// ::= Label* Directive ...Operands... EndOfStatement
1070 /// ::= Label* Identifier OperandList* EndOfStatement
1071 bool AsmParser::ParseStatement() {
1072 if (Lexer.is(AsmToken::EndOfStatement)) {
1078 // Statements always start with an identifier or are a full line comment.
1079 AsmToken ID = getTok();
1080 SMLoc IDLoc = ID.getLoc();
1082 int64_t LocalLabelVal = -1;
1083 // A full line comment is a '#' as the first token.
1084 if (Lexer.is(AsmToken::Hash))
1085 return ParseCppHashLineFilenameComment(IDLoc);
1087 // Allow an integer followed by a ':' as a directional local label.
1088 if (Lexer.is(AsmToken::Integer)) {
1089 LocalLabelVal = getTok().getIntVal();
1090 if (LocalLabelVal < 0) {
1091 if (!TheCondState.Ignore)
1092 return TokError("unexpected token at start of statement");
1096 IDVal = getTok().getString();
1097 Lex(); // Consume the integer token to be used as an identifier token.
1098 if (Lexer.getKind() != AsmToken::Colon) {
1099 if (!TheCondState.Ignore)
1100 return TokError("unexpected token at start of statement");
1104 } else if (Lexer.is(AsmToken::Dot)) {
1105 // Treat '.' as a valid identifier in this context.
1109 } else if (ParseIdentifier(IDVal)) {
1110 if (!TheCondState.Ignore)
1111 return TokError("unexpected token at start of statement");
1116 // Handle conditional assembly here before checking for skipping. We
1117 // have to do this so that .endif isn't skipped in a ".if 0" block for
1120 return ParseDirectiveIf(IDLoc);
1121 if (IDVal == ".ifb")
1122 return ParseDirectiveIfb(IDLoc, true);
1123 if (IDVal == ".ifnb")
1124 return ParseDirectiveIfb(IDLoc, false);
1125 if (IDVal == ".ifc")
1126 return ParseDirectiveIfc(IDLoc, true);
1127 if (IDVal == ".ifnc")
1128 return ParseDirectiveIfc(IDLoc, false);
1129 if (IDVal == ".ifdef")
1130 return ParseDirectiveIfdef(IDLoc, true);
1131 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1132 return ParseDirectiveIfdef(IDLoc, false);
1133 if (IDVal == ".elseif")
1134 return ParseDirectiveElseIf(IDLoc);
1135 if (IDVal == ".else")
1136 return ParseDirectiveElse(IDLoc);
1137 if (IDVal == ".endif")
1138 return ParseDirectiveEndIf(IDLoc);
1140 // If we are in a ".if 0" block, ignore this statement.
1141 if (TheCondState.Ignore) {
1142 EatToEndOfStatement();
1146 // FIXME: Recurse on local labels?
1148 // See what kind of statement we have.
1149 switch (Lexer.getKind()) {
1150 case AsmToken::Colon: {
1151 CheckForValidSection();
1153 // identifier ':' -> Label.
1156 // Diagnose attempt to use '.' as a label.
1158 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1160 // Diagnose attempt to use a variable as a label.
1162 // FIXME: Diagnostics. Note the location of the definition as a label.
1163 // FIXME: This doesn't diagnose assignment to a symbol which has been
1164 // implicitly marked as external.
1166 if (LocalLabelVal == -1)
1167 Sym = getContext().GetOrCreateSymbol(IDVal);
1169 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1170 if (!Sym->isUndefined() || Sym->isVariable())
1171 return Error(IDLoc, "invalid symbol redefinition");
1176 // If we are generating dwarf for assembly source files then gather the
1177 // info to make a dwarf label entry for this label if needed.
1178 if (getContext().getGenDwarfForAssembly())
1179 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1182 // Consume any end of statement token, if present, to avoid spurious
1183 // AddBlankLine calls().
1184 if (Lexer.is(AsmToken::EndOfStatement)) {
1186 if (Lexer.is(AsmToken::Eof))
1190 return ParseStatement();
1193 case AsmToken::Equal:
1194 // identifier '=' ... -> assignment statement
1197 return ParseAssignment(IDVal, true);
1199 default: // Normal instruction or directive.
1203 // If macros are enabled, check to see if this is a macro instantiation.
1205 if (const Macro *M = MacroMap.lookup(IDVal))
1206 return HandleMacroEntry(IDVal, IDLoc, M);
1208 // Otherwise, we have a normal instruction or directive.
1209 if (IDVal[0] == '.' && IDVal != ".") {
1211 // Target hook for parsing target specific directives.
1212 if (!getTargetParser().ParseDirective(ID))
1215 // Assembler features
1216 if (IDVal == ".set" || IDVal == ".equ")
1217 return ParseDirectiveSet(IDVal, true);
1218 if (IDVal == ".equiv")
1219 return ParseDirectiveSet(IDVal, false);
1223 if (IDVal == ".ascii")
1224 return ParseDirectiveAscii(IDVal, false);
1225 if (IDVal == ".asciz" || IDVal == ".string")
1226 return ParseDirectiveAscii(IDVal, true);
1228 if (IDVal == ".byte")
1229 return ParseDirectiveValue(1);
1230 if (IDVal == ".short")
1231 return ParseDirectiveValue(2);
1232 if (IDVal == ".value")
1233 return ParseDirectiveValue(2);
1234 if (IDVal == ".2byte")
1235 return ParseDirectiveValue(2);
1236 if (IDVal == ".long")
1237 return ParseDirectiveValue(4);
1238 if (IDVal == ".int")
1239 return ParseDirectiveValue(4);
1240 if (IDVal == ".4byte")
1241 return ParseDirectiveValue(4);
1242 if (IDVal == ".quad")
1243 return ParseDirectiveValue(8);
1244 if (IDVal == ".8byte")
1245 return ParseDirectiveValue(8);
1246 if (IDVal == ".single" || IDVal == ".float")
1247 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1248 if (IDVal == ".double")
1249 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1251 if (IDVal == ".align") {
1252 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1253 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1255 if (IDVal == ".align32") {
1256 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1257 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1259 if (IDVal == ".balign")
1260 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1261 if (IDVal == ".balignw")
1262 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1263 if (IDVal == ".balignl")
1264 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1265 if (IDVal == ".p2align")
1266 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1267 if (IDVal == ".p2alignw")
1268 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1269 if (IDVal == ".p2alignl")
1270 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1272 if (IDVal == ".org")
1273 return ParseDirectiveOrg();
1275 if (IDVal == ".fill")
1276 return ParseDirectiveFill();
1277 if (IDVal == ".space" || IDVal == ".skip")
1278 return ParseDirectiveSpace();
1279 if (IDVal == ".zero")
1280 return ParseDirectiveZero();
1282 // Symbol attribute directives
1284 if (IDVal == ".extern") {
1285 EatToEndOfStatement(); // .extern is the default, ignore it.
1288 if (IDVal == ".globl" || IDVal == ".global")
1289 return ParseDirectiveSymbolAttribute(MCSA_Global);
1290 if (IDVal == ".indirect_symbol")
1291 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1292 if (IDVal == ".lazy_reference")
1293 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1294 if (IDVal == ".no_dead_strip")
1295 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1296 if (IDVal == ".symbol_resolver")
1297 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1298 if (IDVal == ".private_extern")
1299 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1300 if (IDVal == ".reference")
1301 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1302 if (IDVal == ".weak_definition")
1303 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1304 if (IDVal == ".weak_reference")
1305 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1306 if (IDVal == ".weak_def_can_be_hidden")
1307 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1309 if (IDVal == ".comm" || IDVal == ".common")
1310 return ParseDirectiveComm(/*IsLocal=*/false);
1311 if (IDVal == ".lcomm")
1312 return ParseDirectiveComm(/*IsLocal=*/true);
1314 if (IDVal == ".abort")
1315 return ParseDirectiveAbort();
1316 if (IDVal == ".include")
1317 return ParseDirectiveInclude();
1318 if (IDVal == ".incbin")
1319 return ParseDirectiveIncbin();
1321 if (IDVal == ".code16" || IDVal == ".code16gcc")
1322 return TokError(Twine(IDVal) + " not supported yet");
1324 // Macro-like directives
1325 if (IDVal == ".rept")
1326 return ParseDirectiveRept(IDLoc);
1327 if (IDVal == ".irp")
1328 return ParseDirectiveIrp(IDLoc);
1329 if (IDVal == ".irpc")
1330 return ParseDirectiveIrpc(IDLoc);
1331 if (IDVal == ".endr")
1332 return ParseDirectiveEndr(IDLoc);
1334 // Look up the handler in the handler table.
1335 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1336 DirectiveMap.lookup(IDVal);
1338 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1341 return Error(IDLoc, "unknown directive");
1344 CheckForValidSection();
1346 // Canonicalize the opcode to lower case.
1347 SmallString<128> OpcodeStr;
1348 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1349 OpcodeStr.push_back(tolower(IDVal[i]));
1351 bool HadError = getTargetParser().ParseInstruction(OpcodeStr.str(), IDLoc,
1354 // Dump the parsed representation, if requested.
1355 if (getShowParsedOperands()) {
1356 SmallString<256> Str;
1357 raw_svector_ostream OS(Str);
1358 OS << "parsed instruction: [";
1359 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1362 ParsedOperands[i]->print(OS);
1366 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1369 // If we are generating dwarf for assembly source files and the current
1370 // section is the initial text section then generate a .loc directive for
1372 if (!HadError && getContext().getGenDwarfForAssembly() &&
1373 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1374 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1375 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1376 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1377 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1381 // If parsing succeeded, match the instruction.
1384 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Opcode,
1385 ParsedOperands, Out,
1390 // Free any parsed operands. If parsing ms-style inline assembly the operands
1391 // will be freed by the ParseMSInlineAsm() function.
1392 if (!ParsingInlineAsm) {
1393 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1394 delete ParsedOperands[i];
1395 ParsedOperands.clear();
1398 // Don't skip the rest of the line, the instruction parser is responsible for
1403 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1404 /// since they may not be able to be tokenized to get to the end of line token.
1405 void AsmParser::EatToEndOfLine() {
1406 if (!Lexer.is(AsmToken::EndOfStatement))
1407 Lexer.LexUntilEndOfLine();
1412 /// ParseCppHashLineFilenameComment as this:
1413 /// ::= # number "filename"
1414 /// or just as a full line comment if it doesn't have a number and a string.
1415 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1416 Lex(); // Eat the hash token.
1418 if (getLexer().isNot(AsmToken::Integer)) {
1419 // Consume the line since in cases it is not a well-formed line directive,
1420 // as if were simply a full line comment.
1425 int64_t LineNumber = getTok().getIntVal();
1428 if (getLexer().isNot(AsmToken::String)) {
1433 StringRef Filename = getTok().getString();
1434 // Get rid of the enclosing quotes.
1435 Filename = Filename.substr(1, Filename.size()-2);
1437 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1439 CppHashFilename = Filename;
1440 CppHashLineNumber = LineNumber;
1442 // Ignore any trailing characters, they're just comment.
1447 /// DiagHandler - will use the last parsed cpp hash line filename comment
1448 /// for the Filename and LineNo if any in the diagnostic.
1449 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1450 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1451 raw_ostream &OS = errs();
1453 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1454 const SMLoc &DiagLoc = Diag.getLoc();
1455 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1456 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1458 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1459 // before printing the message.
1460 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1461 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1462 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1463 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1466 // If we have not parsed a cpp hash line filename comment or the source
1467 // manager changed or buffer changed (like in a nested include) then just
1468 // print the normal diagnostic using its Filename and LineNo.
1469 if (!Parser->CppHashLineNumber ||
1470 &DiagSrcMgr != &Parser->SrcMgr ||
1471 DiagBuf != CppHashBuf) {
1472 if (Parser->SavedDiagHandler)
1473 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1479 // Use the CppHashFilename and calculate a line number based on the
1480 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1482 const std::string Filename = Parser->CppHashFilename;
1484 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1485 int CppHashLocLineNo =
1486 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1487 int LineNo = Parser->CppHashLineNumber - 1 +
1488 (DiagLocLineNo - CppHashLocLineNo);
1490 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1491 Filename, LineNo, Diag.getColumnNo(),
1492 Diag.getKind(), Diag.getMessage(),
1493 Diag.getLineContents(), Diag.getRanges());
1495 if (Parser->SavedDiagHandler)
1496 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1498 NewDiag.print(0, OS);
1501 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1502 // difference being that that function accepts '@' as part of identifiers and
1503 // we can't do that. AsmLexer.cpp should probably be changed to handle
1504 // '@' as a special case when needed.
1505 static bool isIdentifierChar(char c) {
1506 return isalnum(c) || c == '_' || c == '$' || c == '.';
1509 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1510 const MacroParameters &Parameters,
1511 const MacroArguments &A,
1513 unsigned NParameters = Parameters.size();
1514 if (NParameters != 0 && NParameters != A.size())
1515 return Error(L, "Wrong number of arguments");
1517 // A macro without parameters is handled differently on Darwin:
1518 // gas accepts no arguments and does no substitutions
1519 while (!Body.empty()) {
1520 // Scan for the next substitution.
1521 std::size_t End = Body.size(), Pos = 0;
1522 for (; Pos != End; ++Pos) {
1523 // Check for a substitution or escape.
1525 // This macro has no parameters, look for $0, $1, etc.
1526 if (Body[Pos] != '$' || Pos + 1 == End)
1529 char Next = Body[Pos + 1];
1530 if (Next == '$' || Next == 'n' || isdigit(Next))
1533 // This macro has parameters, look for \foo, \bar, etc.
1534 if (Body[Pos] == '\\' && Pos + 1 != End)
1540 OS << Body.slice(0, Pos);
1542 // Check if we reached the end.
1547 switch (Body[Pos+1]) {
1553 // $n => number of arguments
1558 // $[0-9] => argument
1560 // Missing arguments are ignored.
1561 unsigned Index = Body[Pos+1] - '0';
1562 if (Index >= A.size())
1565 // Otherwise substitute with the token values, with spaces eliminated.
1566 for (MacroArgument::const_iterator it = A[Index].begin(),
1567 ie = A[Index].end(); it != ie; ++it)
1568 OS << it->getString();
1574 unsigned I = Pos + 1;
1575 while (isIdentifierChar(Body[I]) && I + 1 != End)
1578 const char *Begin = Body.data() + Pos +1;
1579 StringRef Argument(Begin, I - (Pos +1));
1581 for (; Index < NParameters; ++Index)
1582 if (Parameters[Index].first == Argument)
1585 if (Index == NParameters) {
1586 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1589 OS << '\\' << Argument;
1593 for (MacroArgument::const_iterator it = A[Index].begin(),
1594 ie = A[Index].end(); it != ie; ++it)
1595 if (it->getKind() == AsmToken::String)
1596 OS << it->getStringContents();
1598 OS << it->getString();
1600 Pos += 1 + Argument.size();
1603 // Update the scan point.
1604 Body = Body.substr(Pos);
1610 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1612 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1616 static bool IsOperator(AsmToken::TokenKind kind)
1622 case AsmToken::Plus:
1623 case AsmToken::Minus:
1624 case AsmToken::Tilde:
1625 case AsmToken::Slash:
1626 case AsmToken::Star:
1628 case AsmToken::Equal:
1629 case AsmToken::EqualEqual:
1630 case AsmToken::Pipe:
1631 case AsmToken::PipePipe:
1632 case AsmToken::Caret:
1634 case AsmToken::AmpAmp:
1635 case AsmToken::Exclaim:
1636 case AsmToken::ExclaimEqual:
1637 case AsmToken::Percent:
1638 case AsmToken::Less:
1639 case AsmToken::LessEqual:
1640 case AsmToken::LessLess:
1641 case AsmToken::LessGreater:
1642 case AsmToken::Greater:
1643 case AsmToken::GreaterEqual:
1644 case AsmToken::GreaterGreater:
1649 /// ParseMacroArgument - Extract AsmTokens for a macro argument.
1650 /// This is used for both default macro parameter values and the
1651 /// arguments in macro invocations
1652 bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1653 AsmToken::TokenKind &ArgumentDelimiter) {
1654 unsigned ParenLevel = 0;
1655 unsigned AddTokens = 0;
1657 // gas accepts arguments separated by whitespace, except on Darwin
1659 Lexer.setSkipSpace(false);
1662 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1663 Lexer.setSkipSpace(true);
1664 return TokError("unexpected token in macro instantiation");
1667 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1668 // Spaces and commas cannot be mixed to delimit parameters
1669 if (ArgumentDelimiter == AsmToken::Eof)
1670 ArgumentDelimiter = AsmToken::Comma;
1671 else if (ArgumentDelimiter != AsmToken::Comma) {
1672 Lexer.setSkipSpace(true);
1673 return TokError("expected ' ' for macro argument separator");
1678 if (Lexer.is(AsmToken::Space)) {
1679 Lex(); // Eat spaces
1681 // Spaces can delimit parameters, but could also be part an expression.
1682 // If the token after a space is an operator, add the token and the next
1683 // one into this argument
1684 if (ArgumentDelimiter == AsmToken::Space ||
1685 ArgumentDelimiter == AsmToken::Eof) {
1686 if (IsOperator(Lexer.getKind())) {
1687 // Check to see whether the token is used as an operator,
1688 // or part of an identifier
1689 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1690 if (*NextChar == ' ')
1694 if (!AddTokens && ParenLevel == 0) {
1695 if (ArgumentDelimiter == AsmToken::Eof &&
1696 !IsOperator(Lexer.getKind()))
1697 ArgumentDelimiter = AsmToken::Space;
1703 // HandleMacroEntry relies on not advancing the lexer here
1704 // to be able to fill in the remaining default parameter values
1705 if (Lexer.is(AsmToken::EndOfStatement))
1708 // Adjust the current parentheses level.
1709 if (Lexer.is(AsmToken::LParen))
1711 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1714 // Append the token to the current argument list.
1715 MA.push_back(getTok());
1721 Lexer.setSkipSpace(true);
1722 if (ParenLevel != 0)
1723 return TokError("unbalanced parentheses in macro argument");
1727 // Parse the macro instantiation arguments.
1728 bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
1729 const unsigned NParameters = M ? M->Parameters.size() : 0;
1730 // Argument delimiter is initially unknown. It will be set by
1731 // ParseMacroArgument()
1732 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1734 // Parse two kinds of macro invocations:
1735 // - macros defined without any parameters accept an arbitrary number of them
1736 // - macros defined with parameters accept at most that many of them
1737 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1741 if (ParseMacroArgument(MA, ArgumentDelimiter))
1744 if (!MA.empty() || !NParameters)
1746 else if (NParameters) {
1747 if (!M->Parameters[Parameter].second.empty())
1748 A.push_back(M->Parameters[Parameter].second);
1751 // At the end of the statement, fill in remaining arguments that have
1752 // default values. If there aren't any, then the next argument is
1753 // required but missing
1754 if (Lexer.is(AsmToken::EndOfStatement)) {
1755 if (NParameters && Parameter < NParameters - 1) {
1756 if (M->Parameters[Parameter + 1].second.empty())
1757 return TokError("macro argument '" +
1758 Twine(M->Parameters[Parameter + 1].first) +
1766 if (Lexer.is(AsmToken::Comma))
1769 return TokError("Too many arguments");
1772 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1774 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1775 // this, although we should protect against infinite loops.
1776 if (ActiveMacros.size() == 20)
1777 return TokError("macros cannot be nested more than 20 levels deep");
1780 if (ParseMacroArguments(M, A))
1783 // Remove any trailing empty arguments. Do this after-the-fact as we have
1784 // to keep empty arguments in the middle of the list or positionality
1785 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1786 while (!A.empty() && A.back().empty())
1789 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1790 // to hold the macro body with substitutions.
1791 SmallString<256> Buf;
1792 StringRef Body = M->Body;
1793 raw_svector_ostream OS(Buf);
1795 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1798 // We include the .endmacro in the buffer as our queue to exit the macro
1800 OS << ".endmacro\n";
1802 MemoryBuffer *Instantiation =
1803 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1805 // Create the macro instantiation object and add to the current macro
1806 // instantiation stack.
1807 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1810 ActiveMacros.push_back(MI);
1812 // Jump to the macro instantiation and prime the lexer.
1813 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1814 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1820 void AsmParser::HandleMacroExit() {
1821 // Jump to the EndOfStatement we should return to, and consume it.
1822 JumpToLoc(ActiveMacros.back()->ExitLoc);
1825 // Pop the instantiation entry.
1826 delete ActiveMacros.back();
1827 ActiveMacros.pop_back();
1830 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1831 switch (Value->getKind()) {
1832 case MCExpr::Binary: {
1833 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1834 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1837 case MCExpr::Target:
1838 case MCExpr::Constant:
1840 case MCExpr::SymbolRef: {
1841 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1843 return IsUsedIn(Sym, S.getVariableValue());
1847 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1850 llvm_unreachable("Unknown expr kind!");
1853 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1855 // FIXME: Use better location, we should use proper tokens.
1856 SMLoc EqualLoc = Lexer.getLoc();
1858 const MCExpr *Value;
1859 if (ParseExpression(Value))
1862 // Note: we don't count b as used in "a = b". This is to allow
1866 if (Lexer.isNot(AsmToken::EndOfStatement))
1867 return TokError("unexpected token in assignment");
1869 // Error on assignment to '.'.
1871 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1872 "(use '.space' or '.org').)"));
1875 // Eat the end of statement marker.
1878 // Validate that the LHS is allowed to be a variable (either it has not been
1879 // used as a symbol, or it is an absolute symbol).
1880 MCSymbol *Sym = getContext().LookupSymbol(Name);
1882 // Diagnose assignment to a label.
1884 // FIXME: Diagnostics. Note the location of the definition as a label.
1885 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1886 if (IsUsedIn(Sym, Value))
1887 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1888 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1889 ; // Allow redefinitions of undefined symbols only used in directives.
1890 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1891 ; // Allow redefinitions of variables that haven't yet been used.
1892 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1893 return Error(EqualLoc, "redefinition of '" + Name + "'");
1894 else if (!Sym->isVariable())
1895 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1896 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1897 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1900 // Don't count these checks as uses.
1901 Sym->setUsed(false);
1903 Sym = getContext().GetOrCreateSymbol(Name);
1905 // FIXME: Handle '.'.
1907 // Do the assignment.
1908 Out.EmitAssignment(Sym, Value);
1910 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1916 /// ParseIdentifier:
1919 bool AsmParser::ParseIdentifier(StringRef &Res) {
1920 // The assembler has relaxed rules for accepting identifiers, in particular we
1921 // allow things like '.globl $foo', which would normally be separate
1922 // tokens. At this level, we have already lexed so we cannot (currently)
1923 // handle this as a context dependent token, instead we detect adjacent tokens
1924 // and return the combined identifier.
1925 if (Lexer.is(AsmToken::Dollar)) {
1926 SMLoc DollarLoc = getLexer().getLoc();
1928 // Consume the dollar sign, and check for a following identifier.
1930 if (Lexer.isNot(AsmToken::Identifier))
1933 // We have a '$' followed by an identifier, make sure they are adjacent.
1934 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1937 // Construct the joined identifier and consume the token.
1938 Res = StringRef(DollarLoc.getPointer(),
1939 getTok().getIdentifier().size() + 1);
1944 if (Lexer.isNot(AsmToken::Identifier) &&
1945 Lexer.isNot(AsmToken::String))
1948 Res = getTok().getIdentifier();
1950 Lex(); // Consume the identifier token.
1955 /// ParseDirectiveSet:
1956 /// ::= .equ identifier ',' expression
1957 /// ::= .equiv identifier ',' expression
1958 /// ::= .set identifier ',' expression
1959 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1962 if (ParseIdentifier(Name))
1963 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1965 if (getLexer().isNot(AsmToken::Comma))
1966 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1969 return ParseAssignment(Name, allow_redef, true);
1972 bool AsmParser::ParseEscapedString(std::string &Data) {
1973 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1976 StringRef Str = getTok().getStringContents();
1977 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1978 if (Str[i] != '\\') {
1983 // Recognize escaped characters. Note that this escape semantics currently
1984 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1987 return TokError("unexpected backslash at end of string");
1989 // Recognize octal sequences.
1990 if ((unsigned) (Str[i] - '0') <= 7) {
1991 // Consume up to three octal characters.
1992 unsigned Value = Str[i] - '0';
1994 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1996 Value = Value * 8 + (Str[i] - '0');
1998 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2000 Value = Value * 8 + (Str[i] - '0');
2005 return TokError("invalid octal escape sequence (out of range)");
2007 Data += (unsigned char) Value;
2011 // Otherwise recognize individual escapes.
2014 // Just reject invalid escape sequences for now.
2015 return TokError("invalid escape sequence (unrecognized character)");
2017 case 'b': Data += '\b'; break;
2018 case 'f': Data += '\f'; break;
2019 case 'n': Data += '\n'; break;
2020 case 'r': Data += '\r'; break;
2021 case 't': Data += '\t'; break;
2022 case '"': Data += '"'; break;
2023 case '\\': Data += '\\'; break;
2030 /// ParseDirectiveAscii:
2031 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2032 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2033 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2034 CheckForValidSection();
2037 if (getLexer().isNot(AsmToken::String))
2038 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2041 if (ParseEscapedString(Data))
2044 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2046 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2050 if (getLexer().is(AsmToken::EndOfStatement))
2053 if (getLexer().isNot(AsmToken::Comma))
2054 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2063 /// ParseDirectiveValue
2064 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2065 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2066 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2067 CheckForValidSection();
2070 const MCExpr *Value;
2071 SMLoc ExprLoc = getLexer().getLoc();
2072 if (ParseExpression(Value))
2075 // Special case constant expressions to match code generator.
2076 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2077 assert(Size <= 8 && "Invalid size");
2078 uint64_t IntValue = MCE->getValue();
2079 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2080 return Error(ExprLoc, "literal value out of range for directive");
2081 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2083 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2085 if (getLexer().is(AsmToken::EndOfStatement))
2088 // FIXME: Improve diagnostic.
2089 if (getLexer().isNot(AsmToken::Comma))
2090 return TokError("unexpected token in directive");
2099 /// ParseDirectiveRealValue
2100 /// ::= (.single | .double) [ expression (, expression)* ]
2101 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2102 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2103 CheckForValidSection();
2106 // We don't truly support arithmetic on floating point expressions, so we
2107 // have to manually parse unary prefixes.
2109 if (getLexer().is(AsmToken::Minus)) {
2112 } else if (getLexer().is(AsmToken::Plus))
2115 if (getLexer().isNot(AsmToken::Integer) &&
2116 getLexer().isNot(AsmToken::Real) &&
2117 getLexer().isNot(AsmToken::Identifier))
2118 return TokError("unexpected token in directive");
2120 // Convert to an APFloat.
2121 APFloat Value(Semantics);
2122 StringRef IDVal = getTok().getString();
2123 if (getLexer().is(AsmToken::Identifier)) {
2124 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2125 Value = APFloat::getInf(Semantics);
2126 else if (!IDVal.compare_lower("nan"))
2127 Value = APFloat::getNaN(Semantics, false, ~0);
2129 return TokError("invalid floating point literal");
2130 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2131 APFloat::opInvalidOp)
2132 return TokError("invalid floating point literal");
2136 // Consume the numeric token.
2139 // Emit the value as an integer.
2140 APInt AsInt = Value.bitcastToAPInt();
2141 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2142 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2144 if (getLexer().is(AsmToken::EndOfStatement))
2147 if (getLexer().isNot(AsmToken::Comma))
2148 return TokError("unexpected token in directive");
2157 /// ParseDirectiveSpace
2158 /// ::= .space expression [ , expression ]
2159 bool AsmParser::ParseDirectiveSpace() {
2160 CheckForValidSection();
2163 if (ParseAbsoluteExpression(NumBytes))
2166 int64_t FillExpr = 0;
2167 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2168 if (getLexer().isNot(AsmToken::Comma))
2169 return TokError("unexpected token in '.space' directive");
2172 if (ParseAbsoluteExpression(FillExpr))
2175 if (getLexer().isNot(AsmToken::EndOfStatement))
2176 return TokError("unexpected token in '.space' directive");
2182 return TokError("invalid number of bytes in '.space' directive");
2184 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
2185 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
2190 /// ParseDirectiveZero
2191 /// ::= .zero expression
2192 bool AsmParser::ParseDirectiveZero() {
2193 CheckForValidSection();
2196 if (ParseAbsoluteExpression(NumBytes))
2200 if (getLexer().is(AsmToken::Comma)) {
2202 if (ParseAbsoluteExpression(Val))
2206 if (getLexer().isNot(AsmToken::EndOfStatement))
2207 return TokError("unexpected token in '.zero' directive");
2211 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2216 /// ParseDirectiveFill
2217 /// ::= .fill expression , expression , expression
2218 bool AsmParser::ParseDirectiveFill() {
2219 CheckForValidSection();
2222 if (ParseAbsoluteExpression(NumValues))
2225 if (getLexer().isNot(AsmToken::Comma))
2226 return TokError("unexpected token in '.fill' directive");
2230 if (ParseAbsoluteExpression(FillSize))
2233 if (getLexer().isNot(AsmToken::Comma))
2234 return TokError("unexpected token in '.fill' directive");
2238 if (ParseAbsoluteExpression(FillExpr))
2241 if (getLexer().isNot(AsmToken::EndOfStatement))
2242 return TokError("unexpected token in '.fill' directive");
2246 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2247 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2249 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2250 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2255 /// ParseDirectiveOrg
2256 /// ::= .org expression [ , expression ]
2257 bool AsmParser::ParseDirectiveOrg() {
2258 CheckForValidSection();
2260 const MCExpr *Offset;
2261 SMLoc Loc = getTok().getLoc();
2262 if (ParseExpression(Offset))
2265 // Parse optional fill expression.
2266 int64_t FillExpr = 0;
2267 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2268 if (getLexer().isNot(AsmToken::Comma))
2269 return TokError("unexpected token in '.org' directive");
2272 if (ParseAbsoluteExpression(FillExpr))
2275 if (getLexer().isNot(AsmToken::EndOfStatement))
2276 return TokError("unexpected token in '.org' directive");
2281 // Only limited forms of relocatable expressions are accepted here, it
2282 // has to be relative to the current section. The streamer will return
2283 // 'true' if the expression wasn't evaluatable.
2284 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2285 return Error(Loc, "expected assembly-time absolute expression");
2290 /// ParseDirectiveAlign
2291 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2292 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2293 CheckForValidSection();
2295 SMLoc AlignmentLoc = getLexer().getLoc();
2297 if (ParseAbsoluteExpression(Alignment))
2301 bool HasFillExpr = false;
2302 int64_t FillExpr = 0;
2303 int64_t MaxBytesToFill = 0;
2304 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2305 if (getLexer().isNot(AsmToken::Comma))
2306 return TokError("unexpected token in directive");
2309 // The fill expression can be omitted while specifying a maximum number of
2310 // alignment bytes, e.g:
2312 if (getLexer().isNot(AsmToken::Comma)) {
2314 if (ParseAbsoluteExpression(FillExpr))
2318 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2319 if (getLexer().isNot(AsmToken::Comma))
2320 return TokError("unexpected token in directive");
2323 MaxBytesLoc = getLexer().getLoc();
2324 if (ParseAbsoluteExpression(MaxBytesToFill))
2327 if (getLexer().isNot(AsmToken::EndOfStatement))
2328 return TokError("unexpected token in directive");
2337 // Compute alignment in bytes.
2339 // FIXME: Diagnose overflow.
2340 if (Alignment >= 32) {
2341 Error(AlignmentLoc, "invalid alignment value");
2345 Alignment = 1ULL << Alignment;
2348 // Diagnose non-sensical max bytes to align.
2349 if (MaxBytesLoc.isValid()) {
2350 if (MaxBytesToFill < 1) {
2351 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2352 "many bytes, ignoring maximum bytes expression");
2356 if (MaxBytesToFill >= Alignment) {
2357 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2363 // Check whether we should use optimal code alignment for this .align
2365 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2366 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2367 ValueSize == 1 && UseCodeAlign) {
2368 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2370 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2371 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2378 /// ParseDirectiveSymbolAttribute
2379 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2380 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2381 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2384 SMLoc Loc = getTok().getLoc();
2386 if (ParseIdentifier(Name))
2387 return Error(Loc, "expected identifier in directive");
2389 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2391 // Assembler local symbols don't make any sense here. Complain loudly.
2392 if (Sym->isTemporary())
2393 return Error(Loc, "non-local symbol required in directive");
2395 getStreamer().EmitSymbolAttribute(Sym, Attr);
2397 if (getLexer().is(AsmToken::EndOfStatement))
2400 if (getLexer().isNot(AsmToken::Comma))
2401 return TokError("unexpected token in directive");
2410 /// ParseDirectiveComm
2411 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2412 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2413 CheckForValidSection();
2415 SMLoc IDLoc = getLexer().getLoc();
2417 if (ParseIdentifier(Name))
2418 return TokError("expected identifier in directive");
2420 // Handle the identifier as the key symbol.
2421 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2423 if (getLexer().isNot(AsmToken::Comma))
2424 return TokError("unexpected token in directive");
2428 SMLoc SizeLoc = getLexer().getLoc();
2429 if (ParseAbsoluteExpression(Size))
2432 int64_t Pow2Alignment = 0;
2433 SMLoc Pow2AlignmentLoc;
2434 if (getLexer().is(AsmToken::Comma)) {
2436 Pow2AlignmentLoc = getLexer().getLoc();
2437 if (ParseAbsoluteExpression(Pow2Alignment))
2440 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2441 if (IsLocal && LCOMM == LCOMM::NoAlignment)
2442 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2444 // If this target takes alignments in bytes (not log) validate and convert.
2445 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2446 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
2447 if (!isPowerOf2_64(Pow2Alignment))
2448 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2449 Pow2Alignment = Log2_64(Pow2Alignment);
2453 if (getLexer().isNot(AsmToken::EndOfStatement))
2454 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2458 // NOTE: a size of zero for a .comm should create a undefined symbol
2459 // but a size of .lcomm creates a bss symbol of size zero.
2461 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2462 "be less than zero");
2464 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2465 // may internally end up wanting an alignment in bytes.
2466 // FIXME: Diagnose overflow.
2467 if (Pow2Alignment < 0)
2468 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2469 "alignment, can't be less than zero");
2471 if (!Sym->isUndefined())
2472 return Error(IDLoc, "invalid symbol redefinition");
2474 // Create the Symbol as a common or local common with Size and Pow2Alignment
2476 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2480 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2484 /// ParseDirectiveAbort
2485 /// ::= .abort [... message ...]
2486 bool AsmParser::ParseDirectiveAbort() {
2487 // FIXME: Use loc from directive.
2488 SMLoc Loc = getLexer().getLoc();
2490 StringRef Str = ParseStringToEndOfStatement();
2491 if (getLexer().isNot(AsmToken::EndOfStatement))
2492 return TokError("unexpected token in '.abort' directive");
2497 Error(Loc, ".abort detected. Assembly stopping.");
2499 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2500 // FIXME: Actually abort assembly here.
2505 /// ParseDirectiveInclude
2506 /// ::= .include "filename"
2507 bool AsmParser::ParseDirectiveInclude() {
2508 if (getLexer().isNot(AsmToken::String))
2509 return TokError("expected string in '.include' directive");
2511 std::string Filename = getTok().getString();
2512 SMLoc IncludeLoc = getLexer().getLoc();
2515 if (getLexer().isNot(AsmToken::EndOfStatement))
2516 return TokError("unexpected token in '.include' directive");
2518 // Strip the quotes.
2519 Filename = Filename.substr(1, Filename.size()-2);
2521 // Attempt to switch the lexer to the included file before consuming the end
2522 // of statement to avoid losing it when we switch.
2523 if (EnterIncludeFile(Filename)) {
2524 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2531 /// ParseDirectiveIncbin
2532 /// ::= .incbin "filename"
2533 bool AsmParser::ParseDirectiveIncbin() {
2534 if (getLexer().isNot(AsmToken::String))
2535 return TokError("expected string in '.incbin' directive");
2537 std::string Filename = getTok().getString();
2538 SMLoc IncbinLoc = getLexer().getLoc();
2541 if (getLexer().isNot(AsmToken::EndOfStatement))
2542 return TokError("unexpected token in '.incbin' directive");
2544 // Strip the quotes.
2545 Filename = Filename.substr(1, Filename.size()-2);
2547 // Attempt to process the included file.
2548 if (ProcessIncbinFile(Filename)) {
2549 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2556 /// ParseDirectiveIf
2557 /// ::= .if expression
2558 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2559 TheCondStack.push_back(TheCondState);
2560 TheCondState.TheCond = AsmCond::IfCond;
2561 if (TheCondState.Ignore) {
2562 EatToEndOfStatement();
2565 if (ParseAbsoluteExpression(ExprValue))
2568 if (getLexer().isNot(AsmToken::EndOfStatement))
2569 return TokError("unexpected token in '.if' directive");
2573 TheCondState.CondMet = ExprValue;
2574 TheCondState.Ignore = !TheCondState.CondMet;
2580 /// ParseDirectiveIfb
2582 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2583 TheCondStack.push_back(TheCondState);
2584 TheCondState.TheCond = AsmCond::IfCond;
2586 if (TheCondState.Ignore) {
2587 EatToEndOfStatement();
2589 StringRef Str = ParseStringToEndOfStatement();
2591 if (getLexer().isNot(AsmToken::EndOfStatement))
2592 return TokError("unexpected token in '.ifb' directive");
2596 TheCondState.CondMet = ExpectBlank == Str.empty();
2597 TheCondState.Ignore = !TheCondState.CondMet;
2603 /// ParseDirectiveIfc
2604 /// ::= .ifc string1, string2
2605 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2606 TheCondStack.push_back(TheCondState);
2607 TheCondState.TheCond = AsmCond::IfCond;
2609 if (TheCondState.Ignore) {
2610 EatToEndOfStatement();
2612 StringRef Str1 = ParseStringToComma();
2614 if (getLexer().isNot(AsmToken::Comma))
2615 return TokError("unexpected token in '.ifc' directive");
2619 StringRef Str2 = ParseStringToEndOfStatement();
2621 if (getLexer().isNot(AsmToken::EndOfStatement))
2622 return TokError("unexpected token in '.ifc' directive");
2626 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2627 TheCondState.Ignore = !TheCondState.CondMet;
2633 /// ParseDirectiveIfdef
2634 /// ::= .ifdef symbol
2635 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2637 TheCondStack.push_back(TheCondState);
2638 TheCondState.TheCond = AsmCond::IfCond;
2640 if (TheCondState.Ignore) {
2641 EatToEndOfStatement();
2643 if (ParseIdentifier(Name))
2644 return TokError("expected identifier after '.ifdef'");
2648 MCSymbol *Sym = getContext().LookupSymbol(Name);
2651 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2653 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2654 TheCondState.Ignore = !TheCondState.CondMet;
2660 /// ParseDirectiveElseIf
2661 /// ::= .elseif expression
2662 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2663 if (TheCondState.TheCond != AsmCond::IfCond &&
2664 TheCondState.TheCond != AsmCond::ElseIfCond)
2665 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2667 TheCondState.TheCond = AsmCond::ElseIfCond;
2669 bool LastIgnoreState = false;
2670 if (!TheCondStack.empty())
2671 LastIgnoreState = TheCondStack.back().Ignore;
2672 if (LastIgnoreState || TheCondState.CondMet) {
2673 TheCondState.Ignore = true;
2674 EatToEndOfStatement();
2678 if (ParseAbsoluteExpression(ExprValue))
2681 if (getLexer().isNot(AsmToken::EndOfStatement))
2682 return TokError("unexpected token in '.elseif' directive");
2685 TheCondState.CondMet = ExprValue;
2686 TheCondState.Ignore = !TheCondState.CondMet;
2692 /// ParseDirectiveElse
2694 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2695 if (getLexer().isNot(AsmToken::EndOfStatement))
2696 return TokError("unexpected token in '.else' directive");
2700 if (TheCondState.TheCond != AsmCond::IfCond &&
2701 TheCondState.TheCond != AsmCond::ElseIfCond)
2702 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2704 TheCondState.TheCond = AsmCond::ElseCond;
2705 bool LastIgnoreState = false;
2706 if (!TheCondStack.empty())
2707 LastIgnoreState = TheCondStack.back().Ignore;
2708 if (LastIgnoreState || TheCondState.CondMet)
2709 TheCondState.Ignore = true;
2711 TheCondState.Ignore = false;
2716 /// ParseDirectiveEndIf
2718 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2719 if (getLexer().isNot(AsmToken::EndOfStatement))
2720 return TokError("unexpected token in '.endif' directive");
2724 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2725 TheCondStack.empty())
2726 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2728 if (!TheCondStack.empty()) {
2729 TheCondState = TheCondStack.back();
2730 TheCondStack.pop_back();
2736 /// ParseDirectiveFile
2737 /// ::= .file [number] filename
2738 /// ::= .file number directory filename
2739 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2740 // FIXME: I'm not sure what this is.
2741 int64_t FileNumber = -1;
2742 SMLoc FileNumberLoc = getLexer().getLoc();
2743 if (getLexer().is(AsmToken::Integer)) {
2744 FileNumber = getTok().getIntVal();
2748 return TokError("file number less than one");
2751 if (getLexer().isNot(AsmToken::String))
2752 return TokError("unexpected token in '.file' directive");
2754 // Usually the directory and filename together, otherwise just the directory.
2755 StringRef Path = getTok().getString();
2756 Path = Path.substr(1, Path.size()-2);
2759 StringRef Directory;
2761 if (getLexer().is(AsmToken::String)) {
2762 if (FileNumber == -1)
2763 return TokError("explicit path specified, but no file number");
2764 Filename = getTok().getString();
2765 Filename = Filename.substr(1, Filename.size()-2);
2772 if (getLexer().isNot(AsmToken::EndOfStatement))
2773 return TokError("unexpected token in '.file' directive");
2775 if (FileNumber == -1)
2776 getStreamer().EmitFileDirective(Filename);
2778 if (getContext().getGenDwarfForAssembly() == true)
2779 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2780 "used to generate dwarf debug info for assembly code");
2782 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2783 Error(FileNumberLoc, "file number already allocated");
2789 /// ParseDirectiveLine
2790 /// ::= .line [number]
2791 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2792 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2793 if (getLexer().isNot(AsmToken::Integer))
2794 return TokError("unexpected token in '.line' directive");
2796 int64_t LineNumber = getTok().getIntVal();
2800 // FIXME: Do something with the .line.
2803 if (getLexer().isNot(AsmToken::EndOfStatement))
2804 return TokError("unexpected token in '.line' directive");
2810 /// ParseDirectiveLoc
2811 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2812 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2813 /// The first number is a file number, must have been previously assigned with
2814 /// a .file directive, the second number is the line number and optionally the
2815 /// third number is a column position (zero if not specified). The remaining
2816 /// optional items are .loc sub-directives.
2817 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2819 if (getLexer().isNot(AsmToken::Integer))
2820 return TokError("unexpected token in '.loc' directive");
2821 int64_t FileNumber = getTok().getIntVal();
2823 return TokError("file number less than one in '.loc' directive");
2824 if (!getContext().isValidDwarfFileNumber(FileNumber))
2825 return TokError("unassigned file number in '.loc' directive");
2828 int64_t LineNumber = 0;
2829 if (getLexer().is(AsmToken::Integer)) {
2830 LineNumber = getTok().getIntVal();
2832 return TokError("line number less than one in '.loc' directive");
2836 int64_t ColumnPos = 0;
2837 if (getLexer().is(AsmToken::Integer)) {
2838 ColumnPos = getTok().getIntVal();
2840 return TokError("column position less than zero in '.loc' directive");
2844 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2846 int64_t Discriminator = 0;
2847 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2849 if (getLexer().is(AsmToken::EndOfStatement))
2853 SMLoc Loc = getTok().getLoc();
2854 if (getParser().ParseIdentifier(Name))
2855 return TokError("unexpected token in '.loc' directive");
2857 if (Name == "basic_block")
2858 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2859 else if (Name == "prologue_end")
2860 Flags |= DWARF2_FLAG_PROLOGUE_END;
2861 else if (Name == "epilogue_begin")
2862 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2863 else if (Name == "is_stmt") {
2864 SMLoc Loc = getTok().getLoc();
2865 const MCExpr *Value;
2866 if (getParser().ParseExpression(Value))
2868 // The expression must be the constant 0 or 1.
2869 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2870 int Value = MCE->getValue();
2872 Flags &= ~DWARF2_FLAG_IS_STMT;
2873 else if (Value == 1)
2874 Flags |= DWARF2_FLAG_IS_STMT;
2876 return Error(Loc, "is_stmt value not 0 or 1");
2879 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2882 else if (Name == "isa") {
2883 SMLoc Loc = getTok().getLoc();
2884 const MCExpr *Value;
2885 if (getParser().ParseExpression(Value))
2887 // The expression must be a constant greater or equal to 0.
2888 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2889 int Value = MCE->getValue();
2891 return Error(Loc, "isa number less than zero");
2895 return Error(Loc, "isa number not a constant value");
2898 else if (Name == "discriminator") {
2899 if (getParser().ParseAbsoluteExpression(Discriminator))
2903 return Error(Loc, "unknown sub-directive in '.loc' directive");
2906 if (getLexer().is(AsmToken::EndOfStatement))
2911 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2912 Isa, Discriminator, StringRef());
2917 /// ParseDirectiveStabs
2918 /// ::= .stabs string, number, number, number
2919 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2920 SMLoc DirectiveLoc) {
2921 return TokError("unsupported directive '" + Directive + "'");
2924 /// ParseDirectiveCFISections
2925 /// ::= .cfi_sections section [, section]
2926 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2927 SMLoc DirectiveLoc) {
2932 if (getParser().ParseIdentifier(Name))
2933 return TokError("Expected an identifier");
2935 if (Name == ".eh_frame")
2937 else if (Name == ".debug_frame")
2940 if (getLexer().is(AsmToken::Comma)) {
2943 if (getParser().ParseIdentifier(Name))
2944 return TokError("Expected an identifier");
2946 if (Name == ".eh_frame")
2948 else if (Name == ".debug_frame")
2952 getStreamer().EmitCFISections(EH, Debug);
2957 /// ParseDirectiveCFIStartProc
2958 /// ::= .cfi_startproc
2959 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2960 SMLoc DirectiveLoc) {
2961 getStreamer().EmitCFIStartProc();
2965 /// ParseDirectiveCFIEndProc
2966 /// ::= .cfi_endproc
2967 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2968 getStreamer().EmitCFIEndProc();
2972 /// ParseRegisterOrRegisterNumber - parse register name or number.
2973 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2974 SMLoc DirectiveLoc) {
2977 if (getLexer().isNot(AsmToken::Integer)) {
2978 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2981 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2983 return getParser().ParseAbsoluteExpression(Register);
2988 /// ParseDirectiveCFIDefCfa
2989 /// ::= .cfi_def_cfa register, offset
2990 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2991 SMLoc DirectiveLoc) {
2992 int64_t Register = 0;
2993 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2996 if (getLexer().isNot(AsmToken::Comma))
2997 return TokError("unexpected token in directive");
3001 if (getParser().ParseAbsoluteExpression(Offset))
3004 getStreamer().EmitCFIDefCfa(Register, Offset);
3008 /// ParseDirectiveCFIDefCfaOffset
3009 /// ::= .cfi_def_cfa_offset offset
3010 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3011 SMLoc DirectiveLoc) {
3013 if (getParser().ParseAbsoluteExpression(Offset))
3016 getStreamer().EmitCFIDefCfaOffset(Offset);
3020 /// ParseDirectiveCFIAdjustCfaOffset
3021 /// ::= .cfi_adjust_cfa_offset adjustment
3022 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3023 SMLoc DirectiveLoc) {
3024 int64_t Adjustment = 0;
3025 if (getParser().ParseAbsoluteExpression(Adjustment))
3028 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3032 /// ParseDirectiveCFIDefCfaRegister
3033 /// ::= .cfi_def_cfa_register register
3034 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3035 SMLoc DirectiveLoc) {
3036 int64_t Register = 0;
3037 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3040 getStreamer().EmitCFIDefCfaRegister(Register);
3044 /// ParseDirectiveCFIOffset
3045 /// ::= .cfi_offset register, offset
3046 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3047 int64_t Register = 0;
3050 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3053 if (getLexer().isNot(AsmToken::Comma))
3054 return TokError("unexpected token in directive");
3057 if (getParser().ParseAbsoluteExpression(Offset))
3060 getStreamer().EmitCFIOffset(Register, Offset);
3064 /// ParseDirectiveCFIRelOffset
3065 /// ::= .cfi_rel_offset register, offset
3066 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3067 SMLoc DirectiveLoc) {
3068 int64_t Register = 0;
3070 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3073 if (getLexer().isNot(AsmToken::Comma))
3074 return TokError("unexpected token in directive");
3078 if (getParser().ParseAbsoluteExpression(Offset))
3081 getStreamer().EmitCFIRelOffset(Register, Offset);
3085 static bool isValidEncoding(int64_t Encoding) {
3086 if (Encoding & ~0xff)
3089 if (Encoding == dwarf::DW_EH_PE_omit)
3092 const unsigned Format = Encoding & 0xf;
3093 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3094 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3095 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3096 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3099 const unsigned Application = Encoding & 0x70;
3100 if (Application != dwarf::DW_EH_PE_absptr &&
3101 Application != dwarf::DW_EH_PE_pcrel)
3107 /// ParseDirectiveCFIPersonalityOrLsda
3108 /// ::= .cfi_personality encoding, [symbol_name]
3109 /// ::= .cfi_lsda encoding, [symbol_name]
3110 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
3111 SMLoc DirectiveLoc) {
3112 int64_t Encoding = 0;
3113 if (getParser().ParseAbsoluteExpression(Encoding))
3115 if (Encoding == dwarf::DW_EH_PE_omit)
3118 if (!isValidEncoding(Encoding))
3119 return TokError("unsupported encoding.");
3121 if (getLexer().isNot(AsmToken::Comma))
3122 return TokError("unexpected token in directive");
3126 if (getParser().ParseIdentifier(Name))
3127 return TokError("expected identifier in directive");
3129 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3131 if (IDVal == ".cfi_personality")
3132 getStreamer().EmitCFIPersonality(Sym, Encoding);
3134 assert(IDVal == ".cfi_lsda");
3135 getStreamer().EmitCFILsda(Sym, Encoding);
3140 /// ParseDirectiveCFIRememberState
3141 /// ::= .cfi_remember_state
3142 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3143 SMLoc DirectiveLoc) {
3144 getStreamer().EmitCFIRememberState();
3148 /// ParseDirectiveCFIRestoreState
3149 /// ::= .cfi_remember_state
3150 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3151 SMLoc DirectiveLoc) {
3152 getStreamer().EmitCFIRestoreState();
3156 /// ParseDirectiveCFISameValue
3157 /// ::= .cfi_same_value register
3158 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3159 SMLoc DirectiveLoc) {
3160 int64_t Register = 0;
3162 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3165 getStreamer().EmitCFISameValue(Register);
3170 /// ParseDirectiveCFIRestore
3171 /// ::= .cfi_restore register
3172 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
3173 SMLoc DirectiveLoc) {
3174 int64_t Register = 0;
3175 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3178 getStreamer().EmitCFIRestore(Register);
3183 /// ParseDirectiveCFIEscape
3184 /// ::= .cfi_escape expression[,...]
3185 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3186 SMLoc DirectiveLoc) {
3189 if (getParser().ParseAbsoluteExpression(CurrValue))
3192 Values.push_back((uint8_t)CurrValue);
3194 while (getLexer().is(AsmToken::Comma)) {
3197 if (getParser().ParseAbsoluteExpression(CurrValue))
3200 Values.push_back((uint8_t)CurrValue);
3203 getStreamer().EmitCFIEscape(Values);
3207 /// ParseDirectiveCFISignalFrame
3208 /// ::= .cfi_signal_frame
3209 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3210 SMLoc DirectiveLoc) {
3211 if (getLexer().isNot(AsmToken::EndOfStatement))
3212 return Error(getLexer().getLoc(),
3213 "unexpected token in '" + Directive + "' directive");
3215 getStreamer().EmitCFISignalFrame();
3220 /// ParseDirectiveMacrosOnOff
3223 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3224 SMLoc DirectiveLoc) {
3225 if (getLexer().isNot(AsmToken::EndOfStatement))
3226 return Error(getLexer().getLoc(),
3227 "unexpected token in '" + Directive + "' directive");
3229 getParser().MacrosEnabled = Directive == ".macros_on";
3234 /// ParseDirectiveMacro
3235 /// ::= .macro name [parameters]
3236 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3237 SMLoc DirectiveLoc) {
3239 if (getParser().ParseIdentifier(Name))
3240 return TokError("expected identifier in '.macro' directive");
3242 MacroParameters Parameters;
3243 // Argument delimiter is initially unknown. It will be set by
3244 // ParseMacroArgument()
3245 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3246 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3248 MacroParameter Parameter;
3249 if (getParser().ParseIdentifier(Parameter.first))
3250 return TokError("expected identifier in '.macro' directive");
3252 if (getLexer().is(AsmToken::Equal)) {
3254 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3258 Parameters.push_back(Parameter);
3260 if (getLexer().is(AsmToken::Comma))
3262 else if (getLexer().is(AsmToken::EndOfStatement))
3267 // Eat the end of statement.
3270 AsmToken EndToken, StartToken = getTok();
3272 // Lex the macro definition.
3274 // Check whether we have reached the end of the file.
3275 if (getLexer().is(AsmToken::Eof))
3276 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3278 // Otherwise, check whether we have reach the .endmacro.
3279 if (getLexer().is(AsmToken::Identifier) &&
3280 (getTok().getIdentifier() == ".endm" ||
3281 getTok().getIdentifier() == ".endmacro")) {
3282 EndToken = getTok();
3284 if (getLexer().isNot(AsmToken::EndOfStatement))
3285 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3290 // Otherwise, scan til the end of the statement.
3291 getParser().EatToEndOfStatement();
3294 if (getParser().MacroMap.lookup(Name)) {
3295 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3298 const char *BodyStart = StartToken.getLoc().getPointer();
3299 const char *BodyEnd = EndToken.getLoc().getPointer();
3300 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3301 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3305 /// ParseDirectiveEndMacro
3308 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3309 SMLoc DirectiveLoc) {
3310 if (getLexer().isNot(AsmToken::EndOfStatement))
3311 return TokError("unexpected token in '" + Directive + "' directive");
3313 // If we are inside a macro instantiation, terminate the current
3315 if (!getParser().ActiveMacros.empty()) {
3316 getParser().HandleMacroExit();
3320 // Otherwise, this .endmacro is a stray entry in the file; well formed
3321 // .endmacro directives are handled during the macro definition parsing.
3322 return TokError("unexpected '" + Directive + "' in file, "
3323 "no current macro definition");
3326 /// ParseDirectivePurgeMacro
3328 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3329 SMLoc DirectiveLoc) {
3331 if (getParser().ParseIdentifier(Name))
3332 return TokError("expected identifier in '.purgem' directive");
3334 if (getLexer().isNot(AsmToken::EndOfStatement))
3335 return TokError("unexpected token in '.purgem' directive");
3337 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3338 if (I == getParser().MacroMap.end())
3339 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3341 // Undefine the macro.
3342 delete I->getValue();
3343 getParser().MacroMap.erase(I);
3347 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3348 getParser().CheckForValidSection();
3350 const MCExpr *Value;
3352 if (getParser().ParseExpression(Value))
3355 if (getLexer().isNot(AsmToken::EndOfStatement))
3356 return TokError("unexpected token in directive");
3358 if (DirName[1] == 's')
3359 getStreamer().EmitSLEB128Value(Value);
3361 getStreamer().EmitULEB128Value(Value);
3366 Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3367 AsmToken EndToken, StartToken = getTok();
3369 unsigned NestLevel = 0;
3371 // Check whether we have reached the end of the file.
3372 if (getLexer().is(AsmToken::Eof)) {
3373 Error(DirectiveLoc, "no matching '.endr' in definition");
3377 if (Lexer.is(AsmToken::Identifier) &&
3378 (getTok().getIdentifier() == ".rept")) {
3382 // Otherwise, check whether we have reached the .endr.
3383 if (Lexer.is(AsmToken::Identifier) &&
3384 getTok().getIdentifier() == ".endr") {
3385 if (NestLevel == 0) {
3386 EndToken = getTok();
3388 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3389 TokError("unexpected token in '.endr' directive");
3397 // Otherwise, scan till the end of the statement.
3398 EatToEndOfStatement();
3401 const char *BodyStart = StartToken.getLoc().getPointer();
3402 const char *BodyEnd = EndToken.getLoc().getPointer();
3403 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3405 // We Are Anonymous.
3407 MacroParameters Parameters;
3408 return new Macro(Name, Body, Parameters);
3411 void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3412 raw_svector_ostream &OS) {
3415 MemoryBuffer *Instantiation =
3416 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3418 // Create the macro instantiation object and add to the current macro
3419 // instantiation stack.
3420 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3423 ActiveMacros.push_back(MI);
3425 // Jump to the macro instantiation and prime the lexer.
3426 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3427 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3431 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3433 if (ParseAbsoluteExpression(Count))
3434 return TokError("unexpected token in '.rept' directive");
3437 return TokError("Count is negative");
3439 if (Lexer.isNot(AsmToken::EndOfStatement))
3440 return TokError("unexpected token in '.rept' directive");
3442 // Eat the end of statement.
3445 // Lex the rept definition.
3446 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3450 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3451 // to hold the macro body with substitutions.
3452 SmallString<256> Buf;
3453 MacroParameters Parameters;
3455 raw_svector_ostream OS(Buf);
3457 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3460 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3465 /// ParseDirectiveIrp
3466 /// ::= .irp symbol,values
3467 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3468 MacroParameters Parameters;
3469 MacroParameter Parameter;
3471 if (ParseIdentifier(Parameter.first))
3472 return TokError("expected identifier in '.irp' directive");
3474 Parameters.push_back(Parameter);
3476 if (Lexer.isNot(AsmToken::Comma))
3477 return TokError("expected comma in '.irp' directive");
3482 if (ParseMacroArguments(0, A))
3485 // Eat the end of statement.
3488 // Lex the irp definition.
3489 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3493 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3494 // to hold the macro body with substitutions.
3495 SmallString<256> Buf;
3496 raw_svector_ostream OS(Buf);
3498 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3499 MacroArguments Args;
3502 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3506 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3511 /// ParseDirectiveIrpc
3512 /// ::= .irpc symbol,values
3513 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3514 MacroParameters Parameters;
3515 MacroParameter Parameter;
3517 if (ParseIdentifier(Parameter.first))
3518 return TokError("expected identifier in '.irpc' directive");
3520 Parameters.push_back(Parameter);
3522 if (Lexer.isNot(AsmToken::Comma))
3523 return TokError("expected comma in '.irpc' directive");
3528 if (ParseMacroArguments(0, A))
3531 if (A.size() != 1 || A.front().size() != 1)
3532 return TokError("unexpected token in '.irpc' directive");
3534 // Eat the end of statement.
3537 // Lex the irpc definition.
3538 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3542 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3543 // to hold the macro body with substitutions.
3544 SmallString<256> Buf;
3545 raw_svector_ostream OS(Buf);
3547 StringRef Values = A.front().front().getString();
3548 std::size_t I, End = Values.size();
3549 for (I = 0; I < End; ++I) {
3551 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3553 MacroArguments Args;
3554 Args.push_back(Arg);
3556 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3560 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3565 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3566 if (ActiveMacros.empty())
3567 return TokError("unmatched '.endr' directive");
3569 // The only .repl that should get here are the ones created by
3570 // InstantiateMacroLikeBody.
3571 assert(getLexer().is(AsmToken::EndOfStatement));
3578 enum AsmRewriteKind {
3587 AsmRewriteKind Kind;
3592 AsmRewrite(AsmRewriteKind kind, SMLoc loc, unsigned len, unsigned size = 0)
3593 : Kind(kind), Loc(loc), Len(len), Size(size) { }
3597 bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3598 unsigned &NumOutputs, unsigned &NumInputs,
3599 SmallVectorImpl<void *> &OpDecls,
3600 SmallVectorImpl<std::string> &Constraints,
3601 SmallVectorImpl<std::string> &Clobbers,
3602 const MCInstrInfo *MII,
3603 const MCInstPrinter *IP,
3604 MCAsmParserSemaCallback &SI) {
3605 SmallVector<void*, 4> InputDecls;
3606 SmallVector<void*, 4> OutputDecls;
3607 SmallVector<std::string, 4> InputConstraints;
3608 SmallVector<std::string, 4> OutputConstraints;
3609 std::set<std::string> ClobberRegs;
3611 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
3616 // While we have input, parse each statement.
3617 unsigned InputIdx = 0;
3618 unsigned OutputIdx = 0;
3619 while (getLexer().isNot(AsmToken::Eof)) {
3620 // Clear the opcode.
3623 // Save the conditional ignore state of the parser prior to parsing the statement.
3624 bool PreParseCondStateIgnore = TheCondState.Ignore;
3626 // Save the starting point of this statement in case we need to skip it.
3627 SMLoc Start = getLexer().getLoc();
3629 if (ParseStatement())
3632 // If PreParseCondStateIgnore is false, but TheCondState.Ignore is true, then we
3633 // just parsed a directive that changed the state to ignore. Don't skip
3634 // emitting this directive.
3635 if (PreParseCondStateIgnore && TheCondState.Ignore) {
3636 unsigned Len = getLexer().getLoc().getPointer() - Start.getPointer();
3637 AsmStrRewrites.push_back(AsmRewrite(AOK_Skip, Start, Len));
3641 if (isInstruction()) {
3642 const MCInstrDesc &Desc = MII->get(getOpcode());
3644 // Build the list of clobbers, outputs and inputs.
3645 for (unsigned i = 1, e = ParsedOperands.size(); i != e; ++i) {
3646 MCParsedAsmOperand *Operand = ParsedOperands[i];
3649 if (Operand->isImm()) {
3650 AsmStrRewrites.push_back(AsmRewrite(AOK_Imm,
3651 Operand->getStartLoc(),
3652 Operand->getNameLen()));
3656 // Register operand.
3657 if (Operand->isReg()) {
3658 unsigned NumDefs = Desc.getNumDefs();
3660 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3662 raw_string_ostream OS(Reg);
3663 IP->printRegName(OS, Operand->getReg());
3664 ClobberRegs.insert(StringRef(OS.str()));
3669 // Expr/Input or Output.
3671 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3674 bool isOutput = (i == 1) && Desc.mayStore();
3675 if (Operand->needSizeDirective())
3676 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
3677 Operand->getStartLoc(), 0,
3678 Operand->getMemSize()));
3681 std::string Constraint = "=";
3683 OutputDecls.push_back(OpDecl);
3684 Constraint += Operand->getConstraint().str();
3685 OutputConstraints.push_back(Constraint);
3686 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
3687 Operand->getStartLoc(),
3688 Operand->getNameLen()));
3690 InputDecls.push_back(OpDecl);
3691 InputConstraints.push_back(Operand->getConstraint().str());
3692 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
3693 Operand->getStartLoc(),
3694 Operand->getNameLen()));
3698 // Free any parsed operands.
3699 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
3700 delete ParsedOperands[i];
3701 ParsedOperands.clear();
3705 // Set the number of Outputs and Inputs.
3706 NumOutputs = OutputDecls.size();
3707 NumInputs = InputDecls.size();
3709 // Set the unique clobbers.
3710 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3711 E = ClobberRegs.end(); I != E; ++I)
3712 Clobbers.push_back(*I);
3714 // Merge the various outputs and inputs. Output are expected first.
3715 if (NumOutputs || NumInputs) {
3716 unsigned NumExprs = NumOutputs + NumInputs;
3717 OpDecls.resize(NumExprs);
3718 Constraints.resize(NumExprs);
3719 for (unsigned i = 0; i < NumOutputs; ++i) {
3720 OpDecls[i] = OutputDecls[i];
3721 Constraints[i] = OutputConstraints[i];
3723 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
3724 OpDecls[j] = InputDecls[i];
3725 Constraints[j] = InputConstraints[i];
3729 // Build the IR assembly string.
3730 std::string AsmStringIR;
3731 AsmRewriteKind PrevKind = AOK_Imm;
3732 raw_string_ostream OS(AsmStringIR);
3733 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
3734 for (SmallVectorImpl<struct AsmRewrite>::iterator
3735 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3736 const char *Loc = (*I).Loc.getPointer();
3738 AsmRewriteKind Kind = (*I).Kind;
3740 // Emit everything up to the immediate/expression. If the previous rewrite
3741 // was a size directive, then this has already been done.
3742 if (PrevKind != AOK_SizeDirective)
3743 OS << StringRef(Start, Loc - Start);
3746 // Skip the original expression.
3747 if (Kind == AOK_Skip) {
3748 Start = Loc + (*I).Len;
3752 // Rewrite expressions in $N notation.
3756 OS << Twine("$$") + StringRef(Loc, (*I).Len);
3766 case AOK_SizeDirective:
3769 case 8: OS << "byte ptr "; break;
3770 case 16: OS << "word ptr "; break;
3771 case 32: OS << "dword ptr "; break;
3772 case 64: OS << "qword ptr "; break;
3773 case 80: OS << "xword ptr "; break;
3774 case 128: OS << "xmmword ptr "; break;
3775 case 256: OS << "ymmword ptr "; break;
3779 // Skip the original expression.
3780 if (Kind != AOK_SizeDirective)
3781 Start = Loc + (*I).Len;
3784 // Emit the remainder of the asm string.
3785 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3786 if (Start != AsmEnd)
3787 OS << StringRef(Start, AsmEnd - Start);
3789 AsmString = OS.str();
3793 /// \brief Create an MCAsmParser instance.
3794 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3795 MCContext &C, MCStreamer &Out,
3796 const MCAsmInfo &MAI) {
3797 return new AsmParser(SM, C, Out, MAI);