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/StringSwitch.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCParser/AsmCond.h"
24 #include "llvm/MC/MCParser/AsmLexer.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCSectionMachO.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCTargetAsmParser.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/raw_ostream.h"
43 FatalAssemblerWarnings("fatal-assembler-warnings",
44 cl::desc("Consider warnings as error"));
48 /// \brief Helper class for tracking macro definitions.
52 std::vector<StringRef> Parameters;
55 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
56 Name(N), Body(B), Parameters(P) {}
59 /// \brief Helper class for storing information about an active macro
61 struct MacroInstantiation {
62 /// The macro being instantiated.
63 const Macro *TheMacro;
65 /// The macro instantiation with substitutions.
66 MemoryBuffer *Instantiation;
68 /// The location of the instantiation.
69 SMLoc InstantiationLoc;
71 /// The location where parsing should resume upon instantiation completion.
75 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
79 /// \brief The concrete assembly parser instance.
80 class AsmParser : public MCAsmParser {
81 friend class GenericAsmParser;
83 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
84 void operator=(const AsmParser &); // DO NOT IMPLEMENT
91 SourceMgr::DiagHandlerTy SavedDiagHandler;
92 void *SavedDiagContext;
93 MCAsmParserExtension *GenericParser;
94 MCAsmParserExtension *PlatformParser;
96 /// This is the current buffer index we're lexing from as managed by the
100 AsmCond TheCondState;
101 std::vector<AsmCond> TheCondStack;
103 /// DirectiveMap - This is a table handlers for directives. Each handler is
104 /// invoked after the directive identifier is read and is responsible for
105 /// parsing and validating the rest of the directive. The handler is passed
106 /// in the directive name and the location of the directive keyword.
107 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
109 /// MacroMap - Map of currently defined macros.
110 StringMap<Macro*> MacroMap;
112 /// ActiveMacros - Stack of active macro instantiations.
113 std::vector<MacroInstantiation*> ActiveMacros;
115 /// Boolean tracking whether macro substitution is enabled.
116 unsigned MacrosEnabled : 1;
118 /// Flag tracking whether any errors have been encountered.
119 unsigned HadError : 1;
121 /// The values from the last parsed cpp hash file line comment if any.
122 StringRef CppHashFilename;
123 int64_t CppHashLineNumber;
127 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
128 const MCAsmInfo &MAI);
131 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
133 void AddDirectiveHandler(MCAsmParserExtension *Object,
135 DirectiveHandler Handler) {
136 DirectiveMap[Directive] = std::make_pair(Object, Handler);
140 /// @name MCAsmParser Interface
143 virtual SourceMgr &getSourceManager() { return SrcMgr; }
144 virtual MCAsmLexer &getLexer() { return Lexer; }
145 virtual MCContext &getContext() { return Ctx; }
146 virtual MCStreamer &getStreamer() { return Out; }
147 virtual unsigned getAssemblerDialect() { return MAI.getAssemblerDialect(); }
149 virtual bool Warning(SMLoc L, const Twine &Msg,
150 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
151 virtual bool Error(SMLoc L, const Twine &Msg,
152 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
154 const AsmToken &Lex();
156 bool ParseExpression(const MCExpr *&Res);
157 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
158 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
159 virtual bool ParseAbsoluteExpression(int64_t &Res);
164 void CheckForValidSection();
166 bool ParseStatement();
167 void EatToEndOfLine();
168 bool ParseCppHashLineFilenameComment(const SMLoc &L);
170 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
171 bool expandMacro(SmallString<256> &Buf, StringRef Body,
172 const std::vector<StringRef> &Parameters,
173 const std::vector<std::vector<AsmToken> > &A,
175 void HandleMacroExit();
177 void PrintMacroInstantiations();
178 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
179 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
180 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
182 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
184 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
185 bool EnterIncludeFile(const std::string &Filename);
186 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
187 /// This returns true on failure.
188 bool ProcessIncbinFile(const std::string &Filename);
190 /// \brief Reset the current lexer position to that given by \arg Loc. The
191 /// current token is not set; clients should ensure Lex() is called
193 void JumpToLoc(SMLoc Loc);
195 void EatToEndOfStatement();
197 /// \brief Parse up to the end of statement and a return the contents from the
198 /// current token until the end of the statement; the current token on exit
199 /// will be either the EndOfStatement or EOF.
200 StringRef ParseStringToEndOfStatement();
202 bool ParseAssignment(StringRef Name, bool allow_redef);
204 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
205 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
206 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
207 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
209 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
210 /// and set \arg Res to the identifier contents.
211 bool ParseIdentifier(StringRef &Res);
213 // Directive Parsing.
215 // ".ascii", ".asciiz", ".string"
216 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
217 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
218 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
219 bool ParseDirectiveFill(); // ".fill"
220 bool ParseDirectiveSpace(); // ".space"
221 bool ParseDirectiveZero(); // ".zero"
222 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
223 bool ParseDirectiveOrg(); // ".org"
224 // ".align{,32}", ".p2align{,w,l}"
225 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
227 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
228 /// accepts a single symbol (which should be a label or an external).
229 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
231 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
233 bool ParseDirectiveAbort(); // ".abort"
234 bool ParseDirectiveInclude(); // ".include"
235 bool ParseDirectiveIncbin(); // ".incbin"
237 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
238 // ".ifdef" or ".ifndef", depending on expect_defined
239 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
240 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
241 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
242 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
244 /// ParseEscapedString - Parse the current token as a string which may include
245 /// escaped characters and return the string contents.
246 bool ParseEscapedString(std::string &Data);
248 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
249 MCSymbolRefExpr::VariantKind Variant);
252 /// \brief Generic implementations of directive handling, etc. which is shared
253 /// (or the default, at least) for all assembler parser.
254 class GenericAsmParser : public MCAsmParserExtension {
255 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
256 void AddDirectiveHandler(StringRef Directive) {
257 getParser().AddDirectiveHandler(this, Directive,
258 HandleDirective<GenericAsmParser, Handler>);
261 GenericAsmParser() {}
263 AsmParser &getParser() {
264 return (AsmParser&) this->MCAsmParserExtension::getParser();
267 virtual void Initialize(MCAsmParser &Parser) {
268 // Call the base implementation.
269 this->MCAsmParserExtension::Initialize(Parser);
271 // Debugging directives.
272 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
273 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
274 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
275 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
278 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
280 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
282 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
284 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
286 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
287 ".cfi_def_cfa_offset");
288 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
289 ".cfi_adjust_cfa_offset");
290 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
291 ".cfi_def_cfa_register");
292 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
294 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
297 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
299 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
301 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
303 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
305 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
307 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
309 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
311 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
314 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
316 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
318 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
319 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
320 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
322 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
323 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
326 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
328 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
329 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
330 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
331 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
332 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
333 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
334 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
335 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
336 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
337 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
338 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
339 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
340 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
341 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
342 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
343 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
344 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
345 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
346 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
347 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
349 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
350 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
351 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
353 bool ParseDirectiveLEB128(StringRef, SMLoc);
360 extern MCAsmParserExtension *createDarwinAsmParser();
361 extern MCAsmParserExtension *createELFAsmParser();
362 extern MCAsmParserExtension *createCOFFAsmParser();
366 enum { DEFAULT_ADDRSPACE = 0 };
368 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
369 MCStreamer &_Out, const MCAsmInfo &_MAI)
370 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
371 GenericParser(new GenericAsmParser), PlatformParser(0),
372 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0) {
373 // Save the old handler.
374 SavedDiagHandler = SrcMgr.getDiagHandler();
375 SavedDiagContext = SrcMgr.getDiagContext();
376 // Set our own handler which calls the saved handler.
377 SrcMgr.setDiagHandler(DiagHandler, this);
378 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
380 // Initialize the generic parser.
381 GenericParser->Initialize(*this);
383 // Initialize the platform / file format parser.
385 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
387 if (_MAI.hasMicrosoftFastStdCallMangling()) {
388 PlatformParser = createCOFFAsmParser();
389 PlatformParser->Initialize(*this);
390 } else if (_MAI.hasSubsectionsViaSymbols()) {
391 PlatformParser = createDarwinAsmParser();
392 PlatformParser->Initialize(*this);
394 PlatformParser = createELFAsmParser();
395 PlatformParser->Initialize(*this);
399 AsmParser::~AsmParser() {
400 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
402 // Destroy any macros.
403 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
404 ie = MacroMap.end(); it != ie; ++it)
405 delete it->getValue();
407 delete PlatformParser;
408 delete GenericParser;
411 void AsmParser::PrintMacroInstantiations() {
412 // Print the active macro instantiation stack.
413 for (std::vector<MacroInstantiation*>::const_reverse_iterator
414 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
415 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
416 "while in macro instantiation");
419 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
420 if (FatalAssemblerWarnings)
421 return Error(L, Msg, Ranges);
422 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
423 PrintMacroInstantiations();
427 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
429 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
430 PrintMacroInstantiations();
434 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
435 std::string IncludedFile;
436 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
442 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
447 /// Process the specified .incbin file by seaching for it in the include paths
448 /// then just emiting the byte contents of the file to the streamer. This
449 /// returns true on failure.
450 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
451 std::string IncludedFile;
452 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
456 // Pick up the bytes from the file and emit them.
457 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
462 void AsmParser::JumpToLoc(SMLoc Loc) {
463 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
464 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
467 const AsmToken &AsmParser::Lex() {
468 const AsmToken *tok = &Lexer.Lex();
470 if (tok->is(AsmToken::Eof)) {
471 // If this is the end of an included file, pop the parent file off the
473 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
474 if (ParentIncludeLoc != SMLoc()) {
475 JumpToLoc(ParentIncludeLoc);
480 if (tok->is(AsmToken::Error))
481 Error(Lexer.getErrLoc(), Lexer.getErr());
486 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
487 // Create the initial section, if requested.
488 if (!NoInitialTextSection)
495 AsmCond StartingCondState = TheCondState;
497 // If we are generating dwarf for assembly source files save the initial text
498 // section and generate a .file directive.
499 if (getContext().getGenDwarfForAssembly()) {
500 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
501 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
502 getStreamer().EmitLabel(SectionStartSym);
503 getContext().setGenDwarfSectionStartSym(SectionStartSym);
504 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
505 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
508 // While we have input, parse each statement.
509 while (Lexer.isNot(AsmToken::Eof)) {
510 if (!ParseStatement()) continue;
512 // We had an error, validate that one was emitted and recover by skipping to
514 assert(HadError && "Parse statement returned an error, but none emitted!");
515 EatToEndOfStatement();
518 if (TheCondState.TheCond != StartingCondState.TheCond ||
519 TheCondState.Ignore != StartingCondState.Ignore)
520 return TokError("unmatched .ifs or .elses");
522 // Check to see there are no empty DwarfFile slots.
523 const std::vector<MCDwarfFile *> &MCDwarfFiles =
524 getContext().getMCDwarfFiles();
525 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
526 if (!MCDwarfFiles[i])
527 TokError("unassigned file number: " + Twine(i) + " for .file directives");
530 // Check to see that all assembler local symbols were actually defined.
531 // Targets that don't do subsections via symbols may not want this, though,
532 // so conservatively exclude them. Only do this if we're finalizing, though,
533 // as otherwise we won't necessarilly have seen everything yet.
534 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
535 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
536 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
539 MCSymbol *Sym = i->getValue();
540 // Variable symbols may not be marked as defined, so check those
541 // explicitly. If we know it's a variable, we have a definition for
542 // the purposes of this check.
543 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
544 // FIXME: We would really like to refer back to where the symbol was
545 // first referenced for a source location. We need to add something
546 // to track that. Currently, we just point to the end of the file.
547 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
548 "assembler local symbol '" + Sym->getName() +
554 // Finalize the output stream if there are no errors and if the client wants
556 if (!HadError && !NoFinalize)
562 void AsmParser::CheckForValidSection() {
563 if (!getStreamer().getCurrentSection()) {
564 TokError("expected section directive before assembly directive");
565 Out.SwitchSection(Ctx.getMachOSection(
567 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
568 0, SectionKind::getText()));
572 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
573 void AsmParser::EatToEndOfStatement() {
574 while (Lexer.isNot(AsmToken::EndOfStatement) &&
575 Lexer.isNot(AsmToken::Eof))
579 if (Lexer.is(AsmToken::EndOfStatement))
583 StringRef AsmParser::ParseStringToEndOfStatement() {
584 const char *Start = getTok().getLoc().getPointer();
586 while (Lexer.isNot(AsmToken::EndOfStatement) &&
587 Lexer.isNot(AsmToken::Eof))
590 const char *End = getTok().getLoc().getPointer();
591 return StringRef(Start, End - Start);
594 /// ParseParenExpr - Parse a paren expression and return it.
595 /// NOTE: This assumes the leading '(' has already been consumed.
597 /// parenexpr ::= expr)
599 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
600 if (ParseExpression(Res)) return true;
601 if (Lexer.isNot(AsmToken::RParen))
602 return TokError("expected ')' in parentheses expression");
603 EndLoc = Lexer.getLoc();
608 /// ParseBracketExpr - Parse a bracket expression and return it.
609 /// NOTE: This assumes the leading '[' has already been consumed.
611 /// bracketexpr ::= expr]
613 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
614 if (ParseExpression(Res)) return true;
615 if (Lexer.isNot(AsmToken::RBrac))
616 return TokError("expected ']' in brackets expression");
617 EndLoc = Lexer.getLoc();
622 /// ParsePrimaryExpr - Parse a primary expression and return it.
623 /// primaryexpr ::= (parenexpr
624 /// primaryexpr ::= symbol
625 /// primaryexpr ::= number
626 /// primaryexpr ::= '.'
627 /// primaryexpr ::= ~,+,- primaryexpr
628 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
629 switch (Lexer.getKind()) {
631 return TokError("unknown token in expression");
632 // If we have an error assume that we've already handled it.
633 case AsmToken::Error:
635 case AsmToken::Exclaim:
636 Lex(); // Eat the operator.
637 if (ParsePrimaryExpr(Res, EndLoc))
639 Res = MCUnaryExpr::CreateLNot(Res, getContext());
641 case AsmToken::Dollar:
642 case AsmToken::String:
643 case AsmToken::Identifier: {
644 EndLoc = Lexer.getLoc();
646 StringRef Identifier;
647 if (ParseIdentifier(Identifier))
650 // This is a symbol reference.
651 std::pair<StringRef, StringRef> Split = Identifier.split('@');
652 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
654 // Lookup the symbol variant if used.
655 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
656 if (Split.first.size() != Identifier.size()) {
657 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
658 if (Variant == MCSymbolRefExpr::VK_Invalid) {
659 Variant = MCSymbolRefExpr::VK_None;
660 return TokError("invalid variant '" + Split.second + "'");
664 // If this is an absolute variable reference, substitute it now to preserve
665 // semantics in the face of reassignment.
666 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
668 return Error(EndLoc, "unexpected modifier on variable reference");
670 Res = Sym->getVariableValue();
674 // Otherwise create a symbol ref.
675 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
678 case AsmToken::Integer: {
679 SMLoc Loc = getTok().getLoc();
680 int64_t IntVal = getTok().getIntVal();
681 Res = MCConstantExpr::Create(IntVal, getContext());
682 EndLoc = Lexer.getLoc();
684 // Look for 'b' or 'f' following an Integer as a directional label
685 if (Lexer.getKind() == AsmToken::Identifier) {
686 StringRef IDVal = getTok().getString();
687 if (IDVal == "f" || IDVal == "b"){
688 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
689 IDVal == "f" ? 1 : 0);
690 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
692 if(IDVal == "b" && Sym->isUndefined())
693 return Error(Loc, "invalid reference to undefined symbol");
694 EndLoc = Lexer.getLoc();
695 Lex(); // Eat identifier.
700 case AsmToken::Real: {
701 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
702 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
703 Res = MCConstantExpr::Create(IntVal, getContext());
707 case AsmToken::Dot: {
708 // This is a '.' reference, which references the current PC. Emit a
709 // temporary label to the streamer and refer to it.
710 MCSymbol *Sym = Ctx.CreateTempSymbol();
712 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
713 EndLoc = Lexer.getLoc();
714 Lex(); // Eat identifier.
717 case AsmToken::LParen:
718 Lex(); // Eat the '('.
719 return ParseParenExpr(Res, EndLoc);
720 case AsmToken::LBrac:
721 if (!PlatformParser->HasBracketExpressions())
722 return TokError("brackets expression not supported on this target");
723 Lex(); // Eat the '['.
724 return ParseBracketExpr(Res, EndLoc);
725 case AsmToken::Minus:
726 Lex(); // Eat the operator.
727 if (ParsePrimaryExpr(Res, EndLoc))
729 Res = MCUnaryExpr::CreateMinus(Res, getContext());
732 Lex(); // Eat the operator.
733 if (ParsePrimaryExpr(Res, EndLoc))
735 Res = MCUnaryExpr::CreatePlus(Res, getContext());
737 case AsmToken::Tilde:
738 Lex(); // Eat the operator.
739 if (ParsePrimaryExpr(Res, EndLoc))
741 Res = MCUnaryExpr::CreateNot(Res, getContext());
746 bool AsmParser::ParseExpression(const MCExpr *&Res) {
748 return ParseExpression(Res, EndLoc);
752 AsmParser::ApplyModifierToExpr(const MCExpr *E,
753 MCSymbolRefExpr::VariantKind Variant) {
754 // Recurse over the given expression, rebuilding it to apply the given variant
755 // if there is exactly one symbol.
756 switch (E->getKind()) {
758 case MCExpr::Constant:
761 case MCExpr::SymbolRef: {
762 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
764 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
765 TokError("invalid variant on expression '" +
766 getTok().getIdentifier() + "' (already modified)");
770 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
773 case MCExpr::Unary: {
774 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
775 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
778 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
781 case MCExpr::Binary: {
782 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
783 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
784 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
789 if (!LHS) LHS = BE->getLHS();
790 if (!RHS) RHS = BE->getRHS();
792 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
796 assert(0 && "Invalid expression kind!");
800 /// ParseExpression - Parse an expression and return it.
802 /// expr ::= expr &&,|| expr -> lowest.
803 /// expr ::= expr |,^,&,! expr
804 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
805 /// expr ::= expr <<,>> expr
806 /// expr ::= expr +,- expr
807 /// expr ::= expr *,/,% expr -> highest.
808 /// expr ::= primaryexpr
810 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
811 // Parse the expression.
813 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
816 // As a special case, we support 'a op b @ modifier' by rewriting the
817 // expression to include the modifier. This is inefficient, but in general we
818 // expect users to use 'a@modifier op b'.
819 if (Lexer.getKind() == AsmToken::At) {
822 if (Lexer.isNot(AsmToken::Identifier))
823 return TokError("unexpected symbol modifier following '@'");
825 MCSymbolRefExpr::VariantKind Variant =
826 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
827 if (Variant == MCSymbolRefExpr::VK_Invalid)
828 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
830 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
832 return TokError("invalid modifier '" + getTok().getIdentifier() +
833 "' (no symbols present)");
840 // Try to constant fold it up front, if possible.
842 if (Res->EvaluateAsAbsolute(Value))
843 Res = MCConstantExpr::Create(Value, getContext());
848 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
850 return ParseParenExpr(Res, EndLoc) ||
851 ParseBinOpRHS(1, Res, EndLoc);
854 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
857 SMLoc StartLoc = Lexer.getLoc();
858 if (ParseExpression(Expr))
861 if (!Expr->EvaluateAsAbsolute(Res))
862 return Error(StartLoc, "expected absolute expression");
867 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
868 MCBinaryExpr::Opcode &Kind) {
871 return 0; // not a binop.
873 // Lowest Precedence: &&, ||
874 case AsmToken::AmpAmp:
875 Kind = MCBinaryExpr::LAnd;
877 case AsmToken::PipePipe:
878 Kind = MCBinaryExpr::LOr;
882 // Low Precedence: |, &, ^
884 // FIXME: gas seems to support '!' as an infix operator?
886 Kind = MCBinaryExpr::Or;
888 case AsmToken::Caret:
889 Kind = MCBinaryExpr::Xor;
892 Kind = MCBinaryExpr::And;
895 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
896 case AsmToken::EqualEqual:
897 Kind = MCBinaryExpr::EQ;
899 case AsmToken::ExclaimEqual:
900 case AsmToken::LessGreater:
901 Kind = MCBinaryExpr::NE;
904 Kind = MCBinaryExpr::LT;
906 case AsmToken::LessEqual:
907 Kind = MCBinaryExpr::LTE;
909 case AsmToken::Greater:
910 Kind = MCBinaryExpr::GT;
912 case AsmToken::GreaterEqual:
913 Kind = MCBinaryExpr::GTE;
916 // Intermediate Precedence: <<, >>
917 case AsmToken::LessLess:
918 Kind = MCBinaryExpr::Shl;
920 case AsmToken::GreaterGreater:
921 Kind = MCBinaryExpr::Shr;
924 // High Intermediate Precedence: +, -
926 Kind = MCBinaryExpr::Add;
928 case AsmToken::Minus:
929 Kind = MCBinaryExpr::Sub;
932 // Highest Precedence: *, /, %
934 Kind = MCBinaryExpr::Mul;
936 case AsmToken::Slash:
937 Kind = MCBinaryExpr::Div;
939 case AsmToken::Percent:
940 Kind = MCBinaryExpr::Mod;
946 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
947 /// Res contains the LHS of the expression on input.
948 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
951 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
952 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
954 // If the next token is lower precedence than we are allowed to eat, return
955 // successfully with what we ate already.
956 if (TokPrec < Precedence)
961 // Eat the next primary expression.
963 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
965 // If BinOp binds less tightly with RHS than the operator after RHS, let
966 // the pending operator take RHS as its LHS.
967 MCBinaryExpr::Opcode Dummy;
968 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
969 if (TokPrec < NextTokPrec) {
970 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
973 // Merge LHS and RHS according to operator.
974 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
982 /// ::= EndOfStatement
983 /// ::= Label* Directive ...Operands... EndOfStatement
984 /// ::= Label* Identifier OperandList* EndOfStatement
985 bool AsmParser::ParseStatement() {
986 if (Lexer.is(AsmToken::EndOfStatement)) {
992 // Statements always start with an identifier or are a full line comment.
993 AsmToken ID = getTok();
994 SMLoc IDLoc = ID.getLoc();
996 int64_t LocalLabelVal = -1;
997 // A full line comment is a '#' as the first token.
998 if (Lexer.is(AsmToken::Hash))
999 return ParseCppHashLineFilenameComment(IDLoc);
1001 // Allow an integer followed by a ':' as a directional local label.
1002 if (Lexer.is(AsmToken::Integer)) {
1003 LocalLabelVal = getTok().getIntVal();
1004 if (LocalLabelVal < 0) {
1005 if (!TheCondState.Ignore)
1006 return TokError("unexpected token at start of statement");
1010 IDVal = getTok().getString();
1011 Lex(); // Consume the integer token to be used as an identifier token.
1012 if (Lexer.getKind() != AsmToken::Colon) {
1013 if (!TheCondState.Ignore)
1014 return TokError("unexpected token at start of statement");
1018 } else if (Lexer.is(AsmToken::Dot)) {
1019 // Treat '.' as a valid identifier in this context.
1023 } else if (ParseIdentifier(IDVal)) {
1024 if (!TheCondState.Ignore)
1025 return TokError("unexpected token at start of statement");
1030 // Handle conditional assembly here before checking for skipping. We
1031 // have to do this so that .endif isn't skipped in a ".if 0" block for
1034 return ParseDirectiveIf(IDLoc);
1035 if (IDVal == ".ifdef")
1036 return ParseDirectiveIfdef(IDLoc, true);
1037 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1038 return ParseDirectiveIfdef(IDLoc, false);
1039 if (IDVal == ".elseif")
1040 return ParseDirectiveElseIf(IDLoc);
1041 if (IDVal == ".else")
1042 return ParseDirectiveElse(IDLoc);
1043 if (IDVal == ".endif")
1044 return ParseDirectiveEndIf(IDLoc);
1046 // If we are in a ".if 0" block, ignore this statement.
1047 if (TheCondState.Ignore) {
1048 EatToEndOfStatement();
1052 // FIXME: Recurse on local labels?
1054 // See what kind of statement we have.
1055 switch (Lexer.getKind()) {
1056 case AsmToken::Colon: {
1057 CheckForValidSection();
1059 // identifier ':' -> Label.
1062 // Diagnose attempt to use '.' as a label.
1064 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1066 // Diagnose attempt to use a variable as a label.
1068 // FIXME: Diagnostics. Note the location of the definition as a label.
1069 // FIXME: This doesn't diagnose assignment to a symbol which has been
1070 // implicitly marked as external.
1072 if (LocalLabelVal == -1)
1073 Sym = getContext().GetOrCreateSymbol(IDVal);
1075 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1076 if (!Sym->isUndefined() || Sym->isVariable())
1077 return Error(IDLoc, "invalid symbol redefinition");
1082 // If we are generating dwarf for assembly source files then gather the
1083 // info to make a dwarf label entry for this label if needed.
1084 if (getContext().getGenDwarfForAssembly())
1085 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1088 // Consume any end of statement token, if present, to avoid spurious
1089 // AddBlankLine calls().
1090 if (Lexer.is(AsmToken::EndOfStatement)) {
1092 if (Lexer.is(AsmToken::Eof))
1096 return ParseStatement();
1099 case AsmToken::Equal:
1100 // identifier '=' ... -> assignment statement
1103 return ParseAssignment(IDVal, true);
1105 default: // Normal instruction or directive.
1109 // If macros are enabled, check to see if this is a macro instantiation.
1111 if (const Macro *M = MacroMap.lookup(IDVal))
1112 return HandleMacroEntry(IDVal, IDLoc, M);
1114 // Otherwise, we have a normal instruction or directive.
1115 if (IDVal[0] == '.' && IDVal != ".") {
1116 // Assembler features
1117 if (IDVal == ".set" || IDVal == ".equ")
1118 return ParseDirectiveSet(IDVal, true);
1119 if (IDVal == ".equiv")
1120 return ParseDirectiveSet(IDVal, false);
1124 if (IDVal == ".ascii")
1125 return ParseDirectiveAscii(IDVal, false);
1126 if (IDVal == ".asciz" || IDVal == ".string")
1127 return ParseDirectiveAscii(IDVal, true);
1129 if (IDVal == ".byte")
1130 return ParseDirectiveValue(1);
1131 if (IDVal == ".short")
1132 return ParseDirectiveValue(2);
1133 if (IDVal == ".value")
1134 return ParseDirectiveValue(2);
1135 if (IDVal == ".2byte")
1136 return ParseDirectiveValue(2);
1137 if (IDVal == ".long")
1138 return ParseDirectiveValue(4);
1139 if (IDVal == ".int")
1140 return ParseDirectiveValue(4);
1141 if (IDVal == ".4byte")
1142 return ParseDirectiveValue(4);
1143 if (IDVal == ".quad")
1144 return ParseDirectiveValue(8);
1145 if (IDVal == ".8byte")
1146 return ParseDirectiveValue(8);
1147 if (IDVal == ".single" || IDVal == ".float")
1148 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1149 if (IDVal == ".double")
1150 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1152 if (IDVal == ".align") {
1153 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1154 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1156 if (IDVal == ".align32") {
1157 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1158 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1160 if (IDVal == ".balign")
1161 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1162 if (IDVal == ".balignw")
1163 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1164 if (IDVal == ".balignl")
1165 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1166 if (IDVal == ".p2align")
1167 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1168 if (IDVal == ".p2alignw")
1169 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1170 if (IDVal == ".p2alignl")
1171 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1173 if (IDVal == ".org")
1174 return ParseDirectiveOrg();
1176 if (IDVal == ".fill")
1177 return ParseDirectiveFill();
1178 if (IDVal == ".space" || IDVal == ".skip")
1179 return ParseDirectiveSpace();
1180 if (IDVal == ".zero")
1181 return ParseDirectiveZero();
1183 // Symbol attribute directives
1185 if (IDVal == ".globl" || IDVal == ".global")
1186 return ParseDirectiveSymbolAttribute(MCSA_Global);
1187 if (IDVal == ".indirect_symbol")
1188 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1189 if (IDVal == ".lazy_reference")
1190 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1191 if (IDVal == ".no_dead_strip")
1192 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1193 if (IDVal == ".symbol_resolver")
1194 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1195 if (IDVal == ".private_extern")
1196 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1197 if (IDVal == ".reference")
1198 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1199 if (IDVal == ".weak_definition")
1200 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1201 if (IDVal == ".weak_reference")
1202 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1203 if (IDVal == ".weak_def_can_be_hidden")
1204 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1206 if (IDVal == ".comm" || IDVal == ".common")
1207 return ParseDirectiveComm(/*IsLocal=*/false);
1208 if (IDVal == ".lcomm")
1209 return ParseDirectiveComm(/*IsLocal=*/true);
1211 if (IDVal == ".abort")
1212 return ParseDirectiveAbort();
1213 if (IDVal == ".include")
1214 return ParseDirectiveInclude();
1215 if (IDVal == ".incbin")
1216 return ParseDirectiveIncbin();
1218 if (IDVal == ".code16")
1219 return TokError(Twine(IDVal) + " not supported yet");
1221 // Look up the handler in the handler table.
1222 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1223 DirectiveMap.lookup(IDVal);
1225 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1227 // Target hook for parsing target specific directives.
1228 if (!getTargetParser().ParseDirective(ID))
1231 bool retval = Warning(IDLoc, "ignoring directive for now");
1232 EatToEndOfStatement();
1236 CheckForValidSection();
1238 // Canonicalize the opcode to lower case.
1239 SmallString<128> Opcode;
1240 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1241 Opcode.push_back(tolower(IDVal[i]));
1243 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1244 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1247 // Dump the parsed representation, if requested.
1248 if (getShowParsedOperands()) {
1249 SmallString<256> Str;
1250 raw_svector_ostream OS(Str);
1251 OS << "parsed instruction: [";
1252 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1255 ParsedOperands[i]->print(OS);
1259 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1262 // If we are generating dwarf for assembly source files and the current
1263 // section is the initial text section then generate a .loc directive for
1265 if (!HadError && getContext().getGenDwarfForAssembly() &&
1266 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1267 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1268 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1269 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1270 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1274 // If parsing succeeded, match the instruction.
1276 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1279 // Free any parsed operands.
1280 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1281 delete ParsedOperands[i];
1283 // Don't skip the rest of the line, the instruction parser is responsible for
1288 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1289 /// since they may not be able to be tokenized to get to the end of line token.
1290 void AsmParser::EatToEndOfLine() {
1291 if (!Lexer.is(AsmToken::EndOfStatement))
1292 Lexer.LexUntilEndOfLine();
1297 /// ParseCppHashLineFilenameComment as this:
1298 /// ::= # number "filename"
1299 /// or just as a full line comment if it doesn't have a number and a string.
1300 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1301 Lex(); // Eat the hash token.
1303 if (getLexer().isNot(AsmToken::Integer)) {
1304 // Consume the line since in cases it is not a well-formed line directive,
1305 // as if were simply a full line comment.
1310 int64_t LineNumber = getTok().getIntVal();
1313 if (getLexer().isNot(AsmToken::String)) {
1318 StringRef Filename = getTok().getString();
1319 // Get rid of the enclosing quotes.
1320 Filename = Filename.substr(1, Filename.size()-2);
1322 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1324 CppHashFilename = Filename;
1325 CppHashLineNumber = LineNumber;
1327 // Ignore any trailing characters, they're just comment.
1332 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1333 /// for the Filename and LineNo if any in the diagnostic.
1334 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1335 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1336 raw_ostream &OS = errs();
1338 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1339 const SMLoc &DiagLoc = Diag.getLoc();
1340 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1341 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1343 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1344 // before printing the message.
1345 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1346 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1347 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1348 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1351 // If we have not parsed a cpp hash line filename comment or the source
1352 // manager changed or buffer changed (like in a nested include) then just
1353 // print the normal diagnostic using its Filename and LineNo.
1354 if (!Parser->CppHashLineNumber ||
1355 &DiagSrcMgr != &Parser->SrcMgr ||
1356 DiagBuf != CppHashBuf) {
1357 if (Parser->SavedDiagHandler)
1358 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1364 // Use the CppHashFilename and calculate a line number based on the
1365 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1367 const std::string Filename = Parser->CppHashFilename;
1369 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1370 int CppHashLocLineNo =
1371 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1372 int LineNo = Parser->CppHashLineNumber - 1 +
1373 (DiagLocLineNo - CppHashLocLineNo);
1375 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1376 Filename, LineNo, Diag.getColumnNo(),
1377 Diag.getKind(), Diag.getMessage(),
1378 Diag.getLineContents(), Diag.getRanges());
1380 if (Parser->SavedDiagHandler)
1381 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1383 NewDiag.print(0, OS);
1386 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1387 const std::vector<StringRef> &Parameters,
1388 const std::vector<std::vector<AsmToken> > &A,
1390 raw_svector_ostream OS(Buf);
1391 unsigned NParameters = Parameters.size();
1392 if (NParameters != 0 && NParameters != A.size())
1393 return Error(L, "Wrong number of arguments");
1395 while (!Body.empty()) {
1396 // Scan for the next substitution.
1397 std::size_t End = Body.size(), Pos = 0;
1398 for (; Pos != End; ++Pos) {
1399 // Check for a substitution or escape.
1401 // This macro has no parameters, look for $0, $1, etc.
1402 if (Body[Pos] != '$' || Pos + 1 == End)
1405 char Next = Body[Pos + 1];
1406 if (Next == '$' || Next == 'n' || isdigit(Next))
1409 // This macro has parameters, look for \foo, \bar, etc.
1410 if (Body[Pos] == '\\' && Pos + 1 != End)
1416 OS << Body.slice(0, Pos);
1418 // Check if we reached the end.
1423 switch (Body[Pos+1]) {
1429 // $n => number of arguments
1434 // $[0-9] => argument
1436 // Missing arguments are ignored.
1437 unsigned Index = Body[Pos+1] - '0';
1438 if (Index >= A.size())
1441 // Otherwise substitute with the token values, with spaces eliminated.
1442 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1443 ie = A[Index].end(); it != ie; ++it)
1444 OS << it->getString();
1450 unsigned I = Pos + 1;
1451 while (isalnum(Body[I]) && I + 1 != End)
1454 const char *Begin = Body.data() + Pos +1;
1455 StringRef Argument(Begin, I - (Pos +1));
1457 for (; Index < NParameters; ++Index)
1458 if (Parameters[Index] == Argument)
1461 // FIXME: We should error at the macro definition.
1462 if (Index == NParameters)
1463 return Error(L, "Parameter not found");
1465 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1466 ie = A[Index].end(); it != ie; ++it)
1467 OS << it->getString();
1469 Pos += 1 + Argument.size();
1471 // Update the scan point.
1472 Body = Body.substr(Pos);
1475 // We include the .endmacro in the buffer as our queue to exit the macro
1477 OS << ".endmacro\n";
1481 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1483 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1487 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1489 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1490 // this, although we should protect against infinite loops.
1491 if (ActiveMacros.size() == 20)
1492 return TokError("macros cannot be nested more than 20 levels deep");
1494 // Parse the macro instantiation arguments.
1495 std::vector<std::vector<AsmToken> > MacroArguments;
1496 MacroArguments.push_back(std::vector<AsmToken>());
1497 unsigned ParenLevel = 0;
1499 if (Lexer.is(AsmToken::Eof))
1500 return TokError("unexpected token in macro instantiation");
1501 if (Lexer.is(AsmToken::EndOfStatement))
1504 // If we aren't inside parentheses and this is a comma, start a new token
1506 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1507 MacroArguments.push_back(std::vector<AsmToken>());
1509 // Adjust the current parentheses level.
1510 if (Lexer.is(AsmToken::LParen))
1512 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1515 // Append the token to the current argument list.
1516 MacroArguments.back().push_back(getTok());
1521 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1522 // to hold the macro body with substitutions.
1523 SmallString<256> Buf;
1524 StringRef Body = M->Body;
1526 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1529 MemoryBuffer *Instantiation =
1530 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1532 // Create the macro instantiation object and add to the current macro
1533 // instantiation stack.
1534 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1537 ActiveMacros.push_back(MI);
1539 // Jump to the macro instantiation and prime the lexer.
1540 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1541 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1547 void AsmParser::HandleMacroExit() {
1548 // Jump to the EndOfStatement we should return to, and consume it.
1549 JumpToLoc(ActiveMacros.back()->ExitLoc);
1552 // Pop the instantiation entry.
1553 delete ActiveMacros.back();
1554 ActiveMacros.pop_back();
1557 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1558 switch (Value->getKind()) {
1559 case MCExpr::Binary: {
1560 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1561 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1564 case MCExpr::Target:
1565 case MCExpr::Constant:
1567 case MCExpr::SymbolRef: {
1568 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1570 return IsUsedIn(Sym, S.getVariableValue());
1574 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1577 llvm_unreachable("Unknown expr kind!");
1580 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1581 // FIXME: Use better location, we should use proper tokens.
1582 SMLoc EqualLoc = Lexer.getLoc();
1584 const MCExpr *Value;
1585 if (ParseExpression(Value))
1588 // Note: we don't count b as used in "a = b". This is to allow
1592 if (Lexer.isNot(AsmToken::EndOfStatement))
1593 return TokError("unexpected token in assignment");
1595 // Error on assignment to '.'.
1597 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1598 "(use '.space' or '.org').)"));
1601 // Eat the end of statement marker.
1604 // Validate that the LHS is allowed to be a variable (either it has not been
1605 // used as a symbol, or it is an absolute symbol).
1606 MCSymbol *Sym = getContext().LookupSymbol(Name);
1608 // Diagnose assignment to a label.
1610 // FIXME: Diagnostics. Note the location of the definition as a label.
1611 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1612 if (IsUsedIn(Sym, Value))
1613 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1614 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1615 ; // Allow redefinitions of undefined symbols only used in directives.
1616 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1617 return Error(EqualLoc, "redefinition of '" + Name + "'");
1618 else if (!Sym->isVariable())
1619 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1620 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1621 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1624 // Don't count these checks as uses.
1625 Sym->setUsed(false);
1627 Sym = getContext().GetOrCreateSymbol(Name);
1629 // FIXME: Handle '.'.
1631 // Do the assignment.
1632 Out.EmitAssignment(Sym, Value);
1637 /// ParseIdentifier:
1640 bool AsmParser::ParseIdentifier(StringRef &Res) {
1641 // The assembler has relaxed rules for accepting identifiers, in particular we
1642 // allow things like '.globl $foo', which would normally be separate
1643 // tokens. At this level, we have already lexed so we cannot (currently)
1644 // handle this as a context dependent token, instead we detect adjacent tokens
1645 // and return the combined identifier.
1646 if (Lexer.is(AsmToken::Dollar)) {
1647 SMLoc DollarLoc = getLexer().getLoc();
1649 // Consume the dollar sign, and check for a following identifier.
1651 if (Lexer.isNot(AsmToken::Identifier))
1654 // We have a '$' followed by an identifier, make sure they are adjacent.
1655 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1658 // Construct the joined identifier and consume the token.
1659 Res = StringRef(DollarLoc.getPointer(),
1660 getTok().getIdentifier().size() + 1);
1665 if (Lexer.isNot(AsmToken::Identifier) &&
1666 Lexer.isNot(AsmToken::String))
1669 Res = getTok().getIdentifier();
1671 Lex(); // Consume the identifier token.
1676 /// ParseDirectiveSet:
1677 /// ::= .equ identifier ',' expression
1678 /// ::= .equiv identifier ',' expression
1679 /// ::= .set identifier ',' expression
1680 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1683 if (ParseIdentifier(Name))
1684 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1686 if (getLexer().isNot(AsmToken::Comma))
1687 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1690 return ParseAssignment(Name, allow_redef);
1693 bool AsmParser::ParseEscapedString(std::string &Data) {
1694 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1697 StringRef Str = getTok().getStringContents();
1698 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1699 if (Str[i] != '\\') {
1704 // Recognize escaped characters. Note that this escape semantics currently
1705 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1708 return TokError("unexpected backslash at end of string");
1710 // Recognize octal sequences.
1711 if ((unsigned) (Str[i] - '0') <= 7) {
1712 // Consume up to three octal characters.
1713 unsigned Value = Str[i] - '0';
1715 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1717 Value = Value * 8 + (Str[i] - '0');
1719 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1721 Value = Value * 8 + (Str[i] - '0');
1726 return TokError("invalid octal escape sequence (out of range)");
1728 Data += (unsigned char) Value;
1732 // Otherwise recognize individual escapes.
1735 // Just reject invalid escape sequences for now.
1736 return TokError("invalid escape sequence (unrecognized character)");
1738 case 'b': Data += '\b'; break;
1739 case 'f': Data += '\f'; break;
1740 case 'n': Data += '\n'; break;
1741 case 'r': Data += '\r'; break;
1742 case 't': Data += '\t'; break;
1743 case '"': Data += '"'; break;
1744 case '\\': Data += '\\'; break;
1751 /// ParseDirectiveAscii:
1752 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1753 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1754 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1755 CheckForValidSection();
1758 if (getLexer().isNot(AsmToken::String))
1759 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1762 if (ParseEscapedString(Data))
1765 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1767 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1771 if (getLexer().is(AsmToken::EndOfStatement))
1774 if (getLexer().isNot(AsmToken::Comma))
1775 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1784 /// ParseDirectiveValue
1785 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1786 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1787 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1788 CheckForValidSection();
1791 const MCExpr *Value;
1792 SMLoc ExprLoc = getLexer().getLoc();
1793 if (ParseExpression(Value))
1796 // Special case constant expressions to match code generator.
1797 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1798 assert(Size <= 8 && "Invalid size");
1799 uint64_t IntValue = MCE->getValue();
1800 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1801 return Error(ExprLoc, "literal value out of range for directive");
1802 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1804 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1806 if (getLexer().is(AsmToken::EndOfStatement))
1809 // FIXME: Improve diagnostic.
1810 if (getLexer().isNot(AsmToken::Comma))
1811 return TokError("unexpected token in directive");
1820 /// ParseDirectiveRealValue
1821 /// ::= (.single | .double) [ expression (, expression)* ]
1822 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1823 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1824 CheckForValidSection();
1827 // We don't truly support arithmetic on floating point expressions, so we
1828 // have to manually parse unary prefixes.
1830 if (getLexer().is(AsmToken::Minus)) {
1833 } else if (getLexer().is(AsmToken::Plus))
1836 if (getLexer().isNot(AsmToken::Integer) &&
1837 getLexer().isNot(AsmToken::Real) &&
1838 getLexer().isNot(AsmToken::Identifier))
1839 return TokError("unexpected token in directive");
1841 // Convert to an APFloat.
1842 APFloat Value(Semantics);
1843 StringRef IDVal = getTok().getString();
1844 if (getLexer().is(AsmToken::Identifier)) {
1845 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1846 Value = APFloat::getInf(Semantics);
1847 else if (!IDVal.compare_lower("nan"))
1848 Value = APFloat::getNaN(Semantics, false, ~0);
1850 return TokError("invalid floating point literal");
1851 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1852 APFloat::opInvalidOp)
1853 return TokError("invalid floating point literal");
1857 // Consume the numeric token.
1860 // Emit the value as an integer.
1861 APInt AsInt = Value.bitcastToAPInt();
1862 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1863 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1865 if (getLexer().is(AsmToken::EndOfStatement))
1868 if (getLexer().isNot(AsmToken::Comma))
1869 return TokError("unexpected token in directive");
1878 /// ParseDirectiveSpace
1879 /// ::= .space expression [ , expression ]
1880 bool AsmParser::ParseDirectiveSpace() {
1881 CheckForValidSection();
1884 if (ParseAbsoluteExpression(NumBytes))
1887 int64_t FillExpr = 0;
1888 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1889 if (getLexer().isNot(AsmToken::Comma))
1890 return TokError("unexpected token in '.space' directive");
1893 if (ParseAbsoluteExpression(FillExpr))
1896 if (getLexer().isNot(AsmToken::EndOfStatement))
1897 return TokError("unexpected token in '.space' directive");
1903 return TokError("invalid number of bytes in '.space' directive");
1905 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1906 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1911 /// ParseDirectiveZero
1912 /// ::= .zero expression
1913 bool AsmParser::ParseDirectiveZero() {
1914 CheckForValidSection();
1917 if (ParseAbsoluteExpression(NumBytes))
1921 if (getLexer().is(AsmToken::Comma)) {
1923 if (ParseAbsoluteExpression(Val))
1927 if (getLexer().isNot(AsmToken::EndOfStatement))
1928 return TokError("unexpected token in '.zero' directive");
1932 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1937 /// ParseDirectiveFill
1938 /// ::= .fill expression , expression , expression
1939 bool AsmParser::ParseDirectiveFill() {
1940 CheckForValidSection();
1943 if (ParseAbsoluteExpression(NumValues))
1946 if (getLexer().isNot(AsmToken::Comma))
1947 return TokError("unexpected token in '.fill' directive");
1951 if (ParseAbsoluteExpression(FillSize))
1954 if (getLexer().isNot(AsmToken::Comma))
1955 return TokError("unexpected token in '.fill' directive");
1959 if (ParseAbsoluteExpression(FillExpr))
1962 if (getLexer().isNot(AsmToken::EndOfStatement))
1963 return TokError("unexpected token in '.fill' directive");
1967 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1968 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1970 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1971 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1976 /// ParseDirectiveOrg
1977 /// ::= .org expression [ , expression ]
1978 bool AsmParser::ParseDirectiveOrg() {
1979 CheckForValidSection();
1981 const MCExpr *Offset;
1982 SMLoc Loc = getTok().getLoc();
1983 if (ParseExpression(Offset))
1986 // Parse optional fill expression.
1987 int64_t FillExpr = 0;
1988 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1989 if (getLexer().isNot(AsmToken::Comma))
1990 return TokError("unexpected token in '.org' directive");
1993 if (ParseAbsoluteExpression(FillExpr))
1996 if (getLexer().isNot(AsmToken::EndOfStatement))
1997 return TokError("unexpected token in '.org' directive");
2002 // Only limited forms of relocatable expressions are accepted here, it
2003 // has to be relative to the current section. The streamer will return
2004 // 'true' if the expression wasn't evaluatable.
2005 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2006 return Error(Loc, "expected assembly-time absolute expression");
2011 /// ParseDirectiveAlign
2012 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2013 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2014 CheckForValidSection();
2016 SMLoc AlignmentLoc = getLexer().getLoc();
2018 if (ParseAbsoluteExpression(Alignment))
2022 bool HasFillExpr = false;
2023 int64_t FillExpr = 0;
2024 int64_t MaxBytesToFill = 0;
2025 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2026 if (getLexer().isNot(AsmToken::Comma))
2027 return TokError("unexpected token in directive");
2030 // The fill expression can be omitted while specifying a maximum number of
2031 // alignment bytes, e.g:
2033 if (getLexer().isNot(AsmToken::Comma)) {
2035 if (ParseAbsoluteExpression(FillExpr))
2039 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2040 if (getLexer().isNot(AsmToken::Comma))
2041 return TokError("unexpected token in directive");
2044 MaxBytesLoc = getLexer().getLoc();
2045 if (ParseAbsoluteExpression(MaxBytesToFill))
2048 if (getLexer().isNot(AsmToken::EndOfStatement))
2049 return TokError("unexpected token in directive");
2058 // Compute alignment in bytes.
2060 // FIXME: Diagnose overflow.
2061 if (Alignment >= 32) {
2062 Error(AlignmentLoc, "invalid alignment value");
2066 Alignment = 1ULL << Alignment;
2069 // Diagnose non-sensical max bytes to align.
2070 if (MaxBytesLoc.isValid()) {
2071 if (MaxBytesToFill < 1) {
2072 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2073 "many bytes, ignoring maximum bytes expression");
2077 if (MaxBytesToFill >= Alignment) {
2078 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2084 // Check whether we should use optimal code alignment for this .align
2086 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2087 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2088 ValueSize == 1 && UseCodeAlign) {
2089 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2091 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2092 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2099 /// ParseDirectiveSymbolAttribute
2100 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2101 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2102 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2105 SMLoc Loc = getTok().getLoc();
2107 if (ParseIdentifier(Name))
2108 return Error(Loc, "expected identifier in directive");
2110 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2112 // Assembler local symbols don't make any sense here. Complain loudly.
2113 if (Sym->isTemporary())
2114 return Error(Loc, "non-local symbol required in directive");
2116 getStreamer().EmitSymbolAttribute(Sym, Attr);
2118 if (getLexer().is(AsmToken::EndOfStatement))
2121 if (getLexer().isNot(AsmToken::Comma))
2122 return TokError("unexpected token in directive");
2131 /// ParseDirectiveComm
2132 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2133 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2134 CheckForValidSection();
2136 SMLoc IDLoc = getLexer().getLoc();
2138 if (ParseIdentifier(Name))
2139 return TokError("expected identifier in directive");
2141 // Handle the identifier as the key symbol.
2142 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2144 if (getLexer().isNot(AsmToken::Comma))
2145 return TokError("unexpected token in directive");
2149 SMLoc SizeLoc = getLexer().getLoc();
2150 if (ParseAbsoluteExpression(Size))
2153 int64_t Pow2Alignment = 0;
2154 SMLoc Pow2AlignmentLoc;
2155 if (getLexer().is(AsmToken::Comma)) {
2157 Pow2AlignmentLoc = getLexer().getLoc();
2158 if (ParseAbsoluteExpression(Pow2Alignment))
2161 // If this target takes alignments in bytes (not log) validate and convert.
2162 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2163 if (!isPowerOf2_64(Pow2Alignment))
2164 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2165 Pow2Alignment = Log2_64(Pow2Alignment);
2169 if (getLexer().isNot(AsmToken::EndOfStatement))
2170 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2174 // NOTE: a size of zero for a .comm should create a undefined symbol
2175 // but a size of .lcomm creates a bss symbol of size zero.
2177 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2178 "be less than zero");
2180 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2181 // may internally end up wanting an alignment in bytes.
2182 // FIXME: Diagnose overflow.
2183 if (Pow2Alignment < 0)
2184 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2185 "alignment, can't be less than zero");
2187 if (!Sym->isUndefined())
2188 return Error(IDLoc, "invalid symbol redefinition");
2190 // '.lcomm' is equivalent to '.zerofill'.
2191 // Create the Symbol as a common or local common with Size and Pow2Alignment
2193 getStreamer().EmitZerofill(Ctx.getMachOSection(
2194 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2195 0, SectionKind::getBSS()),
2196 Sym, Size, 1 << Pow2Alignment);
2200 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2204 /// ParseDirectiveAbort
2205 /// ::= .abort [... message ...]
2206 bool AsmParser::ParseDirectiveAbort() {
2207 // FIXME: Use loc from directive.
2208 SMLoc Loc = getLexer().getLoc();
2210 StringRef Str = ParseStringToEndOfStatement();
2211 if (getLexer().isNot(AsmToken::EndOfStatement))
2212 return TokError("unexpected token in '.abort' directive");
2217 Error(Loc, ".abort detected. Assembly stopping.");
2219 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2220 // FIXME: Actually abort assembly here.
2225 /// ParseDirectiveInclude
2226 /// ::= .include "filename"
2227 bool AsmParser::ParseDirectiveInclude() {
2228 if (getLexer().isNot(AsmToken::String))
2229 return TokError("expected string in '.include' directive");
2231 std::string Filename = getTok().getString();
2232 SMLoc IncludeLoc = getLexer().getLoc();
2235 if (getLexer().isNot(AsmToken::EndOfStatement))
2236 return TokError("unexpected token in '.include' directive");
2238 // Strip the quotes.
2239 Filename = Filename.substr(1, Filename.size()-2);
2241 // Attempt to switch the lexer to the included file before consuming the end
2242 // of statement to avoid losing it when we switch.
2243 if (EnterIncludeFile(Filename)) {
2244 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2251 /// ParseDirectiveIncbin
2252 /// ::= .incbin "filename"
2253 bool AsmParser::ParseDirectiveIncbin() {
2254 if (getLexer().isNot(AsmToken::String))
2255 return TokError("expected string in '.incbin' directive");
2257 std::string Filename = getTok().getString();
2258 SMLoc IncbinLoc = getLexer().getLoc();
2261 if (getLexer().isNot(AsmToken::EndOfStatement))
2262 return TokError("unexpected token in '.incbin' directive");
2264 // Strip the quotes.
2265 Filename = Filename.substr(1, Filename.size()-2);
2267 // Attempt to process the included file.
2268 if (ProcessIncbinFile(Filename)) {
2269 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2276 /// ParseDirectiveIf
2277 /// ::= .if expression
2278 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2279 TheCondStack.push_back(TheCondState);
2280 TheCondState.TheCond = AsmCond::IfCond;
2281 if(TheCondState.Ignore) {
2282 EatToEndOfStatement();
2286 if (ParseAbsoluteExpression(ExprValue))
2289 if (getLexer().isNot(AsmToken::EndOfStatement))
2290 return TokError("unexpected token in '.if' directive");
2294 TheCondState.CondMet = ExprValue;
2295 TheCondState.Ignore = !TheCondState.CondMet;
2301 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2303 TheCondStack.push_back(TheCondState);
2304 TheCondState.TheCond = AsmCond::IfCond;
2306 if (TheCondState.Ignore) {
2307 EatToEndOfStatement();
2309 if (ParseIdentifier(Name))
2310 return TokError("expected identifier after '.ifdef'");
2314 MCSymbol *Sym = getContext().LookupSymbol(Name);
2317 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2319 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2320 TheCondState.Ignore = !TheCondState.CondMet;
2326 /// ParseDirectiveElseIf
2327 /// ::= .elseif expression
2328 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2329 if (TheCondState.TheCond != AsmCond::IfCond &&
2330 TheCondState.TheCond != AsmCond::ElseIfCond)
2331 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2333 TheCondState.TheCond = AsmCond::ElseIfCond;
2335 bool LastIgnoreState = false;
2336 if (!TheCondStack.empty())
2337 LastIgnoreState = TheCondStack.back().Ignore;
2338 if (LastIgnoreState || TheCondState.CondMet) {
2339 TheCondState.Ignore = true;
2340 EatToEndOfStatement();
2344 if (ParseAbsoluteExpression(ExprValue))
2347 if (getLexer().isNot(AsmToken::EndOfStatement))
2348 return TokError("unexpected token in '.elseif' directive");
2351 TheCondState.CondMet = ExprValue;
2352 TheCondState.Ignore = !TheCondState.CondMet;
2358 /// ParseDirectiveElse
2360 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2361 if (getLexer().isNot(AsmToken::EndOfStatement))
2362 return TokError("unexpected token in '.else' directive");
2366 if (TheCondState.TheCond != AsmCond::IfCond &&
2367 TheCondState.TheCond != AsmCond::ElseIfCond)
2368 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2370 TheCondState.TheCond = AsmCond::ElseCond;
2371 bool LastIgnoreState = false;
2372 if (!TheCondStack.empty())
2373 LastIgnoreState = TheCondStack.back().Ignore;
2374 if (LastIgnoreState || TheCondState.CondMet)
2375 TheCondState.Ignore = true;
2377 TheCondState.Ignore = false;
2382 /// ParseDirectiveEndIf
2384 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2385 if (getLexer().isNot(AsmToken::EndOfStatement))
2386 return TokError("unexpected token in '.endif' directive");
2390 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2391 TheCondStack.empty())
2392 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2394 if (!TheCondStack.empty()) {
2395 TheCondState = TheCondStack.back();
2396 TheCondStack.pop_back();
2402 /// ParseDirectiveFile
2403 /// ::= .file [number] filename
2404 /// ::= .file number directory filename
2405 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2406 // FIXME: I'm not sure what this is.
2407 int64_t FileNumber = -1;
2408 SMLoc FileNumberLoc = getLexer().getLoc();
2409 if (getLexer().is(AsmToken::Integer)) {
2410 FileNumber = getTok().getIntVal();
2414 return TokError("file number less than one");
2417 if (getLexer().isNot(AsmToken::String))
2418 return TokError("unexpected token in '.file' directive");
2420 // Usually the directory and filename together, otherwise just the directory.
2421 StringRef Path = getTok().getString();
2422 Path = Path.substr(1, Path.size()-2);
2425 StringRef Directory;
2427 if (getLexer().is(AsmToken::String)) {
2428 if (FileNumber == -1)
2429 return TokError("explicit path specified, but no file number");
2430 Filename = getTok().getString();
2431 Filename = Filename.substr(1, Filename.size()-2);
2438 if (getLexer().isNot(AsmToken::EndOfStatement))
2439 return TokError("unexpected token in '.file' directive");
2441 if (FileNumber == -1)
2442 getStreamer().EmitFileDirective(Filename);
2444 if (getContext().getGenDwarfForAssembly() == true)
2445 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2446 "used to generate dwarf debug info for assembly code");
2448 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2449 Error(FileNumberLoc, "file number already allocated");
2455 /// ParseDirectiveLine
2456 /// ::= .line [number]
2457 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2458 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2459 if (getLexer().isNot(AsmToken::Integer))
2460 return TokError("unexpected token in '.line' directive");
2462 int64_t LineNumber = getTok().getIntVal();
2466 // FIXME: Do something with the .line.
2469 if (getLexer().isNot(AsmToken::EndOfStatement))
2470 return TokError("unexpected token in '.line' directive");
2476 /// ParseDirectiveLoc
2477 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2478 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2479 /// The first number is a file number, must have been previously assigned with
2480 /// a .file directive, the second number is the line number and optionally the
2481 /// third number is a column position (zero if not specified). The remaining
2482 /// optional items are .loc sub-directives.
2483 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2485 if (getLexer().isNot(AsmToken::Integer))
2486 return TokError("unexpected token in '.loc' directive");
2487 int64_t FileNumber = getTok().getIntVal();
2489 return TokError("file number less than one in '.loc' directive");
2490 if (!getContext().isValidDwarfFileNumber(FileNumber))
2491 return TokError("unassigned file number in '.loc' directive");
2494 int64_t LineNumber = 0;
2495 if (getLexer().is(AsmToken::Integer)) {
2496 LineNumber = getTok().getIntVal();
2498 return TokError("line number less than one in '.loc' directive");
2502 int64_t ColumnPos = 0;
2503 if (getLexer().is(AsmToken::Integer)) {
2504 ColumnPos = getTok().getIntVal();
2506 return TokError("column position less than zero in '.loc' directive");
2510 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2512 int64_t Discriminator = 0;
2513 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2515 if (getLexer().is(AsmToken::EndOfStatement))
2519 SMLoc Loc = getTok().getLoc();
2520 if (getParser().ParseIdentifier(Name))
2521 return TokError("unexpected token in '.loc' directive");
2523 if (Name == "basic_block")
2524 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2525 else if (Name == "prologue_end")
2526 Flags |= DWARF2_FLAG_PROLOGUE_END;
2527 else if (Name == "epilogue_begin")
2528 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2529 else if (Name == "is_stmt") {
2530 SMLoc Loc = getTok().getLoc();
2531 const MCExpr *Value;
2532 if (getParser().ParseExpression(Value))
2534 // The expression must be the constant 0 or 1.
2535 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2536 int Value = MCE->getValue();
2538 Flags &= ~DWARF2_FLAG_IS_STMT;
2539 else if (Value == 1)
2540 Flags |= DWARF2_FLAG_IS_STMT;
2542 return Error(Loc, "is_stmt value not 0 or 1");
2545 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2548 else if (Name == "isa") {
2549 SMLoc Loc = getTok().getLoc();
2550 const MCExpr *Value;
2551 if (getParser().ParseExpression(Value))
2553 // The expression must be a constant greater or equal to 0.
2554 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2555 int Value = MCE->getValue();
2557 return Error(Loc, "isa number less than zero");
2561 return Error(Loc, "isa number not a constant value");
2564 else if (Name == "discriminator") {
2565 if (getParser().ParseAbsoluteExpression(Discriminator))
2569 return Error(Loc, "unknown sub-directive in '.loc' directive");
2572 if (getLexer().is(AsmToken::EndOfStatement))
2577 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2578 Isa, Discriminator, StringRef());
2583 /// ParseDirectiveStabs
2584 /// ::= .stabs string, number, number, number
2585 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2586 SMLoc DirectiveLoc) {
2587 return TokError("unsupported directive '" + Directive + "'");
2590 /// ParseDirectiveCFISections
2591 /// ::= .cfi_sections section [, section]
2592 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2593 SMLoc DirectiveLoc) {
2598 if (getParser().ParseIdentifier(Name))
2599 return TokError("Expected an identifier");
2601 if (Name == ".eh_frame")
2603 else if (Name == ".debug_frame")
2606 if (getLexer().is(AsmToken::Comma)) {
2609 if (getParser().ParseIdentifier(Name))
2610 return TokError("Expected an identifier");
2612 if (Name == ".eh_frame")
2614 else if (Name == ".debug_frame")
2618 getStreamer().EmitCFISections(EH, Debug);
2623 /// ParseDirectiveCFIStartProc
2624 /// ::= .cfi_startproc
2625 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2626 SMLoc DirectiveLoc) {
2627 getStreamer().EmitCFIStartProc();
2631 /// ParseDirectiveCFIEndProc
2632 /// ::= .cfi_endproc
2633 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2634 getStreamer().EmitCFIEndProc();
2638 /// ParseRegisterOrRegisterNumber - parse register name or number.
2639 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2640 SMLoc DirectiveLoc) {
2643 if (getLexer().isNot(AsmToken::Integer)) {
2644 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2647 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2649 return getParser().ParseAbsoluteExpression(Register);
2654 /// ParseDirectiveCFIDefCfa
2655 /// ::= .cfi_def_cfa register, offset
2656 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2657 SMLoc DirectiveLoc) {
2658 int64_t Register = 0;
2659 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2662 if (getLexer().isNot(AsmToken::Comma))
2663 return TokError("unexpected token in directive");
2667 if (getParser().ParseAbsoluteExpression(Offset))
2670 getStreamer().EmitCFIDefCfa(Register, Offset);
2674 /// ParseDirectiveCFIDefCfaOffset
2675 /// ::= .cfi_def_cfa_offset offset
2676 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2677 SMLoc DirectiveLoc) {
2679 if (getParser().ParseAbsoluteExpression(Offset))
2682 getStreamer().EmitCFIDefCfaOffset(Offset);
2686 /// ParseDirectiveCFIAdjustCfaOffset
2687 /// ::= .cfi_adjust_cfa_offset adjustment
2688 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2689 SMLoc DirectiveLoc) {
2690 int64_t Adjustment = 0;
2691 if (getParser().ParseAbsoluteExpression(Adjustment))
2694 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2698 /// ParseDirectiveCFIDefCfaRegister
2699 /// ::= .cfi_def_cfa_register register
2700 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2701 SMLoc DirectiveLoc) {
2702 int64_t Register = 0;
2703 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2706 getStreamer().EmitCFIDefCfaRegister(Register);
2710 /// ParseDirectiveCFIOffset
2711 /// ::= .cfi_offset register, offset
2712 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2713 int64_t Register = 0;
2716 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2719 if (getLexer().isNot(AsmToken::Comma))
2720 return TokError("unexpected token in directive");
2723 if (getParser().ParseAbsoluteExpression(Offset))
2726 getStreamer().EmitCFIOffset(Register, Offset);
2730 /// ParseDirectiveCFIRelOffset
2731 /// ::= .cfi_rel_offset register, offset
2732 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2733 SMLoc DirectiveLoc) {
2734 int64_t Register = 0;
2736 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2739 if (getLexer().isNot(AsmToken::Comma))
2740 return TokError("unexpected token in directive");
2744 if (getParser().ParseAbsoluteExpression(Offset))
2747 getStreamer().EmitCFIRelOffset(Register, Offset);
2751 static bool isValidEncoding(int64_t Encoding) {
2752 if (Encoding & ~0xff)
2755 if (Encoding == dwarf::DW_EH_PE_omit)
2758 const unsigned Format = Encoding & 0xf;
2759 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2760 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2761 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2762 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2765 const unsigned Application = Encoding & 0x70;
2766 if (Application != dwarf::DW_EH_PE_absptr &&
2767 Application != dwarf::DW_EH_PE_pcrel)
2773 /// ParseDirectiveCFIPersonalityOrLsda
2774 /// ::= .cfi_personality encoding, [symbol_name]
2775 /// ::= .cfi_lsda encoding, [symbol_name]
2776 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2777 SMLoc DirectiveLoc) {
2778 int64_t Encoding = 0;
2779 if (getParser().ParseAbsoluteExpression(Encoding))
2781 if (Encoding == dwarf::DW_EH_PE_omit)
2784 if (!isValidEncoding(Encoding))
2785 return TokError("unsupported encoding.");
2787 if (getLexer().isNot(AsmToken::Comma))
2788 return TokError("unexpected token in directive");
2792 if (getParser().ParseIdentifier(Name))
2793 return TokError("expected identifier in directive");
2795 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2797 if (IDVal == ".cfi_personality")
2798 getStreamer().EmitCFIPersonality(Sym, Encoding);
2800 assert(IDVal == ".cfi_lsda");
2801 getStreamer().EmitCFILsda(Sym, Encoding);
2806 /// ParseDirectiveCFIRememberState
2807 /// ::= .cfi_remember_state
2808 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2809 SMLoc DirectiveLoc) {
2810 getStreamer().EmitCFIRememberState();
2814 /// ParseDirectiveCFIRestoreState
2815 /// ::= .cfi_remember_state
2816 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2817 SMLoc DirectiveLoc) {
2818 getStreamer().EmitCFIRestoreState();
2822 /// ParseDirectiveCFISameValue
2823 /// ::= .cfi_same_value register
2824 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2825 SMLoc DirectiveLoc) {
2826 int64_t Register = 0;
2828 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2831 getStreamer().EmitCFISameValue(Register);
2836 /// ParseDirectiveCFIRestore
2837 /// ::= .cfi_restore register
2838 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
2839 SMLoc DirectiveLoc) {
2840 int64_t Register = 0;
2841 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2844 getStreamer().EmitCFIRestore(Register);
2849 /// ParseDirectiveCFIEscape
2850 /// ::= .cfi_escape expression[,...]
2851 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
2852 SMLoc DirectiveLoc) {
2855 if (getParser().ParseAbsoluteExpression(CurrValue))
2858 Values.push_back((uint8_t)CurrValue);
2860 while (getLexer().is(AsmToken::Comma)) {
2863 if (getParser().ParseAbsoluteExpression(CurrValue))
2866 Values.push_back((uint8_t)CurrValue);
2869 getStreamer().EmitCFIEscape(Values);
2873 /// ParseDirectiveCFISignalFrame
2874 /// ::= .cfi_signal_frame
2875 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
2876 SMLoc DirectiveLoc) {
2877 if (getLexer().isNot(AsmToken::EndOfStatement))
2878 return Error(getLexer().getLoc(),
2879 "unexpected token in '" + Directive + "' directive");
2881 getStreamer().EmitCFISignalFrame();
2886 /// ParseDirectiveMacrosOnOff
2889 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2890 SMLoc DirectiveLoc) {
2891 if (getLexer().isNot(AsmToken::EndOfStatement))
2892 return Error(getLexer().getLoc(),
2893 "unexpected token in '" + Directive + "' directive");
2895 getParser().MacrosEnabled = Directive == ".macros_on";
2900 /// ParseDirectiveMacro
2901 /// ::= .macro name [parameters]
2902 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2903 SMLoc DirectiveLoc) {
2905 if (getParser().ParseIdentifier(Name))
2906 return TokError("expected identifier in directive");
2908 std::vector<StringRef> Parameters;
2909 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2911 StringRef Parameter;
2912 if (getParser().ParseIdentifier(Parameter))
2913 return TokError("expected identifier in directive");
2914 Parameters.push_back(Parameter);
2916 if (getLexer().isNot(AsmToken::Comma))
2922 if (getLexer().isNot(AsmToken::EndOfStatement))
2923 return TokError("unexpected token in '.macro' directive");
2925 // Eat the end of statement.
2928 AsmToken EndToken, StartToken = getTok();
2930 // Lex the macro definition.
2932 // Check whether we have reached the end of the file.
2933 if (getLexer().is(AsmToken::Eof))
2934 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2936 // Otherwise, check whether we have reach the .endmacro.
2937 if (getLexer().is(AsmToken::Identifier) &&
2938 (getTok().getIdentifier() == ".endm" ||
2939 getTok().getIdentifier() == ".endmacro")) {
2940 EndToken = getTok();
2942 if (getLexer().isNot(AsmToken::EndOfStatement))
2943 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2948 // Otherwise, scan til the end of the statement.
2949 getParser().EatToEndOfStatement();
2952 if (getParser().MacroMap.lookup(Name)) {
2953 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2956 const char *BodyStart = StartToken.getLoc().getPointer();
2957 const char *BodyEnd = EndToken.getLoc().getPointer();
2958 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2959 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
2963 /// ParseDirectiveEndMacro
2966 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2967 SMLoc DirectiveLoc) {
2968 if (getLexer().isNot(AsmToken::EndOfStatement))
2969 return TokError("unexpected token in '" + Directive + "' directive");
2971 // If we are inside a macro instantiation, terminate the current
2973 if (!getParser().ActiveMacros.empty()) {
2974 getParser().HandleMacroExit();
2978 // Otherwise, this .endmacro is a stray entry in the file; well formed
2979 // .endmacro directives are handled during the macro definition parsing.
2980 return TokError("unexpected '" + Directive + "' in file, "
2981 "no current macro definition");
2984 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2985 getParser().CheckForValidSection();
2987 const MCExpr *Value;
2989 if (getParser().ParseExpression(Value))
2992 if (getLexer().isNot(AsmToken::EndOfStatement))
2993 return TokError("unexpected token in directive");
2995 if (DirName[1] == 's')
2996 getStreamer().EmitSLEB128Value(Value);
2998 getStreamer().EmitULEB128Value(Value);
3004 /// \brief Create an MCAsmParser instance.
3005 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3006 MCContext &C, MCStreamer &Out,
3007 const MCAsmInfo &MAI) {
3008 return new AsmParser(SM, C, Out, MAI);