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,
90 struct ParseStatementInfo {
91 /// ParsedOperands - The parsed operands from the last parsed statement.
92 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
94 /// Opcode - The opcode from the last parsed instruction.
97 SmallVectorImpl<AsmRewrite> *AsmRewrites;
99 ParseStatementInfo() : Opcode(~0U), AsmRewrites(0) {}
100 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
101 : Opcode(~0), AsmRewrites(rewrites) {}
103 ~ParseStatementInfo() {
104 // Free any parsed operands.
105 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
106 delete ParsedOperands[i];
107 ParsedOperands.clear();
111 /// \brief The concrete assembly parser instance.
112 class AsmParser : public MCAsmParser {
113 friend class GenericAsmParser;
115 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
116 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
121 const MCAsmInfo &MAI;
123 SourceMgr::DiagHandlerTy SavedDiagHandler;
124 void *SavedDiagContext;
125 MCAsmParserExtension *GenericParser;
126 MCAsmParserExtension *PlatformParser;
128 /// This is the current buffer index we're lexing from as managed by the
129 /// SourceMgr object.
132 AsmCond TheCondState;
133 std::vector<AsmCond> TheCondStack;
135 /// DirectiveMap - This is a table handlers for directives. Each handler is
136 /// invoked after the directive identifier is read and is responsible for
137 /// parsing and validating the rest of the directive. The handler is passed
138 /// in the directive name and the location of the directive keyword.
139 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
141 /// MacroMap - Map of currently defined macros.
142 StringMap<Macro*> MacroMap;
144 /// ActiveMacros - Stack of active macro instantiations.
145 std::vector<MacroInstantiation*> ActiveMacros;
147 /// Boolean tracking whether macro substitution is enabled.
148 unsigned MacrosEnabled : 1;
150 /// Flag tracking whether any errors have been encountered.
151 unsigned HadError : 1;
153 /// The values from the last parsed cpp hash file line comment if any.
154 StringRef CppHashFilename;
155 int64_t CppHashLineNumber;
159 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
160 unsigned AssemblerDialect;
162 /// IsDarwin - is Darwin compatibility enabled?
165 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
166 bool ParsingInlineAsm;
169 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
170 const MCAsmInfo &MAI);
171 virtual ~AsmParser();
173 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
175 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
177 DirectiveHandler Handler) {
178 DirectiveMap[Directive] = std::make_pair(Object, Handler);
182 /// @name MCAsmParser Interface
185 virtual SourceMgr &getSourceManager() { return SrcMgr; }
186 virtual MCAsmLexer &getLexer() { return Lexer; }
187 virtual MCContext &getContext() { return Ctx; }
188 virtual MCStreamer &getStreamer() { return Out; }
189 virtual unsigned getAssemblerDialect() {
190 if (AssemblerDialect == ~0U)
191 return MAI.getAssemblerDialect();
193 return AssemblerDialect;
195 virtual void setAssemblerDialect(unsigned i) {
196 AssemblerDialect = i;
199 virtual bool Warning(SMLoc L, const Twine &Msg,
200 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
201 virtual bool Error(SMLoc L, const Twine &Msg,
202 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
204 virtual const AsmToken &Lex();
206 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
207 bool isParsingInlineAsm() { return ParsingInlineAsm; }
209 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
210 unsigned &NumOutputs, unsigned &NumInputs,
211 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
212 SmallVectorImpl<std::string> &Constraints,
213 SmallVectorImpl<std::string> &Clobbers,
214 const MCInstrInfo *MII,
215 const MCInstPrinter *IP,
216 MCAsmParserSemaCallback &SI);
218 bool ParseExpression(const MCExpr *&Res);
219 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
220 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
221 virtual bool ParseAbsoluteExpression(int64_t &Res);
226 void CheckForValidSection();
228 bool ParseStatement(ParseStatementInfo &Info);
229 void EatToEndOfLine();
230 bool ParseCppHashLineFilenameComment(const SMLoc &L);
232 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
233 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
234 const MacroParameters &Parameters,
235 const MacroArguments &A,
237 void HandleMacroExit();
239 void PrintMacroInstantiations();
240 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
241 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
242 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
244 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
246 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
247 bool EnterIncludeFile(const std::string &Filename);
248 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
249 /// This returns true on failure.
250 bool ProcessIncbinFile(const std::string &Filename);
252 /// \brief Reset the current lexer position to that given by \p Loc. The
253 /// current token is not set; clients should ensure Lex() is called
255 void JumpToLoc(SMLoc Loc);
257 virtual void EatToEndOfStatement();
259 bool ParseMacroArgument(MacroArgument &MA,
260 AsmToken::TokenKind &ArgumentDelimiter);
261 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
263 /// \brief Parse up to the end of statement and a return the contents from the
264 /// current token until the end of the statement; the current token on exit
265 /// will be either the EndOfStatement or EOF.
266 virtual StringRef ParseStringToEndOfStatement();
268 /// \brief Parse until the end of a statement or a comma is encountered,
269 /// return the contents from the current token up to the end or comma.
270 StringRef ParseStringToComma();
272 bool ParseAssignment(StringRef Name, bool allow_redef,
273 bool NoDeadStrip = false);
275 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
276 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
277 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
278 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
280 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
281 /// and set \p Res to the identifier contents.
282 virtual bool ParseIdentifier(StringRef &Res);
284 // Directive Parsing.
286 // ".ascii", ".asciiz", ".string"
287 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
288 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
289 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
290 bool ParseDirectiveFill(); // ".fill"
291 bool ParseDirectiveSpace(); // ".space"
292 bool ParseDirectiveZero(); // ".zero"
293 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
294 bool ParseDirectiveOrg(); // ".org"
295 // ".align{,32}", ".p2align{,w,l}"
296 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
298 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
299 /// accepts a single symbol (which should be a label or an external).
300 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
302 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
304 bool ParseDirectiveAbort(); // ".abort"
305 bool ParseDirectiveInclude(); // ".include"
306 bool ParseDirectiveIncbin(); // ".incbin"
308 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
309 // ".ifb" or ".ifnb", depending on ExpectBlank.
310 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
311 // ".ifc" or ".ifnc", depending on ExpectEqual.
312 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
313 // ".ifdef" or ".ifndef", depending on expect_defined
314 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
315 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
316 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
317 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
319 /// ParseEscapedString - Parse the current token as a string which may include
320 /// escaped characters and return the string contents.
321 bool ParseEscapedString(std::string &Data);
323 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
324 MCSymbolRefExpr::VariantKind Variant);
326 // Macro-like directives
327 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
328 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
329 raw_svector_ostream &OS);
330 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
331 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
332 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
333 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
336 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
339 /// \brief Generic implementations of directive handling, etc. which is shared
340 /// (or the default, at least) for all assembler parser.
341 class GenericAsmParser : public MCAsmParserExtension {
342 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
343 void AddDirectiveHandler(StringRef Directive) {
344 getParser().AddDirectiveHandler(this, Directive,
345 HandleDirective<GenericAsmParser, Handler>);
348 GenericAsmParser() {}
350 AsmParser &getParser() {
351 return (AsmParser&) this->MCAsmParserExtension::getParser();
354 virtual void Initialize(MCAsmParser &Parser) {
355 // Call the base implementation.
356 this->MCAsmParserExtension::Initialize(Parser);
358 // Debugging directives.
359 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
360 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
361 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
362 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
365 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
367 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
369 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
371 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
373 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
374 ".cfi_def_cfa_offset");
375 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
376 ".cfi_adjust_cfa_offset");
377 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
378 ".cfi_def_cfa_register");
379 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
381 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
384 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
386 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
388 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
390 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
392 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
394 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
396 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
398 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
401 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
403 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
405 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
406 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
407 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
408 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
410 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
411 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
414 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
416 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
417 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
418 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
419 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
420 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
421 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
422 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
423 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
424 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
425 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
426 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
427 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
428 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
429 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
430 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
431 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
432 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
433 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
434 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
435 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
437 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
438 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
439 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
440 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
442 bool ParseDirectiveLEB128(StringRef, SMLoc);
449 extern MCAsmParserExtension *createDarwinAsmParser();
450 extern MCAsmParserExtension *createELFAsmParser();
451 extern MCAsmParserExtension *createCOFFAsmParser();
455 enum { DEFAULT_ADDRSPACE = 0 };
457 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
458 MCStreamer &_Out, const MCAsmInfo &_MAI)
459 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
460 GenericParser(new GenericAsmParser), PlatformParser(0),
461 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
462 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
463 // Save the old handler.
464 SavedDiagHandler = SrcMgr.getDiagHandler();
465 SavedDiagContext = SrcMgr.getDiagContext();
466 // Set our own handler which calls the saved handler.
467 SrcMgr.setDiagHandler(DiagHandler, this);
468 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
470 // Initialize the generic parser.
471 GenericParser->Initialize(*this);
473 // Initialize the platform / file format parser.
475 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
477 if (_MAI.hasMicrosoftFastStdCallMangling()) {
478 PlatformParser = createCOFFAsmParser();
479 PlatformParser->Initialize(*this);
480 } else if (_MAI.hasSubsectionsViaSymbols()) {
481 PlatformParser = createDarwinAsmParser();
482 PlatformParser->Initialize(*this);
485 PlatformParser = createELFAsmParser();
486 PlatformParser->Initialize(*this);
490 AsmParser::~AsmParser() {
491 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
493 // Destroy any macros.
494 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
495 ie = MacroMap.end(); it != ie; ++it)
496 delete it->getValue();
498 delete PlatformParser;
499 delete GenericParser;
502 void AsmParser::PrintMacroInstantiations() {
503 // Print the active macro instantiation stack.
504 for (std::vector<MacroInstantiation*>::const_reverse_iterator
505 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
506 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
507 "while in macro instantiation");
510 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
511 if (FatalAssemblerWarnings)
512 return Error(L, Msg, Ranges);
513 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
514 PrintMacroInstantiations();
518 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
520 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
521 PrintMacroInstantiations();
525 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
526 std::string IncludedFile;
527 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
533 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
538 /// Process the specified .incbin file by seaching for it in the include paths
539 /// then just emitting the byte contents of the file to the streamer. This
540 /// returns true on failure.
541 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
542 std::string IncludedFile;
543 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
547 // Pick up the bytes from the file and emit them.
548 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
553 void AsmParser::JumpToLoc(SMLoc Loc) {
554 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
555 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
558 const AsmToken &AsmParser::Lex() {
559 const AsmToken *tok = &Lexer.Lex();
561 if (tok->is(AsmToken::Eof)) {
562 // If this is the end of an included file, pop the parent file off the
564 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
565 if (ParentIncludeLoc != SMLoc()) {
566 JumpToLoc(ParentIncludeLoc);
571 if (tok->is(AsmToken::Error))
572 Error(Lexer.getErrLoc(), Lexer.getErr());
577 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
578 // Create the initial section, if requested.
579 if (!NoInitialTextSection)
586 AsmCond StartingCondState = TheCondState;
588 // If we are generating dwarf for assembly source files save the initial text
589 // section and generate a .file directive.
590 if (getContext().getGenDwarfForAssembly()) {
591 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
592 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
593 getStreamer().EmitLabel(SectionStartSym);
594 getContext().setGenDwarfSectionStartSym(SectionStartSym);
595 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
596 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
599 // While we have input, parse each statement.
600 while (Lexer.isNot(AsmToken::Eof)) {
601 ParseStatementInfo Info;
602 if (!ParseStatement(Info)) continue;
604 // We had an error, validate that one was emitted and recover by skipping to
606 assert(HadError && "Parse statement returned an error, but none emitted!");
607 EatToEndOfStatement();
610 if (TheCondState.TheCond != StartingCondState.TheCond ||
611 TheCondState.Ignore != StartingCondState.Ignore)
612 return TokError("unmatched .ifs or .elses");
614 // Check to see there are no empty DwarfFile slots.
615 const std::vector<MCDwarfFile *> &MCDwarfFiles =
616 getContext().getMCDwarfFiles();
617 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
618 if (!MCDwarfFiles[i])
619 TokError("unassigned file number: " + Twine(i) + " for .file directives");
622 // Check to see that all assembler local symbols were actually defined.
623 // Targets that don't do subsections via symbols may not want this, though,
624 // so conservatively exclude them. Only do this if we're finalizing, though,
625 // as otherwise we won't necessarilly have seen everything yet.
626 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
627 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
628 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
631 MCSymbol *Sym = i->getValue();
632 // Variable symbols may not be marked as defined, so check those
633 // explicitly. If we know it's a variable, we have a definition for
634 // the purposes of this check.
635 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
636 // FIXME: We would really like to refer back to where the symbol was
637 // first referenced for a source location. We need to add something
638 // to track that. Currently, we just point to the end of the file.
639 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
640 "assembler local symbol '" + Sym->getName() +
646 // Finalize the output stream if there are no errors and if the client wants
648 if (!HadError && !NoFinalize)
654 void AsmParser::CheckForValidSection() {
655 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
656 TokError("expected section directive before assembly directive");
657 Out.SwitchSection(Ctx.getMachOSection(
659 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
660 0, SectionKind::getText()));
664 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
665 void AsmParser::EatToEndOfStatement() {
666 while (Lexer.isNot(AsmToken::EndOfStatement) &&
667 Lexer.isNot(AsmToken::Eof))
671 if (Lexer.is(AsmToken::EndOfStatement))
675 StringRef AsmParser::ParseStringToEndOfStatement() {
676 const char *Start = getTok().getLoc().getPointer();
678 while (Lexer.isNot(AsmToken::EndOfStatement) &&
679 Lexer.isNot(AsmToken::Eof))
682 const char *End = getTok().getLoc().getPointer();
683 return StringRef(Start, End - Start);
686 StringRef AsmParser::ParseStringToComma() {
687 const char *Start = getTok().getLoc().getPointer();
689 while (Lexer.isNot(AsmToken::EndOfStatement) &&
690 Lexer.isNot(AsmToken::Comma) &&
691 Lexer.isNot(AsmToken::Eof))
694 const char *End = getTok().getLoc().getPointer();
695 return StringRef(Start, End - Start);
698 /// ParseParenExpr - Parse a paren expression and return it.
699 /// NOTE: This assumes the leading '(' has already been consumed.
701 /// parenexpr ::= expr)
703 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
704 if (ParseExpression(Res)) return true;
705 if (Lexer.isNot(AsmToken::RParen))
706 return TokError("expected ')' in parentheses expression");
707 EndLoc = Lexer.getLoc();
712 /// ParseBracketExpr - Parse a bracket expression and return it.
713 /// NOTE: This assumes the leading '[' has already been consumed.
715 /// bracketexpr ::= expr]
717 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
718 if (ParseExpression(Res)) return true;
719 if (Lexer.isNot(AsmToken::RBrac))
720 return TokError("expected ']' in brackets expression");
721 EndLoc = Lexer.getLoc();
726 /// ParsePrimaryExpr - Parse a primary expression and return it.
727 /// primaryexpr ::= (parenexpr
728 /// primaryexpr ::= symbol
729 /// primaryexpr ::= number
730 /// primaryexpr ::= '.'
731 /// primaryexpr ::= ~,+,- primaryexpr
732 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
733 switch (Lexer.getKind()) {
735 return TokError("unknown token in expression");
736 // If we have an error assume that we've already handled it.
737 case AsmToken::Error:
739 case AsmToken::Exclaim:
740 Lex(); // Eat the operator.
741 if (ParsePrimaryExpr(Res, EndLoc))
743 Res = MCUnaryExpr::CreateLNot(Res, getContext());
745 case AsmToken::Dollar:
746 case AsmToken::String:
747 case AsmToken::Identifier: {
748 EndLoc = Lexer.getLoc();
750 StringRef Identifier;
751 if (ParseIdentifier(Identifier))
754 // This is a symbol reference.
755 std::pair<StringRef, StringRef> Split = Identifier.split('@');
756 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
758 // Lookup the symbol variant if used.
759 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
760 if (Split.first.size() != Identifier.size()) {
761 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
762 if (Variant == MCSymbolRefExpr::VK_Invalid) {
763 Variant = MCSymbolRefExpr::VK_None;
764 return TokError("invalid variant '" + Split.second + "'");
768 // If this is an absolute variable reference, substitute it now to preserve
769 // semantics in the face of reassignment.
770 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
772 return Error(EndLoc, "unexpected modifier on variable reference");
774 Res = Sym->getVariableValue();
778 // Otherwise create a symbol ref.
779 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
782 case AsmToken::Integer: {
783 SMLoc Loc = getTok().getLoc();
784 int64_t IntVal = getTok().getIntVal();
785 Res = MCConstantExpr::Create(IntVal, getContext());
786 EndLoc = Lexer.getLoc();
788 // Look for 'b' or 'f' following an Integer as a directional label
789 if (Lexer.getKind() == AsmToken::Identifier) {
790 StringRef IDVal = getTok().getString();
791 if (IDVal == "f" || IDVal == "b"){
792 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
793 IDVal == "f" ? 1 : 0);
794 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
796 if (IDVal == "b" && Sym->isUndefined())
797 return Error(Loc, "invalid reference to undefined symbol");
798 EndLoc = Lexer.getLoc();
799 Lex(); // Eat identifier.
804 case AsmToken::Real: {
805 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
806 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
807 Res = MCConstantExpr::Create(IntVal, getContext());
811 case AsmToken::Dot: {
812 // This is a '.' reference, which references the current PC. Emit a
813 // temporary label to the streamer and refer to it.
814 MCSymbol *Sym = Ctx.CreateTempSymbol();
816 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
817 EndLoc = Lexer.getLoc();
818 Lex(); // Eat identifier.
821 case AsmToken::LParen:
822 Lex(); // Eat the '('.
823 return ParseParenExpr(Res, EndLoc);
824 case AsmToken::LBrac:
825 if (!PlatformParser->HasBracketExpressions())
826 return TokError("brackets expression not supported on this target");
827 Lex(); // Eat the '['.
828 return ParseBracketExpr(Res, EndLoc);
829 case AsmToken::Minus:
830 Lex(); // Eat the operator.
831 if (ParsePrimaryExpr(Res, EndLoc))
833 Res = MCUnaryExpr::CreateMinus(Res, getContext());
836 Lex(); // Eat the operator.
837 if (ParsePrimaryExpr(Res, EndLoc))
839 Res = MCUnaryExpr::CreatePlus(Res, getContext());
841 case AsmToken::Tilde:
842 Lex(); // Eat the operator.
843 if (ParsePrimaryExpr(Res, EndLoc))
845 Res = MCUnaryExpr::CreateNot(Res, getContext());
850 bool AsmParser::ParseExpression(const MCExpr *&Res) {
852 return ParseExpression(Res, EndLoc);
856 AsmParser::ApplyModifierToExpr(const MCExpr *E,
857 MCSymbolRefExpr::VariantKind Variant) {
858 // Recurse over the given expression, rebuilding it to apply the given variant
859 // if there is exactly one symbol.
860 switch (E->getKind()) {
862 case MCExpr::Constant:
865 case MCExpr::SymbolRef: {
866 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
868 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
869 TokError("invalid variant on expression '" +
870 getTok().getIdentifier() + "' (already modified)");
874 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
877 case MCExpr::Unary: {
878 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
879 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
882 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
885 case MCExpr::Binary: {
886 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
887 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
888 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
893 if (!LHS) LHS = BE->getLHS();
894 if (!RHS) RHS = BE->getRHS();
896 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
900 llvm_unreachable("Invalid expression kind!");
903 /// ParseExpression - Parse an expression and return it.
905 /// expr ::= expr &&,|| expr -> lowest.
906 /// expr ::= expr |,^,&,! expr
907 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
908 /// expr ::= expr <<,>> expr
909 /// expr ::= expr +,- expr
910 /// expr ::= expr *,/,% expr -> highest.
911 /// expr ::= primaryexpr
913 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
914 // Parse the expression.
916 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
919 // As a special case, we support 'a op b @ modifier' by rewriting the
920 // expression to include the modifier. This is inefficient, but in general we
921 // expect users to use 'a@modifier op b'.
922 if (Lexer.getKind() == AsmToken::At) {
925 if (Lexer.isNot(AsmToken::Identifier))
926 return TokError("unexpected symbol modifier following '@'");
928 MCSymbolRefExpr::VariantKind Variant =
929 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
930 if (Variant == MCSymbolRefExpr::VK_Invalid)
931 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
933 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
935 return TokError("invalid modifier '" + getTok().getIdentifier() +
936 "' (no symbols present)");
943 // Try to constant fold it up front, if possible.
945 if (Res->EvaluateAsAbsolute(Value))
946 Res = MCConstantExpr::Create(Value, getContext());
951 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
953 return ParseParenExpr(Res, EndLoc) ||
954 ParseBinOpRHS(1, Res, EndLoc);
957 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
960 SMLoc StartLoc = Lexer.getLoc();
961 if (ParseExpression(Expr))
964 if (!Expr->EvaluateAsAbsolute(Res))
965 return Error(StartLoc, "expected absolute expression");
970 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
971 MCBinaryExpr::Opcode &Kind) {
974 return 0; // not a binop.
976 // Lowest Precedence: &&, ||
977 case AsmToken::AmpAmp:
978 Kind = MCBinaryExpr::LAnd;
980 case AsmToken::PipePipe:
981 Kind = MCBinaryExpr::LOr;
985 // Low Precedence: |, &, ^
987 // FIXME: gas seems to support '!' as an infix operator?
989 Kind = MCBinaryExpr::Or;
991 case AsmToken::Caret:
992 Kind = MCBinaryExpr::Xor;
995 Kind = MCBinaryExpr::And;
998 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
999 case AsmToken::EqualEqual:
1000 Kind = MCBinaryExpr::EQ;
1002 case AsmToken::ExclaimEqual:
1003 case AsmToken::LessGreater:
1004 Kind = MCBinaryExpr::NE;
1006 case AsmToken::Less:
1007 Kind = MCBinaryExpr::LT;
1009 case AsmToken::LessEqual:
1010 Kind = MCBinaryExpr::LTE;
1012 case AsmToken::Greater:
1013 Kind = MCBinaryExpr::GT;
1015 case AsmToken::GreaterEqual:
1016 Kind = MCBinaryExpr::GTE;
1019 // Intermediate Precedence: <<, >>
1020 case AsmToken::LessLess:
1021 Kind = MCBinaryExpr::Shl;
1023 case AsmToken::GreaterGreater:
1024 Kind = MCBinaryExpr::Shr;
1027 // High Intermediate Precedence: +, -
1028 case AsmToken::Plus:
1029 Kind = MCBinaryExpr::Add;
1031 case AsmToken::Minus:
1032 Kind = MCBinaryExpr::Sub;
1035 // Highest Precedence: *, /, %
1036 case AsmToken::Star:
1037 Kind = MCBinaryExpr::Mul;
1039 case AsmToken::Slash:
1040 Kind = MCBinaryExpr::Div;
1042 case AsmToken::Percent:
1043 Kind = MCBinaryExpr::Mod;
1049 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1050 /// Res contains the LHS of the expression on input.
1051 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1054 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1055 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1057 // If the next token is lower precedence than we are allowed to eat, return
1058 // successfully with what we ate already.
1059 if (TokPrec < Precedence)
1064 // Eat the next primary expression.
1066 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1068 // If BinOp binds less tightly with RHS than the operator after RHS, let
1069 // the pending operator take RHS as its LHS.
1070 MCBinaryExpr::Opcode Dummy;
1071 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1072 if (TokPrec < NextTokPrec) {
1073 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1076 // Merge LHS and RHS according to operator.
1077 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1082 /// ::= EndOfStatement
1083 /// ::= Label* Directive ...Operands... EndOfStatement
1084 /// ::= Label* Identifier OperandList* EndOfStatement
1085 bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
1086 if (Lexer.is(AsmToken::EndOfStatement)) {
1092 // Statements always start with an identifier or are a full line comment.
1093 AsmToken ID = getTok();
1094 SMLoc IDLoc = ID.getLoc();
1096 int64_t LocalLabelVal = -1;
1097 // A full line comment is a '#' as the first token.
1098 if (Lexer.is(AsmToken::Hash))
1099 return ParseCppHashLineFilenameComment(IDLoc);
1101 // Allow an integer followed by a ':' as a directional local label.
1102 if (Lexer.is(AsmToken::Integer)) {
1103 LocalLabelVal = getTok().getIntVal();
1104 if (LocalLabelVal < 0) {
1105 if (!TheCondState.Ignore)
1106 return TokError("unexpected token at start of statement");
1110 IDVal = getTok().getString();
1111 Lex(); // Consume the integer token to be used as an identifier token.
1112 if (Lexer.getKind() != AsmToken::Colon) {
1113 if (!TheCondState.Ignore)
1114 return TokError("unexpected token at start of statement");
1118 } else if (Lexer.is(AsmToken::Dot)) {
1119 // Treat '.' as a valid identifier in this context.
1123 } else if (ParseIdentifier(IDVal)) {
1124 if (!TheCondState.Ignore)
1125 return TokError("unexpected token at start of statement");
1130 // Handle conditional assembly here before checking for skipping. We
1131 // have to do this so that .endif isn't skipped in a ".if 0" block for
1134 return ParseDirectiveIf(IDLoc);
1135 if (IDVal == ".ifb")
1136 return ParseDirectiveIfb(IDLoc, true);
1137 if (IDVal == ".ifnb")
1138 return ParseDirectiveIfb(IDLoc, false);
1139 if (IDVal == ".ifc")
1140 return ParseDirectiveIfc(IDLoc, true);
1141 if (IDVal == ".ifnc")
1142 return ParseDirectiveIfc(IDLoc, false);
1143 if (IDVal == ".ifdef")
1144 return ParseDirectiveIfdef(IDLoc, true);
1145 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1146 return ParseDirectiveIfdef(IDLoc, false);
1147 if (IDVal == ".elseif")
1148 return ParseDirectiveElseIf(IDLoc);
1149 if (IDVal == ".else")
1150 return ParseDirectiveElse(IDLoc);
1151 if (IDVal == ".endif")
1152 return ParseDirectiveEndIf(IDLoc);
1154 // If we are in a ".if 0" block, ignore this statement.
1155 if (TheCondState.Ignore) {
1156 EatToEndOfStatement();
1160 // FIXME: Recurse on local labels?
1162 // See what kind of statement we have.
1163 switch (Lexer.getKind()) {
1164 case AsmToken::Colon: {
1165 CheckForValidSection();
1167 // identifier ':' -> Label.
1170 // Diagnose attempt to use '.' as a label.
1172 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1174 // Diagnose attempt to use a variable as a label.
1176 // FIXME: Diagnostics. Note the location of the definition as a label.
1177 // FIXME: This doesn't diagnose assignment to a symbol which has been
1178 // implicitly marked as external.
1180 if (LocalLabelVal == -1)
1181 Sym = getContext().GetOrCreateSymbol(IDVal);
1183 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1184 if (!Sym->isUndefined() || Sym->isVariable())
1185 return Error(IDLoc, "invalid symbol redefinition");
1190 // If we are generating dwarf for assembly source files then gather the
1191 // info to make a dwarf label entry for this label if needed.
1192 if (getContext().getGenDwarfForAssembly())
1193 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1196 // Consume any end of statement token, if present, to avoid spurious
1197 // AddBlankLine calls().
1198 if (Lexer.is(AsmToken::EndOfStatement)) {
1200 if (Lexer.is(AsmToken::Eof))
1207 case AsmToken::Equal:
1208 // identifier '=' ... -> assignment statement
1211 return ParseAssignment(IDVal, true);
1213 default: // Normal instruction or directive.
1217 // If macros are enabled, check to see if this is a macro instantiation.
1219 if (const Macro *M = MacroMap.lookup(IDVal))
1220 return HandleMacroEntry(IDVal, IDLoc, M);
1222 // Otherwise, we have a normal instruction or directive.
1223 if (IDVal[0] == '.' && IDVal != ".") {
1225 // Target hook for parsing target specific directives.
1226 if (!getTargetParser().ParseDirective(ID))
1229 // Assembler features
1230 if (IDVal == ".set" || IDVal == ".equ")
1231 return ParseDirectiveSet(IDVal, true);
1232 if (IDVal == ".equiv")
1233 return ParseDirectiveSet(IDVal, false);
1237 if (IDVal == ".ascii")
1238 return ParseDirectiveAscii(IDVal, false);
1239 if (IDVal == ".asciz" || IDVal == ".string")
1240 return ParseDirectiveAscii(IDVal, true);
1242 if (IDVal == ".byte")
1243 return ParseDirectiveValue(1);
1244 if (IDVal == ".short")
1245 return ParseDirectiveValue(2);
1246 if (IDVal == ".value")
1247 return ParseDirectiveValue(2);
1248 if (IDVal == ".2byte")
1249 return ParseDirectiveValue(2);
1250 if (IDVal == ".long")
1251 return ParseDirectiveValue(4);
1252 if (IDVal == ".int")
1253 return ParseDirectiveValue(4);
1254 if (IDVal == ".4byte")
1255 return ParseDirectiveValue(4);
1256 if (IDVal == ".quad")
1257 return ParseDirectiveValue(8);
1258 if (IDVal == ".8byte")
1259 return ParseDirectiveValue(8);
1260 if (IDVal == ".single" || IDVal == ".float")
1261 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1262 if (IDVal == ".double")
1263 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1265 if (IDVal == ".align") {
1266 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1267 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1269 if (IDVal == ".align32") {
1270 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1271 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1273 if (IDVal == ".balign")
1274 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1275 if (IDVal == ".balignw")
1276 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1277 if (IDVal == ".balignl")
1278 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1279 if (IDVal == ".p2align")
1280 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1281 if (IDVal == ".p2alignw")
1282 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1283 if (IDVal == ".p2alignl")
1284 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1286 if (IDVal == ".org")
1287 return ParseDirectiveOrg();
1289 if (IDVal == ".fill")
1290 return ParseDirectiveFill();
1291 if (IDVal == ".space" || IDVal == ".skip")
1292 return ParseDirectiveSpace();
1293 if (IDVal == ".zero")
1294 return ParseDirectiveZero();
1296 // Symbol attribute directives
1298 if (IDVal == ".extern") {
1299 EatToEndOfStatement(); // .extern is the default, ignore it.
1302 if (IDVal == ".globl" || IDVal == ".global")
1303 return ParseDirectiveSymbolAttribute(MCSA_Global);
1304 if (IDVal == ".indirect_symbol")
1305 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1306 if (IDVal == ".lazy_reference")
1307 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1308 if (IDVal == ".no_dead_strip")
1309 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1310 if (IDVal == ".symbol_resolver")
1311 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1312 if (IDVal == ".private_extern")
1313 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1314 if (IDVal == ".reference")
1315 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1316 if (IDVal == ".weak_definition")
1317 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1318 if (IDVal == ".weak_reference")
1319 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1320 if (IDVal == ".weak_def_can_be_hidden")
1321 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1323 if (IDVal == ".comm" || IDVal == ".common")
1324 return ParseDirectiveComm(/*IsLocal=*/false);
1325 if (IDVal == ".lcomm")
1326 return ParseDirectiveComm(/*IsLocal=*/true);
1328 if (IDVal == ".abort")
1329 return ParseDirectiveAbort();
1330 if (IDVal == ".include")
1331 return ParseDirectiveInclude();
1332 if (IDVal == ".incbin")
1333 return ParseDirectiveIncbin();
1335 if (IDVal == ".code16" || IDVal == ".code16gcc")
1336 return TokError(Twine(IDVal) + " not supported yet");
1338 // Macro-like directives
1339 if (IDVal == ".rept")
1340 return ParseDirectiveRept(IDLoc);
1341 if (IDVal == ".irp")
1342 return ParseDirectiveIrp(IDLoc);
1343 if (IDVal == ".irpc")
1344 return ParseDirectiveIrpc(IDLoc);
1345 if (IDVal == ".endr")
1346 return ParseDirectiveEndr(IDLoc);
1348 // Look up the handler in the handler table.
1349 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1350 DirectiveMap.lookup(IDVal);
1352 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1355 return Error(IDLoc, "unknown directive");
1359 if (ParsingInlineAsm && IDVal == "_emit")
1360 return ParseDirectiveEmit(IDLoc, Info);
1362 CheckForValidSection();
1364 // Canonicalize the opcode to lower case.
1365 SmallString<128> OpcodeStr;
1366 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1367 OpcodeStr.push_back(tolower(IDVal[i]));
1369 ParseInstructionInfo IInfo(Info.AsmRewrites);
1370 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1371 IDLoc,Info.ParsedOperands);
1373 // Dump the parsed representation, if requested.
1374 if (getShowParsedOperands()) {
1375 SmallString<256> Str;
1376 raw_svector_ostream OS(Str);
1377 OS << "parsed instruction: [";
1378 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1381 Info.ParsedOperands[i]->print(OS);
1385 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1388 // If we are generating dwarf for assembly source files and the current
1389 // section is the initial text section then generate a .loc directive for
1391 if (!HadError && getContext().getGenDwarfForAssembly() &&
1392 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1394 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1396 // If we previously parsed a cpp hash file line comment then make sure the
1397 // current Dwarf File is for the CppHashFilename if not then emit the
1398 // Dwarf File table for it and adjust the line number for the .loc.
1399 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1400 getContext().getMCDwarfFiles();
1401 if (CppHashFilename.size() != 0) {
1402 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1404 getStreamer().EmitDwarfFileDirective(
1405 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1407 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
1408 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1411 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1412 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1413 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1417 // If parsing succeeded, match the instruction.
1420 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1421 Info.ParsedOperands,
1426 // Don't skip the rest of the line, the instruction parser is responsible for
1431 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1432 /// since they may not be able to be tokenized to get to the end of line token.
1433 void AsmParser::EatToEndOfLine() {
1434 if (!Lexer.is(AsmToken::EndOfStatement))
1435 Lexer.LexUntilEndOfLine();
1440 /// ParseCppHashLineFilenameComment as this:
1441 /// ::= # number "filename"
1442 /// or just as a full line comment if it doesn't have a number and a string.
1443 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1444 Lex(); // Eat the hash token.
1446 if (getLexer().isNot(AsmToken::Integer)) {
1447 // Consume the line since in cases it is not a well-formed line directive,
1448 // as if were simply a full line comment.
1453 int64_t LineNumber = getTok().getIntVal();
1456 if (getLexer().isNot(AsmToken::String)) {
1461 StringRef Filename = getTok().getString();
1462 // Get rid of the enclosing quotes.
1463 Filename = Filename.substr(1, Filename.size()-2);
1465 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1467 CppHashFilename = Filename;
1468 CppHashLineNumber = LineNumber;
1469 CppHashBuf = CurBuffer;
1471 // Ignore any trailing characters, they're just comment.
1476 /// DiagHandler - will use the last parsed cpp hash line filename comment
1477 /// for the Filename and LineNo if any in the diagnostic.
1478 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1479 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1480 raw_ostream &OS = errs();
1482 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1483 const SMLoc &DiagLoc = Diag.getLoc();
1484 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1485 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1487 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1488 // before printing the message.
1489 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1490 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1491 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1492 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1495 // If we have not parsed a cpp hash line filename comment or the source
1496 // manager changed or buffer changed (like in a nested include) then just
1497 // print the normal diagnostic using its Filename and LineNo.
1498 if (!Parser->CppHashLineNumber ||
1499 &DiagSrcMgr != &Parser->SrcMgr ||
1500 DiagBuf != CppHashBuf) {
1501 if (Parser->SavedDiagHandler)
1502 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1508 // Use the CppHashFilename and calculate a line number based on the
1509 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1511 const std::string Filename = Parser->CppHashFilename;
1513 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1514 int CppHashLocLineNo =
1515 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1516 int LineNo = Parser->CppHashLineNumber - 1 +
1517 (DiagLocLineNo - CppHashLocLineNo);
1519 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1520 Filename, LineNo, Diag.getColumnNo(),
1521 Diag.getKind(), Diag.getMessage(),
1522 Diag.getLineContents(), Diag.getRanges());
1524 if (Parser->SavedDiagHandler)
1525 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1527 NewDiag.print(0, OS);
1530 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1531 // difference being that that function accepts '@' as part of identifiers and
1532 // we can't do that. AsmLexer.cpp should probably be changed to handle
1533 // '@' as a special case when needed.
1534 static bool isIdentifierChar(char c) {
1535 return isalnum(c) || c == '_' || c == '$' || c == '.';
1538 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1539 const MacroParameters &Parameters,
1540 const MacroArguments &A,
1542 unsigned NParameters = Parameters.size();
1543 if (NParameters != 0 && NParameters != A.size())
1544 return Error(L, "Wrong number of arguments");
1546 // A macro without parameters is handled differently on Darwin:
1547 // gas accepts no arguments and does no substitutions
1548 while (!Body.empty()) {
1549 // Scan for the next substitution.
1550 std::size_t End = Body.size(), Pos = 0;
1551 for (; Pos != End; ++Pos) {
1552 // Check for a substitution or escape.
1554 // This macro has no parameters, look for $0, $1, etc.
1555 if (Body[Pos] != '$' || Pos + 1 == End)
1558 char Next = Body[Pos + 1];
1559 if (Next == '$' || Next == 'n' || isdigit(Next))
1562 // This macro has parameters, look for \foo, \bar, etc.
1563 if (Body[Pos] == '\\' && Pos + 1 != End)
1569 OS << Body.slice(0, Pos);
1571 // Check if we reached the end.
1576 switch (Body[Pos+1]) {
1582 // $n => number of arguments
1587 // $[0-9] => argument
1589 // Missing arguments are ignored.
1590 unsigned Index = Body[Pos+1] - '0';
1591 if (Index >= A.size())
1594 // Otherwise substitute with the token values, with spaces eliminated.
1595 for (MacroArgument::const_iterator it = A[Index].begin(),
1596 ie = A[Index].end(); it != ie; ++it)
1597 OS << it->getString();
1603 unsigned I = Pos + 1;
1604 while (isIdentifierChar(Body[I]) && I + 1 != End)
1607 const char *Begin = Body.data() + Pos +1;
1608 StringRef Argument(Begin, I - (Pos +1));
1610 for (; Index < NParameters; ++Index)
1611 if (Parameters[Index].first == Argument)
1614 if (Index == NParameters) {
1615 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1618 OS << '\\' << Argument;
1622 for (MacroArgument::const_iterator it = A[Index].begin(),
1623 ie = A[Index].end(); it != ie; ++it)
1624 if (it->getKind() == AsmToken::String)
1625 OS << it->getStringContents();
1627 OS << it->getString();
1629 Pos += 1 + Argument.size();
1632 // Update the scan point.
1633 Body = Body.substr(Pos);
1639 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1641 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1645 static bool IsOperator(AsmToken::TokenKind kind)
1651 case AsmToken::Plus:
1652 case AsmToken::Minus:
1653 case AsmToken::Tilde:
1654 case AsmToken::Slash:
1655 case AsmToken::Star:
1657 case AsmToken::Equal:
1658 case AsmToken::EqualEqual:
1659 case AsmToken::Pipe:
1660 case AsmToken::PipePipe:
1661 case AsmToken::Caret:
1663 case AsmToken::AmpAmp:
1664 case AsmToken::Exclaim:
1665 case AsmToken::ExclaimEqual:
1666 case AsmToken::Percent:
1667 case AsmToken::Less:
1668 case AsmToken::LessEqual:
1669 case AsmToken::LessLess:
1670 case AsmToken::LessGreater:
1671 case AsmToken::Greater:
1672 case AsmToken::GreaterEqual:
1673 case AsmToken::GreaterGreater:
1678 /// ParseMacroArgument - Extract AsmTokens for a macro argument.
1679 /// This is used for both default macro parameter values and the
1680 /// arguments in macro invocations
1681 bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1682 AsmToken::TokenKind &ArgumentDelimiter) {
1683 unsigned ParenLevel = 0;
1684 unsigned AddTokens = 0;
1686 // gas accepts arguments separated by whitespace, except on Darwin
1688 Lexer.setSkipSpace(false);
1691 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1692 Lexer.setSkipSpace(true);
1693 return TokError("unexpected token in macro instantiation");
1696 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1697 // Spaces and commas cannot be mixed to delimit parameters
1698 if (ArgumentDelimiter == AsmToken::Eof)
1699 ArgumentDelimiter = AsmToken::Comma;
1700 else if (ArgumentDelimiter != AsmToken::Comma) {
1701 Lexer.setSkipSpace(true);
1702 return TokError("expected ' ' for macro argument separator");
1707 if (Lexer.is(AsmToken::Space)) {
1708 Lex(); // Eat spaces
1710 // Spaces can delimit parameters, but could also be part an expression.
1711 // If the token after a space is an operator, add the token and the next
1712 // one into this argument
1713 if (ArgumentDelimiter == AsmToken::Space ||
1714 ArgumentDelimiter == AsmToken::Eof) {
1715 if (IsOperator(Lexer.getKind())) {
1716 // Check to see whether the token is used as an operator,
1717 // or part of an identifier
1718 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1719 if (*NextChar == ' ')
1723 if (!AddTokens && ParenLevel == 0) {
1724 if (ArgumentDelimiter == AsmToken::Eof &&
1725 !IsOperator(Lexer.getKind()))
1726 ArgumentDelimiter = AsmToken::Space;
1732 // HandleMacroEntry relies on not advancing the lexer here
1733 // to be able to fill in the remaining default parameter values
1734 if (Lexer.is(AsmToken::EndOfStatement))
1737 // Adjust the current parentheses level.
1738 if (Lexer.is(AsmToken::LParen))
1740 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1743 // Append the token to the current argument list.
1744 MA.push_back(getTok());
1750 Lexer.setSkipSpace(true);
1751 if (ParenLevel != 0)
1752 return TokError("unbalanced parentheses in macro argument");
1756 // Parse the macro instantiation arguments.
1757 bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
1758 const unsigned NParameters = M ? M->Parameters.size() : 0;
1759 // Argument delimiter is initially unknown. It will be set by
1760 // ParseMacroArgument()
1761 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1763 // Parse two kinds of macro invocations:
1764 // - macros defined without any parameters accept an arbitrary number of them
1765 // - macros defined with parameters accept at most that many of them
1766 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1770 if (ParseMacroArgument(MA, ArgumentDelimiter))
1773 if (!MA.empty() || !NParameters)
1775 else if (NParameters) {
1776 if (!M->Parameters[Parameter].second.empty())
1777 A.push_back(M->Parameters[Parameter].second);
1780 // At the end of the statement, fill in remaining arguments that have
1781 // default values. If there aren't any, then the next argument is
1782 // required but missing
1783 if (Lexer.is(AsmToken::EndOfStatement)) {
1784 if (NParameters && Parameter < NParameters - 1) {
1785 if (M->Parameters[Parameter + 1].second.empty())
1786 return TokError("macro argument '" +
1787 Twine(M->Parameters[Parameter + 1].first) +
1795 if (Lexer.is(AsmToken::Comma))
1798 return TokError("Too many arguments");
1801 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1803 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1804 // this, although we should protect against infinite loops.
1805 if (ActiveMacros.size() == 20)
1806 return TokError("macros cannot be nested more than 20 levels deep");
1809 if (ParseMacroArguments(M, A))
1812 // Remove any trailing empty arguments. Do this after-the-fact as we have
1813 // to keep empty arguments in the middle of the list or positionality
1814 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1815 while (!A.empty() && A.back().empty())
1818 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1819 // to hold the macro body with substitutions.
1820 SmallString<256> Buf;
1821 StringRef Body = M->Body;
1822 raw_svector_ostream OS(Buf);
1824 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1827 // We include the .endmacro in the buffer as our queue to exit the macro
1829 OS << ".endmacro\n";
1831 MemoryBuffer *Instantiation =
1832 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1834 // Create the macro instantiation object and add to the current macro
1835 // instantiation stack.
1836 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1839 ActiveMacros.push_back(MI);
1841 // Jump to the macro instantiation and prime the lexer.
1842 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1843 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1849 void AsmParser::HandleMacroExit() {
1850 // Jump to the EndOfStatement we should return to, and consume it.
1851 JumpToLoc(ActiveMacros.back()->ExitLoc);
1854 // Pop the instantiation entry.
1855 delete ActiveMacros.back();
1856 ActiveMacros.pop_back();
1859 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1860 switch (Value->getKind()) {
1861 case MCExpr::Binary: {
1862 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1863 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1866 case MCExpr::Target:
1867 case MCExpr::Constant:
1869 case MCExpr::SymbolRef: {
1870 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1872 return IsUsedIn(Sym, S.getVariableValue());
1876 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1879 llvm_unreachable("Unknown expr kind!");
1882 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1884 // FIXME: Use better location, we should use proper tokens.
1885 SMLoc EqualLoc = Lexer.getLoc();
1887 const MCExpr *Value;
1888 if (ParseExpression(Value))
1891 // Note: we don't count b as used in "a = b". This is to allow
1895 if (Lexer.isNot(AsmToken::EndOfStatement))
1896 return TokError("unexpected token in assignment");
1898 // Error on assignment to '.'.
1900 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1901 "(use '.space' or '.org').)"));
1904 // Eat the end of statement marker.
1907 // Validate that the LHS is allowed to be a variable (either it has not been
1908 // used as a symbol, or it is an absolute symbol).
1909 MCSymbol *Sym = getContext().LookupSymbol(Name);
1911 // Diagnose assignment to a label.
1913 // FIXME: Diagnostics. Note the location of the definition as a label.
1914 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1915 if (IsUsedIn(Sym, Value))
1916 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1917 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1918 ; // Allow redefinitions of undefined symbols only used in directives.
1919 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1920 ; // Allow redefinitions of variables that haven't yet been used.
1921 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1922 return Error(EqualLoc, "redefinition of '" + Name + "'");
1923 else if (!Sym->isVariable())
1924 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1925 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1926 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1929 // Don't count these checks as uses.
1930 Sym->setUsed(false);
1932 Sym = getContext().GetOrCreateSymbol(Name);
1934 // FIXME: Handle '.'.
1936 // Do the assignment.
1937 Out.EmitAssignment(Sym, Value);
1939 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1945 /// ParseIdentifier:
1948 bool AsmParser::ParseIdentifier(StringRef &Res) {
1949 // The assembler has relaxed rules for accepting identifiers, in particular we
1950 // allow things like '.globl $foo', which would normally be separate
1951 // tokens. At this level, we have already lexed so we cannot (currently)
1952 // handle this as a context dependent token, instead we detect adjacent tokens
1953 // and return the combined identifier.
1954 if (Lexer.is(AsmToken::Dollar)) {
1955 SMLoc DollarLoc = getLexer().getLoc();
1957 // Consume the dollar sign, and check for a following identifier.
1959 if (Lexer.isNot(AsmToken::Identifier))
1962 // We have a '$' followed by an identifier, make sure they are adjacent.
1963 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1966 // Construct the joined identifier and consume the token.
1967 Res = StringRef(DollarLoc.getPointer(),
1968 getTok().getIdentifier().size() + 1);
1973 if (Lexer.isNot(AsmToken::Identifier) &&
1974 Lexer.isNot(AsmToken::String))
1977 Res = getTok().getIdentifier();
1979 Lex(); // Consume the identifier token.
1984 /// ParseDirectiveSet:
1985 /// ::= .equ identifier ',' expression
1986 /// ::= .equiv identifier ',' expression
1987 /// ::= .set identifier ',' expression
1988 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1991 if (ParseIdentifier(Name))
1992 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1994 if (getLexer().isNot(AsmToken::Comma))
1995 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1998 return ParseAssignment(Name, allow_redef, true);
2001 bool AsmParser::ParseEscapedString(std::string &Data) {
2002 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2005 StringRef Str = getTok().getStringContents();
2006 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2007 if (Str[i] != '\\') {
2012 // Recognize escaped characters. Note that this escape semantics currently
2013 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2016 return TokError("unexpected backslash at end of string");
2018 // Recognize octal sequences.
2019 if ((unsigned) (Str[i] - '0') <= 7) {
2020 // Consume up to three octal characters.
2021 unsigned Value = Str[i] - '0';
2023 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2025 Value = Value * 8 + (Str[i] - '0');
2027 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2029 Value = Value * 8 + (Str[i] - '0');
2034 return TokError("invalid octal escape sequence (out of range)");
2036 Data += (unsigned char) Value;
2040 // Otherwise recognize individual escapes.
2043 // Just reject invalid escape sequences for now.
2044 return TokError("invalid escape sequence (unrecognized character)");
2046 case 'b': Data += '\b'; break;
2047 case 'f': Data += '\f'; break;
2048 case 'n': Data += '\n'; break;
2049 case 'r': Data += '\r'; break;
2050 case 't': Data += '\t'; break;
2051 case '"': Data += '"'; break;
2052 case '\\': Data += '\\'; break;
2059 /// ParseDirectiveAscii:
2060 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2061 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2062 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2063 CheckForValidSection();
2066 if (getLexer().isNot(AsmToken::String))
2067 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2070 if (ParseEscapedString(Data))
2073 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2075 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2079 if (getLexer().is(AsmToken::EndOfStatement))
2082 if (getLexer().isNot(AsmToken::Comma))
2083 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2092 /// ParseDirectiveValue
2093 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2094 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2095 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2096 CheckForValidSection();
2099 const MCExpr *Value;
2100 SMLoc ExprLoc = getLexer().getLoc();
2101 if (ParseExpression(Value))
2104 // Special case constant expressions to match code generator.
2105 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2106 assert(Size <= 8 && "Invalid size");
2107 uint64_t IntValue = MCE->getValue();
2108 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2109 return Error(ExprLoc, "literal value out of range for directive");
2110 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2112 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2114 if (getLexer().is(AsmToken::EndOfStatement))
2117 // FIXME: Improve diagnostic.
2118 if (getLexer().isNot(AsmToken::Comma))
2119 return TokError("unexpected token in directive");
2128 /// ParseDirectiveRealValue
2129 /// ::= (.single | .double) [ expression (, expression)* ]
2130 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2131 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2132 CheckForValidSection();
2135 // We don't truly support arithmetic on floating point expressions, so we
2136 // have to manually parse unary prefixes.
2138 if (getLexer().is(AsmToken::Minus)) {
2141 } else if (getLexer().is(AsmToken::Plus))
2144 if (getLexer().isNot(AsmToken::Integer) &&
2145 getLexer().isNot(AsmToken::Real) &&
2146 getLexer().isNot(AsmToken::Identifier))
2147 return TokError("unexpected token in directive");
2149 // Convert to an APFloat.
2150 APFloat Value(Semantics);
2151 StringRef IDVal = getTok().getString();
2152 if (getLexer().is(AsmToken::Identifier)) {
2153 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2154 Value = APFloat::getInf(Semantics);
2155 else if (!IDVal.compare_lower("nan"))
2156 Value = APFloat::getNaN(Semantics, false, ~0);
2158 return TokError("invalid floating point literal");
2159 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2160 APFloat::opInvalidOp)
2161 return TokError("invalid floating point literal");
2165 // Consume the numeric token.
2168 // Emit the value as an integer.
2169 APInt AsInt = Value.bitcastToAPInt();
2170 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2171 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2173 if (getLexer().is(AsmToken::EndOfStatement))
2176 if (getLexer().isNot(AsmToken::Comma))
2177 return TokError("unexpected token in directive");
2186 /// ParseDirectiveSpace
2187 /// ::= .space expression [ , expression ]
2188 bool AsmParser::ParseDirectiveSpace() {
2189 CheckForValidSection();
2192 if (ParseAbsoluteExpression(NumBytes))
2195 int64_t FillExpr = 0;
2196 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2197 if (getLexer().isNot(AsmToken::Comma))
2198 return TokError("unexpected token in '.space' directive");
2201 if (ParseAbsoluteExpression(FillExpr))
2204 if (getLexer().isNot(AsmToken::EndOfStatement))
2205 return TokError("unexpected token in '.space' directive");
2211 return TokError("invalid number of bytes in '.space' directive");
2213 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
2214 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
2219 /// ParseDirectiveZero
2220 /// ::= .zero expression
2221 bool AsmParser::ParseDirectiveZero() {
2222 CheckForValidSection();
2225 if (ParseAbsoluteExpression(NumBytes))
2229 if (getLexer().is(AsmToken::Comma)) {
2231 if (ParseAbsoluteExpression(Val))
2235 if (getLexer().isNot(AsmToken::EndOfStatement))
2236 return TokError("unexpected token in '.zero' directive");
2240 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2245 /// ParseDirectiveFill
2246 /// ::= .fill expression , expression , expression
2247 bool AsmParser::ParseDirectiveFill() {
2248 CheckForValidSection();
2251 if (ParseAbsoluteExpression(NumValues))
2254 if (getLexer().isNot(AsmToken::Comma))
2255 return TokError("unexpected token in '.fill' directive");
2259 if (ParseAbsoluteExpression(FillSize))
2262 if (getLexer().isNot(AsmToken::Comma))
2263 return TokError("unexpected token in '.fill' directive");
2267 if (ParseAbsoluteExpression(FillExpr))
2270 if (getLexer().isNot(AsmToken::EndOfStatement))
2271 return TokError("unexpected token in '.fill' directive");
2275 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2276 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2278 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2279 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2284 /// ParseDirectiveOrg
2285 /// ::= .org expression [ , expression ]
2286 bool AsmParser::ParseDirectiveOrg() {
2287 CheckForValidSection();
2289 const MCExpr *Offset;
2290 SMLoc Loc = getTok().getLoc();
2291 if (ParseExpression(Offset))
2294 // Parse optional fill expression.
2295 int64_t FillExpr = 0;
2296 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2297 if (getLexer().isNot(AsmToken::Comma))
2298 return TokError("unexpected token in '.org' directive");
2301 if (ParseAbsoluteExpression(FillExpr))
2304 if (getLexer().isNot(AsmToken::EndOfStatement))
2305 return TokError("unexpected token in '.org' directive");
2310 // Only limited forms of relocatable expressions are accepted here, it
2311 // has to be relative to the current section. The streamer will return
2312 // 'true' if the expression wasn't evaluatable.
2313 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2314 return Error(Loc, "expected assembly-time absolute expression");
2319 /// ParseDirectiveAlign
2320 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2321 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2322 CheckForValidSection();
2324 SMLoc AlignmentLoc = getLexer().getLoc();
2326 if (ParseAbsoluteExpression(Alignment))
2330 bool HasFillExpr = false;
2331 int64_t FillExpr = 0;
2332 int64_t MaxBytesToFill = 0;
2333 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2334 if (getLexer().isNot(AsmToken::Comma))
2335 return TokError("unexpected token in directive");
2338 // The fill expression can be omitted while specifying a maximum number of
2339 // alignment bytes, e.g:
2341 if (getLexer().isNot(AsmToken::Comma)) {
2343 if (ParseAbsoluteExpression(FillExpr))
2347 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2348 if (getLexer().isNot(AsmToken::Comma))
2349 return TokError("unexpected token in directive");
2352 MaxBytesLoc = getLexer().getLoc();
2353 if (ParseAbsoluteExpression(MaxBytesToFill))
2356 if (getLexer().isNot(AsmToken::EndOfStatement))
2357 return TokError("unexpected token in directive");
2366 // Compute alignment in bytes.
2368 // FIXME: Diagnose overflow.
2369 if (Alignment >= 32) {
2370 Error(AlignmentLoc, "invalid alignment value");
2374 Alignment = 1ULL << Alignment;
2377 // Diagnose non-sensical max bytes to align.
2378 if (MaxBytesLoc.isValid()) {
2379 if (MaxBytesToFill < 1) {
2380 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2381 "many bytes, ignoring maximum bytes expression");
2385 if (MaxBytesToFill >= Alignment) {
2386 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2392 // Check whether we should use optimal code alignment for this .align
2394 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2395 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2396 ValueSize == 1 && UseCodeAlign) {
2397 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2399 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2400 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2407 /// ParseDirectiveSymbolAttribute
2408 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2409 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2410 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2413 SMLoc Loc = getTok().getLoc();
2415 if (ParseIdentifier(Name))
2416 return Error(Loc, "expected identifier in directive");
2418 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2420 // Assembler local symbols don't make any sense here. Complain loudly.
2421 if (Sym->isTemporary())
2422 return Error(Loc, "non-local symbol required in directive");
2424 getStreamer().EmitSymbolAttribute(Sym, Attr);
2426 if (getLexer().is(AsmToken::EndOfStatement))
2429 if (getLexer().isNot(AsmToken::Comma))
2430 return TokError("unexpected token in directive");
2439 /// ParseDirectiveComm
2440 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2441 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2442 CheckForValidSection();
2444 SMLoc IDLoc = getLexer().getLoc();
2446 if (ParseIdentifier(Name))
2447 return TokError("expected identifier in directive");
2449 // Handle the identifier as the key symbol.
2450 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2452 if (getLexer().isNot(AsmToken::Comma))
2453 return TokError("unexpected token in directive");
2457 SMLoc SizeLoc = getLexer().getLoc();
2458 if (ParseAbsoluteExpression(Size))
2461 int64_t Pow2Alignment = 0;
2462 SMLoc Pow2AlignmentLoc;
2463 if (getLexer().is(AsmToken::Comma)) {
2465 Pow2AlignmentLoc = getLexer().getLoc();
2466 if (ParseAbsoluteExpression(Pow2Alignment))
2469 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2470 if (IsLocal && LCOMM == LCOMM::NoAlignment)
2471 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2473 // If this target takes alignments in bytes (not log) validate and convert.
2474 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2475 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
2476 if (!isPowerOf2_64(Pow2Alignment))
2477 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2478 Pow2Alignment = Log2_64(Pow2Alignment);
2482 if (getLexer().isNot(AsmToken::EndOfStatement))
2483 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2487 // NOTE: a size of zero for a .comm should create a undefined symbol
2488 // but a size of .lcomm creates a bss symbol of size zero.
2490 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2491 "be less than zero");
2493 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2494 // may internally end up wanting an alignment in bytes.
2495 // FIXME: Diagnose overflow.
2496 if (Pow2Alignment < 0)
2497 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2498 "alignment, can't be less than zero");
2500 if (!Sym->isUndefined())
2501 return Error(IDLoc, "invalid symbol redefinition");
2503 // Create the Symbol as a common or local common with Size and Pow2Alignment
2505 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2509 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2513 /// ParseDirectiveAbort
2514 /// ::= .abort [... message ...]
2515 bool AsmParser::ParseDirectiveAbort() {
2516 // FIXME: Use loc from directive.
2517 SMLoc Loc = getLexer().getLoc();
2519 StringRef Str = ParseStringToEndOfStatement();
2520 if (getLexer().isNot(AsmToken::EndOfStatement))
2521 return TokError("unexpected token in '.abort' directive");
2526 Error(Loc, ".abort detected. Assembly stopping.");
2528 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2529 // FIXME: Actually abort assembly here.
2534 /// ParseDirectiveInclude
2535 /// ::= .include "filename"
2536 bool AsmParser::ParseDirectiveInclude() {
2537 if (getLexer().isNot(AsmToken::String))
2538 return TokError("expected string in '.include' directive");
2540 std::string Filename = getTok().getString();
2541 SMLoc IncludeLoc = getLexer().getLoc();
2544 if (getLexer().isNot(AsmToken::EndOfStatement))
2545 return TokError("unexpected token in '.include' directive");
2547 // Strip the quotes.
2548 Filename = Filename.substr(1, Filename.size()-2);
2550 // Attempt to switch the lexer to the included file before consuming the end
2551 // of statement to avoid losing it when we switch.
2552 if (EnterIncludeFile(Filename)) {
2553 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2560 /// ParseDirectiveIncbin
2561 /// ::= .incbin "filename"
2562 bool AsmParser::ParseDirectiveIncbin() {
2563 if (getLexer().isNot(AsmToken::String))
2564 return TokError("expected string in '.incbin' directive");
2566 std::string Filename = getTok().getString();
2567 SMLoc IncbinLoc = getLexer().getLoc();
2570 if (getLexer().isNot(AsmToken::EndOfStatement))
2571 return TokError("unexpected token in '.incbin' directive");
2573 // Strip the quotes.
2574 Filename = Filename.substr(1, Filename.size()-2);
2576 // Attempt to process the included file.
2577 if (ProcessIncbinFile(Filename)) {
2578 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2585 /// ParseDirectiveIf
2586 /// ::= .if expression
2587 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2588 TheCondStack.push_back(TheCondState);
2589 TheCondState.TheCond = AsmCond::IfCond;
2590 if (TheCondState.Ignore) {
2591 EatToEndOfStatement();
2594 if (ParseAbsoluteExpression(ExprValue))
2597 if (getLexer().isNot(AsmToken::EndOfStatement))
2598 return TokError("unexpected token in '.if' directive");
2602 TheCondState.CondMet = ExprValue;
2603 TheCondState.Ignore = !TheCondState.CondMet;
2609 /// ParseDirectiveIfb
2611 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2612 TheCondStack.push_back(TheCondState);
2613 TheCondState.TheCond = AsmCond::IfCond;
2615 if (TheCondState.Ignore) {
2616 EatToEndOfStatement();
2618 StringRef Str = ParseStringToEndOfStatement();
2620 if (getLexer().isNot(AsmToken::EndOfStatement))
2621 return TokError("unexpected token in '.ifb' directive");
2625 TheCondState.CondMet = ExpectBlank == Str.empty();
2626 TheCondState.Ignore = !TheCondState.CondMet;
2632 /// ParseDirectiveIfc
2633 /// ::= .ifc string1, string2
2634 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2635 TheCondStack.push_back(TheCondState);
2636 TheCondState.TheCond = AsmCond::IfCond;
2638 if (TheCondState.Ignore) {
2639 EatToEndOfStatement();
2641 StringRef Str1 = ParseStringToComma();
2643 if (getLexer().isNot(AsmToken::Comma))
2644 return TokError("unexpected token in '.ifc' directive");
2648 StringRef Str2 = ParseStringToEndOfStatement();
2650 if (getLexer().isNot(AsmToken::EndOfStatement))
2651 return TokError("unexpected token in '.ifc' directive");
2655 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2656 TheCondState.Ignore = !TheCondState.CondMet;
2662 /// ParseDirectiveIfdef
2663 /// ::= .ifdef symbol
2664 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2666 TheCondStack.push_back(TheCondState);
2667 TheCondState.TheCond = AsmCond::IfCond;
2669 if (TheCondState.Ignore) {
2670 EatToEndOfStatement();
2672 if (ParseIdentifier(Name))
2673 return TokError("expected identifier after '.ifdef'");
2677 MCSymbol *Sym = getContext().LookupSymbol(Name);
2680 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2682 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2683 TheCondState.Ignore = !TheCondState.CondMet;
2689 /// ParseDirectiveElseIf
2690 /// ::= .elseif expression
2691 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2692 if (TheCondState.TheCond != AsmCond::IfCond &&
2693 TheCondState.TheCond != AsmCond::ElseIfCond)
2694 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2696 TheCondState.TheCond = AsmCond::ElseIfCond;
2698 bool LastIgnoreState = false;
2699 if (!TheCondStack.empty())
2700 LastIgnoreState = TheCondStack.back().Ignore;
2701 if (LastIgnoreState || TheCondState.CondMet) {
2702 TheCondState.Ignore = true;
2703 EatToEndOfStatement();
2707 if (ParseAbsoluteExpression(ExprValue))
2710 if (getLexer().isNot(AsmToken::EndOfStatement))
2711 return TokError("unexpected token in '.elseif' directive");
2714 TheCondState.CondMet = ExprValue;
2715 TheCondState.Ignore = !TheCondState.CondMet;
2721 /// ParseDirectiveElse
2723 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2724 if (getLexer().isNot(AsmToken::EndOfStatement))
2725 return TokError("unexpected token in '.else' directive");
2729 if (TheCondState.TheCond != AsmCond::IfCond &&
2730 TheCondState.TheCond != AsmCond::ElseIfCond)
2731 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2733 TheCondState.TheCond = AsmCond::ElseCond;
2734 bool LastIgnoreState = false;
2735 if (!TheCondStack.empty())
2736 LastIgnoreState = TheCondStack.back().Ignore;
2737 if (LastIgnoreState || TheCondState.CondMet)
2738 TheCondState.Ignore = true;
2740 TheCondState.Ignore = false;
2745 /// ParseDirectiveEndIf
2747 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2748 if (getLexer().isNot(AsmToken::EndOfStatement))
2749 return TokError("unexpected token in '.endif' directive");
2753 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2754 TheCondStack.empty())
2755 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2757 if (!TheCondStack.empty()) {
2758 TheCondState = TheCondStack.back();
2759 TheCondStack.pop_back();
2765 /// ParseDirectiveFile
2766 /// ::= .file [number] filename
2767 /// ::= .file number directory filename
2768 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2769 // FIXME: I'm not sure what this is.
2770 int64_t FileNumber = -1;
2771 SMLoc FileNumberLoc = getLexer().getLoc();
2772 if (getLexer().is(AsmToken::Integer)) {
2773 FileNumber = getTok().getIntVal();
2777 return TokError("file number less than one");
2780 if (getLexer().isNot(AsmToken::String))
2781 return TokError("unexpected token in '.file' directive");
2783 // Usually the directory and filename together, otherwise just the directory.
2784 StringRef Path = getTok().getString();
2785 Path = Path.substr(1, Path.size()-2);
2788 StringRef Directory;
2790 if (getLexer().is(AsmToken::String)) {
2791 if (FileNumber == -1)
2792 return TokError("explicit path specified, but no file number");
2793 Filename = getTok().getString();
2794 Filename = Filename.substr(1, Filename.size()-2);
2801 if (getLexer().isNot(AsmToken::EndOfStatement))
2802 return TokError("unexpected token in '.file' directive");
2804 if (FileNumber == -1)
2805 getStreamer().EmitFileDirective(Filename);
2807 if (getContext().getGenDwarfForAssembly() == true)
2808 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2809 "used to generate dwarf debug info for assembly code");
2811 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2812 Error(FileNumberLoc, "file number already allocated");
2818 /// ParseDirectiveLine
2819 /// ::= .line [number]
2820 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2821 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2822 if (getLexer().isNot(AsmToken::Integer))
2823 return TokError("unexpected token in '.line' directive");
2825 int64_t LineNumber = getTok().getIntVal();
2829 // FIXME: Do something with the .line.
2832 if (getLexer().isNot(AsmToken::EndOfStatement))
2833 return TokError("unexpected token in '.line' directive");
2839 /// ParseDirectiveLoc
2840 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2841 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2842 /// The first number is a file number, must have been previously assigned with
2843 /// a .file directive, the second number is the line number and optionally the
2844 /// third number is a column position (zero if not specified). The remaining
2845 /// optional items are .loc sub-directives.
2846 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2848 if (getLexer().isNot(AsmToken::Integer))
2849 return TokError("unexpected token in '.loc' directive");
2850 int64_t FileNumber = getTok().getIntVal();
2852 return TokError("file number less than one in '.loc' directive");
2853 if (!getContext().isValidDwarfFileNumber(FileNumber))
2854 return TokError("unassigned file number in '.loc' directive");
2857 int64_t LineNumber = 0;
2858 if (getLexer().is(AsmToken::Integer)) {
2859 LineNumber = getTok().getIntVal();
2861 return TokError("line number less than one in '.loc' directive");
2865 int64_t ColumnPos = 0;
2866 if (getLexer().is(AsmToken::Integer)) {
2867 ColumnPos = getTok().getIntVal();
2869 return TokError("column position less than zero in '.loc' directive");
2873 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2875 int64_t Discriminator = 0;
2876 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2878 if (getLexer().is(AsmToken::EndOfStatement))
2882 SMLoc Loc = getTok().getLoc();
2883 if (getParser().ParseIdentifier(Name))
2884 return TokError("unexpected token in '.loc' directive");
2886 if (Name == "basic_block")
2887 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2888 else if (Name == "prologue_end")
2889 Flags |= DWARF2_FLAG_PROLOGUE_END;
2890 else if (Name == "epilogue_begin")
2891 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2892 else if (Name == "is_stmt") {
2893 SMLoc Loc = getTok().getLoc();
2894 const MCExpr *Value;
2895 if (getParser().ParseExpression(Value))
2897 // The expression must be the constant 0 or 1.
2898 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2899 int Value = MCE->getValue();
2901 Flags &= ~DWARF2_FLAG_IS_STMT;
2902 else if (Value == 1)
2903 Flags |= DWARF2_FLAG_IS_STMT;
2905 return Error(Loc, "is_stmt value not 0 or 1");
2908 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2911 else if (Name == "isa") {
2912 SMLoc Loc = getTok().getLoc();
2913 const MCExpr *Value;
2914 if (getParser().ParseExpression(Value))
2916 // The expression must be a constant greater or equal to 0.
2917 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2918 int Value = MCE->getValue();
2920 return Error(Loc, "isa number less than zero");
2924 return Error(Loc, "isa number not a constant value");
2927 else if (Name == "discriminator") {
2928 if (getParser().ParseAbsoluteExpression(Discriminator))
2932 return Error(Loc, "unknown sub-directive in '.loc' directive");
2935 if (getLexer().is(AsmToken::EndOfStatement))
2940 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2941 Isa, Discriminator, StringRef());
2946 /// ParseDirectiveStabs
2947 /// ::= .stabs string, number, number, number
2948 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2949 SMLoc DirectiveLoc) {
2950 return TokError("unsupported directive '" + Directive + "'");
2953 /// ParseDirectiveCFISections
2954 /// ::= .cfi_sections section [, section]
2955 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2956 SMLoc DirectiveLoc) {
2961 if (getParser().ParseIdentifier(Name))
2962 return TokError("Expected an identifier");
2964 if (Name == ".eh_frame")
2966 else if (Name == ".debug_frame")
2969 if (getLexer().is(AsmToken::Comma)) {
2972 if (getParser().ParseIdentifier(Name))
2973 return TokError("Expected an identifier");
2975 if (Name == ".eh_frame")
2977 else if (Name == ".debug_frame")
2981 getStreamer().EmitCFISections(EH, Debug);
2986 /// ParseDirectiveCFIStartProc
2987 /// ::= .cfi_startproc
2988 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2989 SMLoc DirectiveLoc) {
2990 getStreamer().EmitCFIStartProc();
2994 /// ParseDirectiveCFIEndProc
2995 /// ::= .cfi_endproc
2996 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2997 getStreamer().EmitCFIEndProc();
3001 /// ParseRegisterOrRegisterNumber - parse register name or number.
3002 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3003 SMLoc DirectiveLoc) {
3006 if (getLexer().isNot(AsmToken::Integer)) {
3007 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3010 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
3012 return getParser().ParseAbsoluteExpression(Register);
3017 /// ParseDirectiveCFIDefCfa
3018 /// ::= .cfi_def_cfa register, offset
3019 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3020 SMLoc DirectiveLoc) {
3021 int64_t Register = 0;
3022 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3025 if (getLexer().isNot(AsmToken::Comma))
3026 return TokError("unexpected token in directive");
3030 if (getParser().ParseAbsoluteExpression(Offset))
3033 getStreamer().EmitCFIDefCfa(Register, Offset);
3037 /// ParseDirectiveCFIDefCfaOffset
3038 /// ::= .cfi_def_cfa_offset offset
3039 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3040 SMLoc DirectiveLoc) {
3042 if (getParser().ParseAbsoluteExpression(Offset))
3045 getStreamer().EmitCFIDefCfaOffset(Offset);
3049 /// ParseDirectiveCFIAdjustCfaOffset
3050 /// ::= .cfi_adjust_cfa_offset adjustment
3051 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3052 SMLoc DirectiveLoc) {
3053 int64_t Adjustment = 0;
3054 if (getParser().ParseAbsoluteExpression(Adjustment))
3057 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3061 /// ParseDirectiveCFIDefCfaRegister
3062 /// ::= .cfi_def_cfa_register register
3063 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3064 SMLoc DirectiveLoc) {
3065 int64_t Register = 0;
3066 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3069 getStreamer().EmitCFIDefCfaRegister(Register);
3073 /// ParseDirectiveCFIOffset
3074 /// ::= .cfi_offset register, offset
3075 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3076 int64_t Register = 0;
3079 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3082 if (getLexer().isNot(AsmToken::Comma))
3083 return TokError("unexpected token in directive");
3086 if (getParser().ParseAbsoluteExpression(Offset))
3089 getStreamer().EmitCFIOffset(Register, Offset);
3093 /// ParseDirectiveCFIRelOffset
3094 /// ::= .cfi_rel_offset register, offset
3095 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3096 SMLoc DirectiveLoc) {
3097 int64_t Register = 0;
3099 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3102 if (getLexer().isNot(AsmToken::Comma))
3103 return TokError("unexpected token in directive");
3107 if (getParser().ParseAbsoluteExpression(Offset))
3110 getStreamer().EmitCFIRelOffset(Register, Offset);
3114 static bool isValidEncoding(int64_t Encoding) {
3115 if (Encoding & ~0xff)
3118 if (Encoding == dwarf::DW_EH_PE_omit)
3121 const unsigned Format = Encoding & 0xf;
3122 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3123 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3124 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3125 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3128 const unsigned Application = Encoding & 0x70;
3129 if (Application != dwarf::DW_EH_PE_absptr &&
3130 Application != dwarf::DW_EH_PE_pcrel)
3136 /// ParseDirectiveCFIPersonalityOrLsda
3137 /// ::= .cfi_personality encoding, [symbol_name]
3138 /// ::= .cfi_lsda encoding, [symbol_name]
3139 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
3140 SMLoc DirectiveLoc) {
3141 int64_t Encoding = 0;
3142 if (getParser().ParseAbsoluteExpression(Encoding))
3144 if (Encoding == dwarf::DW_EH_PE_omit)
3147 if (!isValidEncoding(Encoding))
3148 return TokError("unsupported encoding.");
3150 if (getLexer().isNot(AsmToken::Comma))
3151 return TokError("unexpected token in directive");
3155 if (getParser().ParseIdentifier(Name))
3156 return TokError("expected identifier in directive");
3158 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3160 if (IDVal == ".cfi_personality")
3161 getStreamer().EmitCFIPersonality(Sym, Encoding);
3163 assert(IDVal == ".cfi_lsda");
3164 getStreamer().EmitCFILsda(Sym, Encoding);
3169 /// ParseDirectiveCFIRememberState
3170 /// ::= .cfi_remember_state
3171 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3172 SMLoc DirectiveLoc) {
3173 getStreamer().EmitCFIRememberState();
3177 /// ParseDirectiveCFIRestoreState
3178 /// ::= .cfi_remember_state
3179 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3180 SMLoc DirectiveLoc) {
3181 getStreamer().EmitCFIRestoreState();
3185 /// ParseDirectiveCFISameValue
3186 /// ::= .cfi_same_value register
3187 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3188 SMLoc DirectiveLoc) {
3189 int64_t Register = 0;
3191 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3194 getStreamer().EmitCFISameValue(Register);
3199 /// ParseDirectiveCFIRestore
3200 /// ::= .cfi_restore register
3201 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
3202 SMLoc DirectiveLoc) {
3203 int64_t Register = 0;
3204 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3207 getStreamer().EmitCFIRestore(Register);
3212 /// ParseDirectiveCFIEscape
3213 /// ::= .cfi_escape expression[,...]
3214 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3215 SMLoc DirectiveLoc) {
3218 if (getParser().ParseAbsoluteExpression(CurrValue))
3221 Values.push_back((uint8_t)CurrValue);
3223 while (getLexer().is(AsmToken::Comma)) {
3226 if (getParser().ParseAbsoluteExpression(CurrValue))
3229 Values.push_back((uint8_t)CurrValue);
3232 getStreamer().EmitCFIEscape(Values);
3236 /// ParseDirectiveCFISignalFrame
3237 /// ::= .cfi_signal_frame
3238 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3239 SMLoc DirectiveLoc) {
3240 if (getLexer().isNot(AsmToken::EndOfStatement))
3241 return Error(getLexer().getLoc(),
3242 "unexpected token in '" + Directive + "' directive");
3244 getStreamer().EmitCFISignalFrame();
3249 /// ParseDirectiveMacrosOnOff
3252 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3253 SMLoc DirectiveLoc) {
3254 if (getLexer().isNot(AsmToken::EndOfStatement))
3255 return Error(getLexer().getLoc(),
3256 "unexpected token in '" + Directive + "' directive");
3258 getParser().MacrosEnabled = Directive == ".macros_on";
3263 /// ParseDirectiveMacro
3264 /// ::= .macro name [parameters]
3265 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3266 SMLoc DirectiveLoc) {
3268 if (getParser().ParseIdentifier(Name))
3269 return TokError("expected identifier in '.macro' directive");
3271 MacroParameters Parameters;
3272 // Argument delimiter is initially unknown. It will be set by
3273 // ParseMacroArgument()
3274 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3275 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3277 MacroParameter Parameter;
3278 if (getParser().ParseIdentifier(Parameter.first))
3279 return TokError("expected identifier in '.macro' directive");
3281 if (getLexer().is(AsmToken::Equal)) {
3283 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3287 Parameters.push_back(Parameter);
3289 if (getLexer().is(AsmToken::Comma))
3291 else if (getLexer().is(AsmToken::EndOfStatement))
3296 // Eat the end of statement.
3299 AsmToken EndToken, StartToken = getTok();
3301 // Lex the macro definition.
3303 // Check whether we have reached the end of the file.
3304 if (getLexer().is(AsmToken::Eof))
3305 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3307 // Otherwise, check whether we have reach the .endmacro.
3308 if (getLexer().is(AsmToken::Identifier) &&
3309 (getTok().getIdentifier() == ".endm" ||
3310 getTok().getIdentifier() == ".endmacro")) {
3311 EndToken = getTok();
3313 if (getLexer().isNot(AsmToken::EndOfStatement))
3314 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3319 // Otherwise, scan til the end of the statement.
3320 getParser().EatToEndOfStatement();
3323 if (getParser().MacroMap.lookup(Name)) {
3324 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3327 const char *BodyStart = StartToken.getLoc().getPointer();
3328 const char *BodyEnd = EndToken.getLoc().getPointer();
3329 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3330 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3334 /// ParseDirectiveEndMacro
3337 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3338 SMLoc DirectiveLoc) {
3339 if (getLexer().isNot(AsmToken::EndOfStatement))
3340 return TokError("unexpected token in '" + Directive + "' directive");
3342 // If we are inside a macro instantiation, terminate the current
3344 if (!getParser().ActiveMacros.empty()) {
3345 getParser().HandleMacroExit();
3349 // Otherwise, this .endmacro is a stray entry in the file; well formed
3350 // .endmacro directives are handled during the macro definition parsing.
3351 return TokError("unexpected '" + Directive + "' in file, "
3352 "no current macro definition");
3355 /// ParseDirectivePurgeMacro
3357 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3358 SMLoc DirectiveLoc) {
3360 if (getParser().ParseIdentifier(Name))
3361 return TokError("expected identifier in '.purgem' directive");
3363 if (getLexer().isNot(AsmToken::EndOfStatement))
3364 return TokError("unexpected token in '.purgem' directive");
3366 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3367 if (I == getParser().MacroMap.end())
3368 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3370 // Undefine the macro.
3371 delete I->getValue();
3372 getParser().MacroMap.erase(I);
3376 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3377 getParser().CheckForValidSection();
3379 const MCExpr *Value;
3381 if (getParser().ParseExpression(Value))
3384 if (getLexer().isNot(AsmToken::EndOfStatement))
3385 return TokError("unexpected token in directive");
3387 if (DirName[1] == 's')
3388 getStreamer().EmitSLEB128Value(Value);
3390 getStreamer().EmitULEB128Value(Value);
3395 Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3396 AsmToken EndToken, StartToken = getTok();
3398 unsigned NestLevel = 0;
3400 // Check whether we have reached the end of the file.
3401 if (getLexer().is(AsmToken::Eof)) {
3402 Error(DirectiveLoc, "no matching '.endr' in definition");
3406 if (Lexer.is(AsmToken::Identifier) &&
3407 (getTok().getIdentifier() == ".rept")) {
3411 // Otherwise, check whether we have reached the .endr.
3412 if (Lexer.is(AsmToken::Identifier) &&
3413 getTok().getIdentifier() == ".endr") {
3414 if (NestLevel == 0) {
3415 EndToken = getTok();
3417 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3418 TokError("unexpected token in '.endr' directive");
3426 // Otherwise, scan till the end of the statement.
3427 EatToEndOfStatement();
3430 const char *BodyStart = StartToken.getLoc().getPointer();
3431 const char *BodyEnd = EndToken.getLoc().getPointer();
3432 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3434 // We Are Anonymous.
3436 MacroParameters Parameters;
3437 return new Macro(Name, Body, Parameters);
3440 void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3441 raw_svector_ostream &OS) {
3444 MemoryBuffer *Instantiation =
3445 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3447 // Create the macro instantiation object and add to the current macro
3448 // instantiation stack.
3449 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3452 ActiveMacros.push_back(MI);
3454 // Jump to the macro instantiation and prime the lexer.
3455 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3456 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3460 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3462 if (ParseAbsoluteExpression(Count))
3463 return TokError("unexpected token in '.rept' directive");
3466 return TokError("Count is negative");
3468 if (Lexer.isNot(AsmToken::EndOfStatement))
3469 return TokError("unexpected token in '.rept' directive");
3471 // Eat the end of statement.
3474 // Lex the rept definition.
3475 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3479 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3480 // to hold the macro body with substitutions.
3481 SmallString<256> Buf;
3482 MacroParameters Parameters;
3484 raw_svector_ostream OS(Buf);
3486 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3489 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3494 /// ParseDirectiveIrp
3495 /// ::= .irp symbol,values
3496 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3497 MacroParameters Parameters;
3498 MacroParameter Parameter;
3500 if (ParseIdentifier(Parameter.first))
3501 return TokError("expected identifier in '.irp' directive");
3503 Parameters.push_back(Parameter);
3505 if (Lexer.isNot(AsmToken::Comma))
3506 return TokError("expected comma in '.irp' directive");
3511 if (ParseMacroArguments(0, A))
3514 // Eat the end of statement.
3517 // Lex the irp definition.
3518 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3522 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3523 // to hold the macro body with substitutions.
3524 SmallString<256> Buf;
3525 raw_svector_ostream OS(Buf);
3527 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3528 MacroArguments Args;
3531 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3535 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3540 /// ParseDirectiveIrpc
3541 /// ::= .irpc symbol,values
3542 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3543 MacroParameters Parameters;
3544 MacroParameter Parameter;
3546 if (ParseIdentifier(Parameter.first))
3547 return TokError("expected identifier in '.irpc' directive");
3549 Parameters.push_back(Parameter);
3551 if (Lexer.isNot(AsmToken::Comma))
3552 return TokError("expected comma in '.irpc' directive");
3557 if (ParseMacroArguments(0, A))
3560 if (A.size() != 1 || A.front().size() != 1)
3561 return TokError("unexpected token in '.irpc' directive");
3563 // Eat the end of statement.
3566 // Lex the irpc definition.
3567 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3571 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3572 // to hold the macro body with substitutions.
3573 SmallString<256> Buf;
3574 raw_svector_ostream OS(Buf);
3576 StringRef Values = A.front().front().getString();
3577 std::size_t I, End = Values.size();
3578 for (I = 0; I < End; ++I) {
3580 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3582 MacroArguments Args;
3583 Args.push_back(Arg);
3585 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3589 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3594 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3595 if (ActiveMacros.empty())
3596 return TokError("unmatched '.endr' directive");
3598 // The only .repl that should get here are the ones created by
3599 // InstantiateMacroLikeBody.
3600 assert(getLexer().is(AsmToken::EndOfStatement));
3606 bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3607 const MCExpr *Value;
3608 SMLoc ExprLoc = getLexer().getLoc();
3609 if (ParseExpression(Value))
3611 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3613 return Error(ExprLoc, "unexpected expression in _emit");
3614 uint64_t IntValue = MCE->getValue();
3615 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3616 return Error(ExprLoc, "literal value out of range for directive");
3618 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3622 bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3623 unsigned &NumOutputs, unsigned &NumInputs,
3624 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
3625 SmallVectorImpl<std::string> &Constraints,
3626 SmallVectorImpl<std::string> &Clobbers,
3627 const MCInstrInfo *MII,
3628 const MCInstPrinter *IP,
3629 MCAsmParserSemaCallback &SI) {
3630 SmallVector<void *, 4> InputDecls;
3631 SmallVector<void *, 4> OutputDecls;
3632 SmallVector<bool, 4> InputDeclsOffsetOf;
3633 SmallVector<bool, 4> OutputDeclsOffsetOf;
3634 SmallVector<std::string, 4> InputConstraints;
3635 SmallVector<std::string, 4> OutputConstraints;
3636 std::set<std::string> ClobberRegs;
3638 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
3643 // While we have input, parse each statement.
3644 unsigned InputIdx = 0;
3645 unsigned OutputIdx = 0;
3646 while (getLexer().isNot(AsmToken::Eof)) {
3647 ParseStatementInfo Info(&AsmStrRewrites);
3648 if (ParseStatement(Info))
3651 if (Info.Opcode != ~0U) {
3652 const MCInstrDesc &Desc = MII->get(Info.Opcode);
3654 // Build the list of clobbers, outputs and inputs.
3655 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3656 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
3659 if (Operand->isImm()) {
3660 if (Operand->needAsmRewrite())
3661 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3662 Operand->getStartLoc()));
3666 // Register operand.
3667 if (Operand->isReg() && !Operand->isOffsetOf()) {
3668 unsigned NumDefs = Desc.getNumDefs();
3670 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3672 raw_string_ostream OS(Reg);
3673 IP->printRegName(OS, Operand->getReg());
3674 ClobberRegs.insert(StringRef(OS.str()));
3679 // Expr/Input or Output.
3681 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3684 bool isOutput = (i == 1) && Desc.mayStore();
3685 if (!Operand->isOffsetOf() && Operand->needSizeDirective())
3686 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
3687 Operand->getStartLoc(),
3689 Operand->getMemSize()));
3691 std::string Constraint = "=";
3693 OutputDecls.push_back(OpDecl);
3694 OutputDeclsOffsetOf.push_back(Operand->isOffsetOf());
3695 Constraint += Operand->getConstraint().str();
3696 OutputConstraints.push_back(Constraint);
3697 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
3698 Operand->getStartLoc(),
3699 Operand->getNameLen()));
3701 InputDecls.push_back(OpDecl);
3702 InputDeclsOffsetOf.push_back(Operand->isOffsetOf());
3703 InputConstraints.push_back(Operand->getConstraint().str());
3704 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
3705 Operand->getStartLoc(),
3706 Operand->getNameLen()));
3713 // Set the number of Outputs and Inputs.
3714 NumOutputs = OutputDecls.size();
3715 NumInputs = InputDecls.size();
3717 // Set the unique clobbers.
3718 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3719 E = ClobberRegs.end(); I != E; ++I)
3720 Clobbers.push_back(*I);
3722 // Merge the various outputs and inputs. Output are expected first.
3723 if (NumOutputs || NumInputs) {
3724 unsigned NumExprs = NumOutputs + NumInputs;
3725 OpDecls.resize(NumExprs);
3726 Constraints.resize(NumExprs);
3727 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3728 // constraint for offsetof. This needs to be cleaned up!
3729 for (unsigned i = 0; i < NumOutputs; ++i) {
3730 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsOffsetOf[i]);
3731 Constraints[i] = OutputDeclsOffsetOf[i] ? "=r" : OutputConstraints[i];
3733 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
3734 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsOffsetOf[i]);
3735 Constraints[j] = InputDeclsOffsetOf[i] ? "r" : InputConstraints[i];
3739 // Build the IR assembly string.
3740 std::string AsmStringIR;
3741 AsmRewriteKind PrevKind = AOK_Imm;
3742 raw_string_ostream OS(AsmStringIR);
3743 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
3744 for (SmallVectorImpl<struct AsmRewrite>::iterator
3745 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3746 const char *Loc = (*I).Loc.getPointer();
3748 AsmRewriteKind Kind = (*I).Kind;
3750 // Emit everything up to the immediate/expression. If the previous rewrite
3751 // was a size directive, then this has already been done.
3752 if (PrevKind != AOK_SizeDirective)
3753 OS << StringRef(Start, Loc - Start);
3756 // Skip the original expression.
3757 if (Kind == AOK_Skip) {
3758 Start = Loc + (*I).Len;
3762 // Rewrite expressions in $N notation.
3780 case AOK_SizeDirective:
3783 case 8: OS << "byte ptr "; break;
3784 case 16: OS << "word ptr "; break;
3785 case 32: OS << "dword ptr "; break;
3786 case 64: OS << "qword ptr "; break;
3787 case 80: OS << "xword ptr "; break;
3788 case 128: OS << "xmmword ptr "; break;
3789 case 256: OS << "ymmword ptr "; break;
3795 case AOK_DotOperator:
3800 // Skip the original expression.
3801 if (Kind != AOK_SizeDirective)
3802 Start = Loc + (*I).Len;
3805 // Emit the remainder of the asm string.
3806 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3807 if (Start != AsmEnd)
3808 OS << StringRef(Start, AsmEnd - Start);
3810 AsmString = OS.str();
3814 /// \brief Create an MCAsmParser instance.
3815 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3816 MCContext &C, MCStreamer &Out,
3817 const MCAsmInfo &MAI) {
3818 return new AsmParser(SM, C, Out, MAI);