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/MCExpr.h"
22 #include "llvm/MC/MCParser/AsmCond.h"
23 #include "llvm/MC/MCParser/AsmLexer.h"
24 #include "llvm/MC/MCParser/MCAsmParser.h"
25 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
26 #include "llvm/MC/MCSectionMachO.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCDwarf.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetAsmInfo.h"
34 #include "llvm/Target/TargetAsmParser.h"
41 /// \brief Helper class for tracking macro definitions.
47 Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
50 /// \brief Helper class for storing information about an active macro
52 struct MacroInstantiation {
53 /// The macro being instantiated.
54 const Macro *TheMacro;
56 /// The macro instantiation with substitutions.
57 MemoryBuffer *Instantiation;
59 /// The location of the instantiation.
60 SMLoc InstantiationLoc;
62 /// The location where parsing should resume upon instantiation completion.
66 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
67 const std::vector<std::vector<AsmToken> > &A);
70 /// \brief The concrete assembly parser instance.
71 class AsmParser : public MCAsmParser {
72 friend class GenericAsmParser;
74 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
75 void operator=(const AsmParser &); // DO NOT IMPLEMENT
81 MCAsmParserExtension *GenericParser;
82 MCAsmParserExtension *PlatformParser;
84 /// This is the current buffer index we're lexing from as managed by the
89 std::vector<AsmCond> TheCondStack;
91 /// DirectiveMap - This is a table handlers for directives. Each handler is
92 /// invoked after the directive identifier is read and is responsible for
93 /// parsing and validating the rest of the directive. The handler is passed
94 /// in the directive name and the location of the directive keyword.
95 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
97 /// MacroMap - Map of currently defined macros.
98 StringMap<Macro*> MacroMap;
100 /// ActiveMacros - Stack of active macro instantiations.
101 std::vector<MacroInstantiation*> ActiveMacros;
103 /// Boolean tracking whether macro substitution is enabled.
104 unsigned MacrosEnabled : 1;
106 /// Flag tracking whether any errors have been encountered.
107 unsigned HadError : 1;
110 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
111 const MCAsmInfo &MAI);
114 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
116 void AddDirectiveHandler(MCAsmParserExtension *Object,
118 DirectiveHandler Handler) {
119 DirectiveMap[Directive] = std::make_pair(Object, Handler);
123 /// @name MCAsmParser Interface
126 virtual SourceMgr &getSourceManager() { return SrcMgr; }
127 virtual MCAsmLexer &getLexer() { return Lexer; }
128 virtual MCContext &getContext() { return Ctx; }
129 virtual MCStreamer &getStreamer() { return Out; }
131 virtual void Warning(SMLoc L, const Twine &Meg);
132 virtual bool Error(SMLoc L, const Twine &Msg);
134 const AsmToken &Lex();
136 bool ParseExpression(const MCExpr *&Res);
137 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
138 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
139 virtual bool ParseAbsoluteExpression(int64_t &Res);
144 void CheckForValidSection();
146 bool ParseStatement();
148 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
149 void HandleMacroExit();
151 void PrintMacroInstantiations();
152 void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type) const {
153 SrcMgr.PrintMessage(Loc, Msg, Type);
156 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
157 bool EnterIncludeFile(const std::string &Filename);
159 /// \brief Reset the current lexer position to that given by \arg Loc. The
160 /// current token is not set; clients should ensure Lex() is called
162 void JumpToLoc(SMLoc Loc);
164 void EatToEndOfStatement();
166 /// \brief Parse up to the end of statement and a return the contents from the
167 /// current token until the end of the statement; the current token on exit
168 /// will be either the EndOfStatement or EOF.
169 StringRef ParseStringToEndOfStatement();
171 bool ParseAssignment(StringRef Name, bool allow_redef);
173 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
174 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
175 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
176 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
178 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
179 /// and set \arg Res to the identifier contents.
180 bool ParseIdentifier(StringRef &Res);
182 // Directive Parsing.
184 // ".ascii", ".asciiz", ".string"
185 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
186 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
187 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
188 bool ParseDirectiveFill(); // ".fill"
189 bool ParseDirectiveSpace(); // ".space"
190 bool ParseDirectiveZero(); // ".zero"
191 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
192 bool ParseDirectiveOrg(); // ".org"
193 // ".align{,32}", ".p2align{,w,l}"
194 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
196 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
197 /// accepts a single symbol (which should be a label or an external).
198 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
200 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
202 bool ParseDirectiveAbort(); // ".abort"
203 bool ParseDirectiveInclude(); // ".include"
205 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
206 // ".ifdef" or ".ifndef", depending on expect_defined
207 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
208 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
209 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
210 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
212 /// ParseEscapedString - Parse the current token as a string which may include
213 /// escaped characters and return the string contents.
214 bool ParseEscapedString(std::string &Data);
216 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
217 MCSymbolRefExpr::VariantKind Variant);
220 /// \brief Generic implementations of directive handling, etc. which is shared
221 /// (or the default, at least) for all assembler parser.
222 class GenericAsmParser : public MCAsmParserExtension {
223 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
224 void AddDirectiveHandler(StringRef Directive) {
225 getParser().AddDirectiveHandler(this, Directive,
226 HandleDirective<GenericAsmParser, Handler>);
229 GenericAsmParser() {}
231 AsmParser &getParser() {
232 return (AsmParser&) this->MCAsmParserExtension::getParser();
235 virtual void Initialize(MCAsmParser &Parser) {
236 // Call the base implementation.
237 this->MCAsmParserExtension::Initialize(Parser);
239 // Debugging directives.
240 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
241 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
242 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
243 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
246 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
248 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
250 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
252 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
253 ".cfi_def_cfa_offset");
254 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
255 ".cfi_def_cfa_register");
256 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
259 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
261 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
263 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
265 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
268 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
270 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
272 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
273 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
274 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
276 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
277 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
280 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
282 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
283 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
284 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
285 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
286 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
287 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
288 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
289 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
290 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
291 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
292 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
293 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
294 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
296 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
297 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
298 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
300 bool ParseDirectiveLEB128(StringRef, SMLoc);
307 extern MCAsmParserExtension *createDarwinAsmParser();
308 extern MCAsmParserExtension *createELFAsmParser();
309 extern MCAsmParserExtension *createCOFFAsmParser();
313 enum { DEFAULT_ADDRSPACE = 0 };
315 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
316 MCStreamer &_Out, const MCAsmInfo &_MAI)
317 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
318 GenericParser(new GenericAsmParser), PlatformParser(0),
319 CurBuffer(0), MacrosEnabled(true) {
320 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
322 // Initialize the generic parser.
323 GenericParser->Initialize(*this);
325 // Initialize the platform / file format parser.
327 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
329 if (_MAI.hasMicrosoftFastStdCallMangling()) {
330 PlatformParser = createCOFFAsmParser();
331 PlatformParser->Initialize(*this);
332 } else if (_MAI.hasSubsectionsViaSymbols()) {
333 PlatformParser = createDarwinAsmParser();
334 PlatformParser->Initialize(*this);
336 PlatformParser = createELFAsmParser();
337 PlatformParser->Initialize(*this);
341 AsmParser::~AsmParser() {
342 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
344 // Destroy any macros.
345 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
346 ie = MacroMap.end(); it != ie; ++it)
347 delete it->getValue();
349 delete PlatformParser;
350 delete GenericParser;
353 void AsmParser::PrintMacroInstantiations() {
354 // Print the active macro instantiation stack.
355 for (std::vector<MacroInstantiation*>::const_reverse_iterator
356 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
357 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
361 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
362 PrintMessage(L, Msg, "warning");
363 PrintMacroInstantiations();
366 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
368 PrintMessage(L, Msg, "error");
369 PrintMacroInstantiations();
373 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
374 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
380 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
385 void AsmParser::JumpToLoc(SMLoc Loc) {
386 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
387 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
390 const AsmToken &AsmParser::Lex() {
391 const AsmToken *tok = &Lexer.Lex();
393 if (tok->is(AsmToken::Eof)) {
394 // If this is the end of an included file, pop the parent file off the
396 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
397 if (ParentIncludeLoc != SMLoc()) {
398 JumpToLoc(ParentIncludeLoc);
403 if (tok->is(AsmToken::Error))
404 Error(Lexer.getErrLoc(), Lexer.getErr());
409 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
410 // Create the initial section, if requested.
411 if (!NoInitialTextSection)
418 AsmCond StartingCondState = TheCondState;
420 // While we have input, parse each statement.
421 while (Lexer.isNot(AsmToken::Eof)) {
422 if (!ParseStatement()) continue;
424 // We had an error, validate that one was emitted and recover by skipping to
426 assert(HadError && "Parse statement returned an error, but none emitted!");
427 EatToEndOfStatement();
430 if (TheCondState.TheCond != StartingCondState.TheCond ||
431 TheCondState.Ignore != StartingCondState.Ignore)
432 return TokError("unmatched .ifs or .elses");
434 // Check to see there are no empty DwarfFile slots.
435 const std::vector<MCDwarfFile *> &MCDwarfFiles =
436 getContext().getMCDwarfFiles();
437 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
438 if (!MCDwarfFiles[i])
439 TokError("unassigned file number: " + Twine(i) + " for .file directives");
442 // Finalize the output stream if there are no errors and if the client wants
444 if (!HadError && !NoFinalize)
450 void AsmParser::CheckForValidSection() {
451 if (!getStreamer().getCurrentSection()) {
452 TokError("expected section directive before assembly directive");
453 Out.SwitchSection(Ctx.getMachOSection(
455 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
456 0, SectionKind::getText()));
460 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
461 void AsmParser::EatToEndOfStatement() {
462 while (Lexer.isNot(AsmToken::EndOfStatement) &&
463 Lexer.isNot(AsmToken::Eof))
467 if (Lexer.is(AsmToken::EndOfStatement))
471 StringRef AsmParser::ParseStringToEndOfStatement() {
472 const char *Start = getTok().getLoc().getPointer();
474 while (Lexer.isNot(AsmToken::EndOfStatement) &&
475 Lexer.isNot(AsmToken::Eof))
478 const char *End = getTok().getLoc().getPointer();
479 return StringRef(Start, End - Start);
482 /// ParseParenExpr - Parse a paren expression and return it.
483 /// NOTE: This assumes the leading '(' has already been consumed.
485 /// parenexpr ::= expr)
487 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
488 if (ParseExpression(Res)) return true;
489 if (Lexer.isNot(AsmToken::RParen))
490 return TokError("expected ')' in parentheses expression");
491 EndLoc = Lexer.getLoc();
496 /// ParseBracketExpr - Parse a bracket expression and return it.
497 /// NOTE: This assumes the leading '[' has already been consumed.
499 /// bracketexpr ::= expr]
501 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
502 if (ParseExpression(Res)) return true;
503 if (Lexer.isNot(AsmToken::RBrac))
504 return TokError("expected ']' in brackets expression");
505 EndLoc = Lexer.getLoc();
510 /// ParsePrimaryExpr - Parse a primary expression and return it.
511 /// primaryexpr ::= (parenexpr
512 /// primaryexpr ::= symbol
513 /// primaryexpr ::= number
514 /// primaryexpr ::= '.'
515 /// primaryexpr ::= ~,+,- primaryexpr
516 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
517 switch (Lexer.getKind()) {
519 return TokError("unknown token in expression");
520 case AsmToken::Exclaim:
521 Lex(); // Eat the operator.
522 if (ParsePrimaryExpr(Res, EndLoc))
524 Res = MCUnaryExpr::CreateLNot(Res, getContext());
526 case AsmToken::Dollar:
527 case AsmToken::String:
528 case AsmToken::Identifier: {
529 EndLoc = Lexer.getLoc();
531 StringRef Identifier;
532 if (ParseIdentifier(Identifier))
535 // This is a symbol reference.
536 std::pair<StringRef, StringRef> Split = Identifier.split('@');
537 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
539 // Lookup the symbol variant if used.
540 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
541 if (Split.first.size() != Identifier.size()) {
542 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
543 if (Variant == MCSymbolRefExpr::VK_Invalid) {
544 Variant = MCSymbolRefExpr::VK_None;
545 return TokError("invalid variant '" + Split.second + "'");
549 // If this is an absolute variable reference, substitute it now to preserve
550 // semantics in the face of reassignment.
551 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
553 return Error(EndLoc, "unexpected modifier on variable reference");
555 Res = Sym->getVariableValue();
559 // Otherwise create a symbol ref.
560 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
563 case AsmToken::Integer: {
564 SMLoc Loc = getTok().getLoc();
565 int64_t IntVal = getTok().getIntVal();
566 Res = MCConstantExpr::Create(IntVal, getContext());
567 EndLoc = Lexer.getLoc();
569 // Look for 'b' or 'f' following an Integer as a directional label
570 if (Lexer.getKind() == AsmToken::Identifier) {
571 StringRef IDVal = getTok().getString();
572 if (IDVal == "f" || IDVal == "b"){
573 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
574 IDVal == "f" ? 1 : 0);
575 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
577 if(IDVal == "b" && Sym->isUndefined())
578 return Error(Loc, "invalid reference to undefined symbol");
579 EndLoc = Lexer.getLoc();
580 Lex(); // Eat identifier.
585 case AsmToken::Real: {
586 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
587 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
588 Res = MCConstantExpr::Create(IntVal, getContext());
592 case AsmToken::Dot: {
593 // This is a '.' reference, which references the current PC. Emit a
594 // temporary label to the streamer and refer to it.
595 MCSymbol *Sym = Ctx.CreateTempSymbol();
597 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
598 EndLoc = Lexer.getLoc();
599 Lex(); // Eat identifier.
602 case AsmToken::LParen:
603 Lex(); // Eat the '('.
604 return ParseParenExpr(Res, EndLoc);
605 case AsmToken::LBrac:
606 Lex(); // Eat the '['.
607 return ParseBracketExpr(Res, EndLoc);
608 case AsmToken::Minus:
609 Lex(); // Eat the operator.
610 if (ParsePrimaryExpr(Res, EndLoc))
612 Res = MCUnaryExpr::CreateMinus(Res, getContext());
615 Lex(); // Eat the operator.
616 if (ParsePrimaryExpr(Res, EndLoc))
618 Res = MCUnaryExpr::CreatePlus(Res, getContext());
620 case AsmToken::Tilde:
621 Lex(); // Eat the operator.
622 if (ParsePrimaryExpr(Res, EndLoc))
624 Res = MCUnaryExpr::CreateNot(Res, getContext());
629 bool AsmParser::ParseExpression(const MCExpr *&Res) {
631 return ParseExpression(Res, EndLoc);
635 AsmParser::ApplyModifierToExpr(const MCExpr *E,
636 MCSymbolRefExpr::VariantKind Variant) {
637 // Recurse over the given expression, rebuilding it to apply the given variant
638 // if there is exactly one symbol.
639 switch (E->getKind()) {
641 case MCExpr::Constant:
644 case MCExpr::SymbolRef: {
645 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
647 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
648 TokError("invalid variant on expression '" +
649 getTok().getIdentifier() + "' (already modified)");
653 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
656 case MCExpr::Unary: {
657 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
658 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
661 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
664 case MCExpr::Binary: {
665 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
666 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
667 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
672 if (!LHS) LHS = BE->getLHS();
673 if (!RHS) RHS = BE->getRHS();
675 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
679 assert(0 && "Invalid expression kind!");
683 /// ParseExpression - Parse an expression and return it.
685 /// expr ::= expr +,- expr -> lowest.
686 /// expr ::= expr |,^,&,! expr -> middle.
687 /// expr ::= expr *,/,%,<<,>> expr -> highest.
688 /// expr ::= primaryexpr
690 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
691 // Parse the expression.
693 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
696 // As a special case, we support 'a op b @ modifier' by rewriting the
697 // expression to include the modifier. This is inefficient, but in general we
698 // expect users to use 'a@modifier op b'.
699 if (Lexer.getKind() == AsmToken::At) {
702 if (Lexer.isNot(AsmToken::Identifier))
703 return TokError("unexpected symbol modifier following '@'");
705 MCSymbolRefExpr::VariantKind Variant =
706 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
707 if (Variant == MCSymbolRefExpr::VK_Invalid)
708 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
710 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
712 return TokError("invalid modifier '" + getTok().getIdentifier() +
713 "' (no symbols present)");
721 // Try to constant fold it up front, if possible.
723 if (Res->EvaluateAsAbsolute(Value))
724 Res = MCConstantExpr::Create(Value, getContext());
729 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
731 return ParseParenExpr(Res, EndLoc) ||
732 ParseBinOpRHS(1, Res, EndLoc);
735 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
738 SMLoc StartLoc = Lexer.getLoc();
739 if (ParseExpression(Expr))
742 if (!Expr->EvaluateAsAbsolute(Res))
743 return Error(StartLoc, "expected absolute expression");
748 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
749 MCBinaryExpr::Opcode &Kind) {
752 return 0; // not a binop.
754 // Lowest Precedence: &&, ||, @
755 case AsmToken::AmpAmp:
756 Kind = MCBinaryExpr::LAnd;
758 case AsmToken::PipePipe:
759 Kind = MCBinaryExpr::LOr;
763 // Low Precedence: |, &, ^
765 // FIXME: gas seems to support '!' as an infix operator?
767 Kind = MCBinaryExpr::Or;
769 case AsmToken::Caret:
770 Kind = MCBinaryExpr::Xor;
773 Kind = MCBinaryExpr::And;
776 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
777 case AsmToken::EqualEqual:
778 Kind = MCBinaryExpr::EQ;
780 case AsmToken::ExclaimEqual:
781 case AsmToken::LessGreater:
782 Kind = MCBinaryExpr::NE;
785 Kind = MCBinaryExpr::LT;
787 case AsmToken::LessEqual:
788 Kind = MCBinaryExpr::LTE;
790 case AsmToken::Greater:
791 Kind = MCBinaryExpr::GT;
793 case AsmToken::GreaterEqual:
794 Kind = MCBinaryExpr::GTE;
797 // High Intermediate Precedence: +, -
799 Kind = MCBinaryExpr::Add;
801 case AsmToken::Minus:
802 Kind = MCBinaryExpr::Sub;
805 // Highest Precedence: *, /, %, <<, >>
807 Kind = MCBinaryExpr::Mul;
809 case AsmToken::Slash:
810 Kind = MCBinaryExpr::Div;
812 case AsmToken::Percent:
813 Kind = MCBinaryExpr::Mod;
815 case AsmToken::LessLess:
816 Kind = MCBinaryExpr::Shl;
818 case AsmToken::GreaterGreater:
819 Kind = MCBinaryExpr::Shr;
825 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
826 /// Res contains the LHS of the expression on input.
827 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
830 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
831 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
833 // If the next token is lower precedence than we are allowed to eat, return
834 // successfully with what we ate already.
835 if (TokPrec < Precedence)
840 // Eat the next primary expression.
842 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
844 // If BinOp binds less tightly with RHS than the operator after RHS, let
845 // the pending operator take RHS as its LHS.
846 MCBinaryExpr::Opcode Dummy;
847 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
848 if (TokPrec < NextTokPrec) {
849 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
852 // Merge LHS and RHS according to operator.
853 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
861 /// ::= EndOfStatement
862 /// ::= Label* Directive ...Operands... EndOfStatement
863 /// ::= Label* Identifier OperandList* EndOfStatement
864 bool AsmParser::ParseStatement() {
865 if (Lexer.is(AsmToken::EndOfStatement)) {
871 // Statements always start with an identifier or are a full line comment.
872 AsmToken ID = getTok();
873 SMLoc IDLoc = ID.getLoc();
875 int64_t LocalLabelVal = -1;
876 // A full line comment is a '#' as the first token.
877 if (Lexer.is(AsmToken::Hash)) {
878 EatToEndOfStatement();
881 // Allow an integer followed by a ':' as a directional local label.
882 if (Lexer.is(AsmToken::Integer)) {
883 LocalLabelVal = getTok().getIntVal();
884 if (LocalLabelVal < 0) {
885 if (!TheCondState.Ignore)
886 return TokError("unexpected token at start of statement");
890 IDVal = getTok().getString();
891 Lex(); // Consume the integer token to be used as an identifier token.
892 if (Lexer.getKind() != AsmToken::Colon) {
893 if (!TheCondState.Ignore)
894 return TokError("unexpected token at start of statement");
898 else if (ParseIdentifier(IDVal)) {
899 if (!TheCondState.Ignore)
900 return TokError("unexpected token at start of statement");
904 // Handle conditional assembly here before checking for skipping. We
905 // have to do this so that .endif isn't skipped in a ".if 0" block for
908 return ParseDirectiveIf(IDLoc);
909 if (IDVal == ".ifdef")
910 return ParseDirectiveIfdef(IDLoc, true);
911 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
912 return ParseDirectiveIfdef(IDLoc, false);
913 if (IDVal == ".elseif")
914 return ParseDirectiveElseIf(IDLoc);
915 if (IDVal == ".else")
916 return ParseDirectiveElse(IDLoc);
917 if (IDVal == ".endif")
918 return ParseDirectiveEndIf(IDLoc);
920 // If we are in a ".if 0" block, ignore this statement.
921 if (TheCondState.Ignore) {
922 EatToEndOfStatement();
926 // FIXME: Recurse on local labels?
928 // See what kind of statement we have.
929 switch (Lexer.getKind()) {
930 case AsmToken::Colon: {
931 CheckForValidSection();
933 // identifier ':' -> Label.
936 // Diagnose attempt to use a variable as a label.
938 // FIXME: Diagnostics. Note the location of the definition as a label.
939 // FIXME: This doesn't diagnose assignment to a symbol which has been
940 // implicitly marked as external.
942 if (LocalLabelVal == -1)
943 Sym = getContext().GetOrCreateSymbol(IDVal);
945 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
946 if (!Sym->isUndefined() || Sym->isVariable())
947 return Error(IDLoc, "invalid symbol redefinition");
952 // Consume any end of statement token, if present, to avoid spurious
953 // AddBlankLine calls().
954 if (Lexer.is(AsmToken::EndOfStatement)) {
956 if (Lexer.is(AsmToken::Eof))
960 return ParseStatement();
963 case AsmToken::Equal:
964 // identifier '=' ... -> assignment statement
967 return ParseAssignment(IDVal, true);
969 default: // Normal instruction or directive.
973 // If macros are enabled, check to see if this is a macro instantiation.
975 if (const Macro *M = MacroMap.lookup(IDVal))
976 return HandleMacroEntry(IDVal, IDLoc, M);
978 // Otherwise, we have a normal instruction or directive.
979 if (IDVal[0] == '.') {
980 // Assembler features
981 if (IDVal == ".set" || IDVal == ".equ")
982 return ParseDirectiveSet(IDVal, true);
983 if (IDVal == ".equiv")
984 return ParseDirectiveSet(IDVal, false);
988 if (IDVal == ".ascii")
989 return ParseDirectiveAscii(IDVal, false);
990 if (IDVal == ".asciz" || IDVal == ".string")
991 return ParseDirectiveAscii(IDVal, true);
993 if (IDVal == ".byte")
994 return ParseDirectiveValue(1);
995 if (IDVal == ".short")
996 return ParseDirectiveValue(2);
997 if (IDVal == ".value")
998 return ParseDirectiveValue(2);
999 if (IDVal == ".2byte")
1000 return ParseDirectiveValue(2);
1001 if (IDVal == ".long")
1002 return ParseDirectiveValue(4);
1003 if (IDVal == ".int")
1004 return ParseDirectiveValue(4);
1005 if (IDVal == ".4byte")
1006 return ParseDirectiveValue(4);
1007 if (IDVal == ".quad")
1008 return ParseDirectiveValue(8);
1009 if (IDVal == ".8byte")
1010 return ParseDirectiveValue(8);
1011 if (IDVal == ".single" || IDVal == ".float")
1012 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1013 if (IDVal == ".double")
1014 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1016 if (IDVal == ".align") {
1017 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1018 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1020 if (IDVal == ".align32") {
1021 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1022 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1024 if (IDVal == ".balign")
1025 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1026 if (IDVal == ".balignw")
1027 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1028 if (IDVal == ".balignl")
1029 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1030 if (IDVal == ".p2align")
1031 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1032 if (IDVal == ".p2alignw")
1033 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1034 if (IDVal == ".p2alignl")
1035 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1037 if (IDVal == ".org")
1038 return ParseDirectiveOrg();
1040 if (IDVal == ".fill")
1041 return ParseDirectiveFill();
1042 if (IDVal == ".space")
1043 return ParseDirectiveSpace();
1044 if (IDVal == ".zero")
1045 return ParseDirectiveZero();
1047 // Symbol attribute directives
1049 if (IDVal == ".globl" || IDVal == ".global")
1050 return ParseDirectiveSymbolAttribute(MCSA_Global);
1051 // ELF only? Should it be here?
1052 if (IDVal == ".local")
1053 return ParseDirectiveSymbolAttribute(MCSA_Local);
1054 if (IDVal == ".hidden")
1055 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1056 if (IDVal == ".indirect_symbol")
1057 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1058 if (IDVal == ".internal")
1059 return ParseDirectiveSymbolAttribute(MCSA_Internal);
1060 if (IDVal == ".lazy_reference")
1061 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1062 if (IDVal == ".no_dead_strip")
1063 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1064 if (IDVal == ".symbol_resolver")
1065 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1066 if (IDVal == ".private_extern")
1067 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1068 if (IDVal == ".protected")
1069 return ParseDirectiveSymbolAttribute(MCSA_Protected);
1070 if (IDVal == ".reference")
1071 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1072 if (IDVal == ".weak")
1073 return ParseDirectiveSymbolAttribute(MCSA_Weak);
1074 if (IDVal == ".weak_definition")
1075 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1076 if (IDVal == ".weak_reference")
1077 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1078 if (IDVal == ".weak_def_can_be_hidden")
1079 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1081 if (IDVal == ".comm")
1082 return ParseDirectiveComm(/*IsLocal=*/false);
1083 if (IDVal == ".lcomm")
1084 return ParseDirectiveComm(/*IsLocal=*/true);
1086 if (IDVal == ".abort")
1087 return ParseDirectiveAbort();
1088 if (IDVal == ".include")
1089 return ParseDirectiveInclude();
1091 if (IDVal == ".code16" || IDVal == ".code32" || IDVal == ".code64")
1092 return TokError(Twine(IDVal) + " not supported yet");
1094 // Look up the handler in the handler table.
1095 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1096 DirectiveMap.lookup(IDVal);
1098 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1100 // Target hook for parsing target specific directives.
1101 if (!getTargetParser().ParseDirective(ID))
1104 Warning(IDLoc, "ignoring directive for now");
1105 EatToEndOfStatement();
1109 CheckForValidSection();
1111 // Canonicalize the opcode to lower case.
1112 SmallString<128> Opcode;
1113 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1114 Opcode.push_back(tolower(IDVal[i]));
1116 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1117 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1120 // Dump the parsed representation, if requested.
1121 if (getShowParsedOperands()) {
1122 SmallString<256> Str;
1123 raw_svector_ostream OS(Str);
1124 OS << "parsed instruction: [";
1125 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1128 ParsedOperands[i]->dump(OS);
1132 PrintMessage(IDLoc, OS.str(), "note");
1135 // If parsing succeeded, match the instruction.
1137 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1140 // Free any parsed operands.
1141 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1142 delete ParsedOperands[i];
1144 // Don't skip the rest of the line, the instruction parser is responsible for
1149 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1150 const std::vector<std::vector<AsmToken> > &A)
1151 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1153 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1154 // to hold the macro body with substitutions.
1155 SmallString<256> Buf;
1156 raw_svector_ostream OS(Buf);
1158 StringRef Body = M->Body;
1159 while (!Body.empty()) {
1160 // Scan for the next substitution.
1161 std::size_t End = Body.size(), Pos = 0;
1162 for (; Pos != End; ++Pos) {
1163 // Check for a substitution or escape.
1164 if (Body[Pos] != '$' || Pos + 1 == End)
1167 char Next = Body[Pos + 1];
1168 if (Next == '$' || Next == 'n' || isdigit(Next))
1173 OS << Body.slice(0, Pos);
1175 // Check if we reached the end.
1179 switch (Body[Pos+1]) {
1185 // $n => number of arguments
1190 // $[0-9] => argument
1192 // Missing arguments are ignored.
1193 unsigned Index = Body[Pos+1] - '0';
1194 if (Index >= A.size())
1197 // Otherwise substitute with the token values, with spaces eliminated.
1198 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1199 ie = A[Index].end(); it != ie; ++it)
1200 OS << it->getString();
1205 // Update the scan point.
1206 Body = Body.substr(Pos + 2);
1209 // We include the .endmacro in the buffer as our queue to exit the macro
1211 OS << ".endmacro\n";
1213 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1216 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1218 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1219 // this, although we should protect against infinite loops.
1220 if (ActiveMacros.size() == 20)
1221 return TokError("macros cannot be nested more than 20 levels deep");
1223 // Parse the macro instantiation arguments.
1224 std::vector<std::vector<AsmToken> > MacroArguments;
1225 MacroArguments.push_back(std::vector<AsmToken>());
1226 unsigned ParenLevel = 0;
1228 if (Lexer.is(AsmToken::Eof))
1229 return TokError("unexpected token in macro instantiation");
1230 if (Lexer.is(AsmToken::EndOfStatement))
1233 // If we aren't inside parentheses and this is a comma, start a new token
1235 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1236 MacroArguments.push_back(std::vector<AsmToken>());
1238 // Adjust the current parentheses level.
1239 if (Lexer.is(AsmToken::LParen))
1241 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1244 // Append the token to the current argument list.
1245 MacroArguments.back().push_back(getTok());
1250 // Create the macro instantiation object and add to the current macro
1251 // instantiation stack.
1252 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1255 ActiveMacros.push_back(MI);
1257 // Jump to the macro instantiation and prime the lexer.
1258 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1259 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1265 void AsmParser::HandleMacroExit() {
1266 // Jump to the EndOfStatement we should return to, and consume it.
1267 JumpToLoc(ActiveMacros.back()->ExitLoc);
1270 // Pop the instantiation entry.
1271 delete ActiveMacros.back();
1272 ActiveMacros.pop_back();
1275 static void MarkUsed(const MCExpr *Value) {
1276 switch (Value->getKind()) {
1277 case MCExpr::Binary:
1278 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1279 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1281 case MCExpr::Target:
1282 case MCExpr::Constant:
1284 case MCExpr::SymbolRef: {
1285 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1289 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1294 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1295 // FIXME: Use better location, we should use proper tokens.
1296 SMLoc EqualLoc = Lexer.getLoc();
1298 const MCExpr *Value;
1299 if (ParseExpression(Value))
1304 if (Lexer.isNot(AsmToken::EndOfStatement))
1305 return TokError("unexpected token in assignment");
1307 // Eat the end of statement marker.
1310 // Validate that the LHS is allowed to be a variable (either it has not been
1311 // used as a symbol, or it is an absolute symbol).
1312 MCSymbol *Sym = getContext().LookupSymbol(Name);
1314 // Diagnose assignment to a label.
1316 // FIXME: Diagnostics. Note the location of the definition as a label.
1317 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1318 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1319 ; // Allow redefinitions of undefined symbols only used in directives.
1320 else if (!Sym->isUndefined() && (!Sym->isAbsolute() || !allow_redef))
1321 return Error(EqualLoc, "redefinition of '" + Name + "'");
1322 else if (!Sym->isVariable())
1323 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1324 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1325 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1328 // Don't count these checks as uses.
1329 Sym->setUsed(false);
1331 Sym = getContext().GetOrCreateSymbol(Name);
1333 // FIXME: Handle '.'.
1335 // Do the assignment.
1336 Out.EmitAssignment(Sym, Value);
1341 /// ParseIdentifier:
1344 bool AsmParser::ParseIdentifier(StringRef &Res) {
1345 // The assembler has relaxed rules for accepting identifiers, in particular we
1346 // allow things like '.globl $foo', which would normally be separate
1347 // tokens. At this level, we have already lexed so we cannot (currently)
1348 // handle this as a context dependent token, instead we detect adjacent tokens
1349 // and return the combined identifier.
1350 if (Lexer.is(AsmToken::Dollar)) {
1351 SMLoc DollarLoc = getLexer().getLoc();
1353 // Consume the dollar sign, and check for a following identifier.
1355 if (Lexer.isNot(AsmToken::Identifier))
1358 // We have a '$' followed by an identifier, make sure they are adjacent.
1359 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1362 // Construct the joined identifier and consume the token.
1363 Res = StringRef(DollarLoc.getPointer(),
1364 getTok().getIdentifier().size() + 1);
1369 if (Lexer.isNot(AsmToken::Identifier) &&
1370 Lexer.isNot(AsmToken::String))
1373 Res = getTok().getIdentifier();
1375 Lex(); // Consume the identifier token.
1380 /// ParseDirectiveSet:
1381 /// ::= .equ identifier ',' expression
1382 /// ::= .equiv identifier ',' expression
1383 /// ::= .set identifier ',' expression
1384 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1387 if (ParseIdentifier(Name))
1388 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1390 if (getLexer().isNot(AsmToken::Comma))
1391 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1394 return ParseAssignment(Name, allow_redef);
1397 bool AsmParser::ParseEscapedString(std::string &Data) {
1398 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1401 StringRef Str = getTok().getStringContents();
1402 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1403 if (Str[i] != '\\') {
1408 // Recognize escaped characters. Note that this escape semantics currently
1409 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1412 return TokError("unexpected backslash at end of string");
1414 // Recognize octal sequences.
1415 if ((unsigned) (Str[i] - '0') <= 7) {
1416 // Consume up to three octal characters.
1417 unsigned Value = Str[i] - '0';
1419 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1421 Value = Value * 8 + (Str[i] - '0');
1423 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1425 Value = Value * 8 + (Str[i] - '0');
1430 return TokError("invalid octal escape sequence (out of range)");
1432 Data += (unsigned char) Value;
1436 // Otherwise recognize individual escapes.
1439 // Just reject invalid escape sequences for now.
1440 return TokError("invalid escape sequence (unrecognized character)");
1442 case 'b': Data += '\b'; break;
1443 case 'f': Data += '\f'; break;
1444 case 'n': Data += '\n'; break;
1445 case 'r': Data += '\r'; break;
1446 case 't': Data += '\t'; break;
1447 case '"': Data += '"'; break;
1448 case '\\': Data += '\\'; break;
1455 /// ParseDirectiveAscii:
1456 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1457 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1458 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1459 CheckForValidSection();
1462 if (getLexer().isNot(AsmToken::String))
1463 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1466 if (ParseEscapedString(Data))
1469 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1471 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1475 if (getLexer().is(AsmToken::EndOfStatement))
1478 if (getLexer().isNot(AsmToken::Comma))
1479 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1488 /// ParseDirectiveValue
1489 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1490 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1491 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1492 CheckForValidSection();
1495 const MCExpr *Value;
1496 if (ParseExpression(Value))
1499 // Special case constant expressions to match code generator.
1500 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1501 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1503 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1505 if (getLexer().is(AsmToken::EndOfStatement))
1508 // FIXME: Improve diagnostic.
1509 if (getLexer().isNot(AsmToken::Comma))
1510 return TokError("unexpected token in directive");
1519 /// ParseDirectiveRealValue
1520 /// ::= (.single | .double) [ expression (, expression)* ]
1521 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1522 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1523 CheckForValidSection();
1526 // We don't truly support arithmetic on floating point expressions, so we
1527 // have to manually parse unary prefixes.
1529 if (getLexer().is(AsmToken::Minus)) {
1532 } else if (getLexer().is(AsmToken::Plus))
1535 if (getLexer().isNot(AsmToken::Integer) &&
1536 getLexer().isNot(AsmToken::Real))
1537 return TokError("unexpected token in directive");
1539 // Convert to an APFloat.
1540 APFloat Value(Semantics);
1541 if (Value.convertFromString(getTok().getString(),
1542 APFloat::rmNearestTiesToEven) ==
1543 APFloat::opInvalidOp)
1544 return TokError("invalid floating point literal");
1548 // Consume the numeric token.
1551 // Emit the value as an integer.
1552 APInt AsInt = Value.bitcastToAPInt();
1553 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1554 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1556 if (getLexer().is(AsmToken::EndOfStatement))
1559 if (getLexer().isNot(AsmToken::Comma))
1560 return TokError("unexpected token in directive");
1569 /// ParseDirectiveSpace
1570 /// ::= .space expression [ , expression ]
1571 bool AsmParser::ParseDirectiveSpace() {
1572 CheckForValidSection();
1575 if (ParseAbsoluteExpression(NumBytes))
1578 int64_t FillExpr = 0;
1579 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1580 if (getLexer().isNot(AsmToken::Comma))
1581 return TokError("unexpected token in '.space' directive");
1584 if (ParseAbsoluteExpression(FillExpr))
1587 if (getLexer().isNot(AsmToken::EndOfStatement))
1588 return TokError("unexpected token in '.space' directive");
1594 return TokError("invalid number of bytes in '.space' directive");
1596 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1597 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1602 /// ParseDirectiveZero
1603 /// ::= .zero expression
1604 bool AsmParser::ParseDirectiveZero() {
1605 CheckForValidSection();
1608 if (ParseAbsoluteExpression(NumBytes))
1612 if (getLexer().is(AsmToken::Comma)) {
1614 if (ParseAbsoluteExpression(Val))
1618 if (getLexer().isNot(AsmToken::EndOfStatement))
1619 return TokError("unexpected token in '.zero' directive");
1623 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1628 /// ParseDirectiveFill
1629 /// ::= .fill expression , expression , expression
1630 bool AsmParser::ParseDirectiveFill() {
1631 CheckForValidSection();
1634 if (ParseAbsoluteExpression(NumValues))
1637 if (getLexer().isNot(AsmToken::Comma))
1638 return TokError("unexpected token in '.fill' directive");
1642 if (ParseAbsoluteExpression(FillSize))
1645 if (getLexer().isNot(AsmToken::Comma))
1646 return TokError("unexpected token in '.fill' directive");
1650 if (ParseAbsoluteExpression(FillExpr))
1653 if (getLexer().isNot(AsmToken::EndOfStatement))
1654 return TokError("unexpected token in '.fill' directive");
1658 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1659 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1661 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1662 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1667 /// ParseDirectiveOrg
1668 /// ::= .org expression [ , expression ]
1669 bool AsmParser::ParseDirectiveOrg() {
1670 CheckForValidSection();
1672 const MCExpr *Offset;
1673 if (ParseExpression(Offset))
1676 // Parse optional fill expression.
1677 int64_t FillExpr = 0;
1678 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1679 if (getLexer().isNot(AsmToken::Comma))
1680 return TokError("unexpected token in '.org' directive");
1683 if (ParseAbsoluteExpression(FillExpr))
1686 if (getLexer().isNot(AsmToken::EndOfStatement))
1687 return TokError("unexpected token in '.org' directive");
1692 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1693 // has to be relative to the current section.
1694 getStreamer().EmitValueToOffset(Offset, FillExpr);
1699 /// ParseDirectiveAlign
1700 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1701 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1702 CheckForValidSection();
1704 SMLoc AlignmentLoc = getLexer().getLoc();
1706 if (ParseAbsoluteExpression(Alignment))
1710 bool HasFillExpr = false;
1711 int64_t FillExpr = 0;
1712 int64_t MaxBytesToFill = 0;
1713 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1714 if (getLexer().isNot(AsmToken::Comma))
1715 return TokError("unexpected token in directive");
1718 // The fill expression can be omitted while specifying a maximum number of
1719 // alignment bytes, e.g:
1721 if (getLexer().isNot(AsmToken::Comma)) {
1723 if (ParseAbsoluteExpression(FillExpr))
1727 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1728 if (getLexer().isNot(AsmToken::Comma))
1729 return TokError("unexpected token in directive");
1732 MaxBytesLoc = getLexer().getLoc();
1733 if (ParseAbsoluteExpression(MaxBytesToFill))
1736 if (getLexer().isNot(AsmToken::EndOfStatement))
1737 return TokError("unexpected token in directive");
1746 // Compute alignment in bytes.
1748 // FIXME: Diagnose overflow.
1749 if (Alignment >= 32) {
1750 Error(AlignmentLoc, "invalid alignment value");
1754 Alignment = 1ULL << Alignment;
1757 // Diagnose non-sensical max bytes to align.
1758 if (MaxBytesLoc.isValid()) {
1759 if (MaxBytesToFill < 1) {
1760 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1761 "many bytes, ignoring maximum bytes expression");
1765 if (MaxBytesToFill >= Alignment) {
1766 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1772 // Check whether we should use optimal code alignment for this .align
1774 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1775 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1776 ValueSize == 1 && UseCodeAlign) {
1777 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1779 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1780 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1787 /// ParseDirectiveSymbolAttribute
1788 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1789 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1790 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1794 if (ParseIdentifier(Name))
1795 return TokError("expected identifier in directive");
1797 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1799 getStreamer().EmitSymbolAttribute(Sym, Attr);
1801 if (getLexer().is(AsmToken::EndOfStatement))
1804 if (getLexer().isNot(AsmToken::Comma))
1805 return TokError("unexpected token in directive");
1814 /// ParseDirectiveComm
1815 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1816 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1817 CheckForValidSection();
1819 SMLoc IDLoc = getLexer().getLoc();
1821 if (ParseIdentifier(Name))
1822 return TokError("expected identifier in directive");
1824 // Handle the identifier as the key symbol.
1825 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1827 if (getLexer().isNot(AsmToken::Comma))
1828 return TokError("unexpected token in directive");
1832 SMLoc SizeLoc = getLexer().getLoc();
1833 if (ParseAbsoluteExpression(Size))
1836 int64_t Pow2Alignment = 0;
1837 SMLoc Pow2AlignmentLoc;
1838 if (getLexer().is(AsmToken::Comma)) {
1840 Pow2AlignmentLoc = getLexer().getLoc();
1841 if (ParseAbsoluteExpression(Pow2Alignment))
1844 // If this target takes alignments in bytes (not log) validate and convert.
1845 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1846 if (!isPowerOf2_64(Pow2Alignment))
1847 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1848 Pow2Alignment = Log2_64(Pow2Alignment);
1852 if (getLexer().isNot(AsmToken::EndOfStatement))
1853 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1857 // NOTE: a size of zero for a .comm should create a undefined symbol
1858 // but a size of .lcomm creates a bss symbol of size zero.
1860 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1861 "be less than zero");
1863 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1864 // may internally end up wanting an alignment in bytes.
1865 // FIXME: Diagnose overflow.
1866 if (Pow2Alignment < 0)
1867 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1868 "alignment, can't be less than zero");
1870 if (!Sym->isUndefined())
1871 return Error(IDLoc, "invalid symbol redefinition");
1873 // '.lcomm' is equivalent to '.zerofill'.
1874 // Create the Symbol as a common or local common with Size and Pow2Alignment
1876 getStreamer().EmitZerofill(Ctx.getMachOSection(
1877 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1878 0, SectionKind::getBSS()),
1879 Sym, Size, 1 << Pow2Alignment);
1883 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1887 /// ParseDirectiveAbort
1888 /// ::= .abort [... message ...]
1889 bool AsmParser::ParseDirectiveAbort() {
1890 // FIXME: Use loc from directive.
1891 SMLoc Loc = getLexer().getLoc();
1893 StringRef Str = ParseStringToEndOfStatement();
1894 if (getLexer().isNot(AsmToken::EndOfStatement))
1895 return TokError("unexpected token in '.abort' directive");
1900 Error(Loc, ".abort detected. Assembly stopping.");
1902 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1903 // FIXME: Actually abort assembly here.
1908 /// ParseDirectiveInclude
1909 /// ::= .include "filename"
1910 bool AsmParser::ParseDirectiveInclude() {
1911 if (getLexer().isNot(AsmToken::String))
1912 return TokError("expected string in '.include' directive");
1914 std::string Filename = getTok().getString();
1915 SMLoc IncludeLoc = getLexer().getLoc();
1918 if (getLexer().isNot(AsmToken::EndOfStatement))
1919 return TokError("unexpected token in '.include' directive");
1921 // Strip the quotes.
1922 Filename = Filename.substr(1, Filename.size()-2);
1924 // Attempt to switch the lexer to the included file before consuming the end
1925 // of statement to avoid losing it when we switch.
1926 if (EnterIncludeFile(Filename)) {
1927 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1934 /// ParseDirectiveIf
1935 /// ::= .if expression
1936 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1937 TheCondStack.push_back(TheCondState);
1938 TheCondState.TheCond = AsmCond::IfCond;
1939 if(TheCondState.Ignore) {
1940 EatToEndOfStatement();
1944 if (ParseAbsoluteExpression(ExprValue))
1947 if (getLexer().isNot(AsmToken::EndOfStatement))
1948 return TokError("unexpected token in '.if' directive");
1952 TheCondState.CondMet = ExprValue;
1953 TheCondState.Ignore = !TheCondState.CondMet;
1959 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
1961 TheCondStack.push_back(TheCondState);
1962 TheCondState.TheCond = AsmCond::IfCond;
1964 if (TheCondState.Ignore) {
1965 EatToEndOfStatement();
1967 if (ParseIdentifier(Name))
1968 return TokError("expected identifier after '.ifdef'");
1972 MCSymbol *Sym = getContext().LookupSymbol(Name);
1975 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
1977 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
1978 TheCondState.Ignore = !TheCondState.CondMet;
1984 /// ParseDirectiveElseIf
1985 /// ::= .elseif expression
1986 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1987 if (TheCondState.TheCond != AsmCond::IfCond &&
1988 TheCondState.TheCond != AsmCond::ElseIfCond)
1989 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1991 TheCondState.TheCond = AsmCond::ElseIfCond;
1993 bool LastIgnoreState = false;
1994 if (!TheCondStack.empty())
1995 LastIgnoreState = TheCondStack.back().Ignore;
1996 if (LastIgnoreState || TheCondState.CondMet) {
1997 TheCondState.Ignore = true;
1998 EatToEndOfStatement();
2002 if (ParseAbsoluteExpression(ExprValue))
2005 if (getLexer().isNot(AsmToken::EndOfStatement))
2006 return TokError("unexpected token in '.elseif' directive");
2009 TheCondState.CondMet = ExprValue;
2010 TheCondState.Ignore = !TheCondState.CondMet;
2016 /// ParseDirectiveElse
2018 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2019 if (getLexer().isNot(AsmToken::EndOfStatement))
2020 return TokError("unexpected token in '.else' directive");
2024 if (TheCondState.TheCond != AsmCond::IfCond &&
2025 TheCondState.TheCond != AsmCond::ElseIfCond)
2026 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2028 TheCondState.TheCond = AsmCond::ElseCond;
2029 bool LastIgnoreState = false;
2030 if (!TheCondStack.empty())
2031 LastIgnoreState = TheCondStack.back().Ignore;
2032 if (LastIgnoreState || TheCondState.CondMet)
2033 TheCondState.Ignore = true;
2035 TheCondState.Ignore = false;
2040 /// ParseDirectiveEndIf
2042 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2043 if (getLexer().isNot(AsmToken::EndOfStatement))
2044 return TokError("unexpected token in '.endif' directive");
2048 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2049 TheCondStack.empty())
2050 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2052 if (!TheCondStack.empty()) {
2053 TheCondState = TheCondStack.back();
2054 TheCondStack.pop_back();
2060 /// ParseDirectiveFile
2061 /// ::= .file [number] string
2062 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2063 // FIXME: I'm not sure what this is.
2064 int64_t FileNumber = -1;
2065 SMLoc FileNumberLoc = getLexer().getLoc();
2066 if (getLexer().is(AsmToken::Integer)) {
2067 FileNumber = getTok().getIntVal();
2071 return TokError("file number less than one");
2074 if (getLexer().isNot(AsmToken::String))
2075 return TokError("unexpected token in '.file' directive");
2077 StringRef Filename = getTok().getString();
2078 Filename = Filename.substr(1, Filename.size()-2);
2081 if (getLexer().isNot(AsmToken::EndOfStatement))
2082 return TokError("unexpected token in '.file' directive");
2084 if (FileNumber == -1)
2085 getStreamer().EmitFileDirective(Filename);
2087 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2088 Error(FileNumberLoc, "file number already allocated");
2094 /// ParseDirectiveLine
2095 /// ::= .line [number]
2096 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2097 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2098 if (getLexer().isNot(AsmToken::Integer))
2099 return TokError("unexpected token in '.line' directive");
2101 int64_t LineNumber = getTok().getIntVal();
2105 // FIXME: Do something with the .line.
2108 if (getLexer().isNot(AsmToken::EndOfStatement))
2109 return TokError("unexpected token in '.line' directive");
2115 /// ParseDirectiveLoc
2116 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2117 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2118 /// The first number is a file number, must have been previously assigned with
2119 /// a .file directive, the second number is the line number and optionally the
2120 /// third number is a column position (zero if not specified). The remaining
2121 /// optional items are .loc sub-directives.
2122 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2124 if (getLexer().isNot(AsmToken::Integer))
2125 return TokError("unexpected token in '.loc' directive");
2126 int64_t FileNumber = getTok().getIntVal();
2128 return TokError("file number less than one in '.loc' directive");
2129 if (!getContext().isValidDwarfFileNumber(FileNumber))
2130 return TokError("unassigned file number in '.loc' directive");
2133 int64_t LineNumber = 0;
2134 if (getLexer().is(AsmToken::Integer)) {
2135 LineNumber = getTok().getIntVal();
2137 return TokError("line number less than one in '.loc' directive");
2141 int64_t ColumnPos = 0;
2142 if (getLexer().is(AsmToken::Integer)) {
2143 ColumnPos = getTok().getIntVal();
2145 return TokError("column position less than zero in '.loc' directive");
2149 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2151 int64_t Discriminator = 0;
2152 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2154 if (getLexer().is(AsmToken::EndOfStatement))
2158 SMLoc Loc = getTok().getLoc();
2159 if (getParser().ParseIdentifier(Name))
2160 return TokError("unexpected token in '.loc' directive");
2162 if (Name == "basic_block")
2163 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2164 else if (Name == "prologue_end")
2165 Flags |= DWARF2_FLAG_PROLOGUE_END;
2166 else if (Name == "epilogue_begin")
2167 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2168 else if (Name == "is_stmt") {
2169 SMLoc Loc = getTok().getLoc();
2170 const MCExpr *Value;
2171 if (getParser().ParseExpression(Value))
2173 // The expression must be the constant 0 or 1.
2174 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2175 int Value = MCE->getValue();
2177 Flags &= ~DWARF2_FLAG_IS_STMT;
2178 else if (Value == 1)
2179 Flags |= DWARF2_FLAG_IS_STMT;
2181 return Error(Loc, "is_stmt value not 0 or 1");
2184 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2187 else if (Name == "isa") {
2188 SMLoc Loc = getTok().getLoc();
2189 const MCExpr *Value;
2190 if (getParser().ParseExpression(Value))
2192 // The expression must be a constant greater or equal to 0.
2193 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2194 int Value = MCE->getValue();
2196 return Error(Loc, "isa number less than zero");
2200 return Error(Loc, "isa number not a constant value");
2203 else if (Name == "discriminator") {
2204 if (getParser().ParseAbsoluteExpression(Discriminator))
2208 return Error(Loc, "unknown sub-directive in '.loc' directive");
2211 if (getLexer().is(AsmToken::EndOfStatement))
2216 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2217 Isa, Discriminator);
2222 /// ParseDirectiveStabs
2223 /// ::= .stabs string, number, number, number
2224 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2225 SMLoc DirectiveLoc) {
2226 return TokError("unsupported directive '" + Directive + "'");
2229 /// ParseDirectiveCFIStartProc
2230 /// ::= .cfi_startproc
2231 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2232 SMLoc DirectiveLoc) {
2233 return getStreamer().EmitCFIStartProc();
2236 /// ParseDirectiveCFIEndProc
2237 /// ::= .cfi_endproc
2238 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2239 return getStreamer().EmitCFIEndProc();
2242 /// ParseRegisterOrRegisterNumber - parse register name or number.
2243 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2244 SMLoc DirectiveLoc) {
2247 if (getLexer().is(AsmToken::Percent)) {
2248 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2251 Register = getContext().getTargetAsmInfo().getDwarfRegNum(RegNo, true);
2253 return getParser().ParseAbsoluteExpression(Register);
2258 /// ParseDirectiveCFIDefCfa
2259 /// ::= .cfi_def_cfa register, offset
2260 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2261 SMLoc DirectiveLoc) {
2262 int64_t Register = 0;
2263 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2266 if (getLexer().isNot(AsmToken::Comma))
2267 return TokError("unexpected token in directive");
2271 if (getParser().ParseAbsoluteExpression(Offset))
2274 return getStreamer().EmitCFIDefCfa(Register, Offset);
2277 /// ParseDirectiveCFIDefCfaOffset
2278 /// ::= .cfi_def_cfa_offset offset
2279 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2280 SMLoc DirectiveLoc) {
2282 if (getParser().ParseAbsoluteExpression(Offset))
2285 return getStreamer().EmitCFIDefCfaOffset(Offset);
2288 /// ParseDirectiveCFIDefCfaRegister
2289 /// ::= .cfi_def_cfa_register register
2290 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2291 SMLoc DirectiveLoc) {
2292 int64_t Register = 0;
2293 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2296 return getStreamer().EmitCFIDefCfaRegister(Register);
2299 /// ParseDirectiveCFIOffset
2300 /// ::= .cfi_off register, offset
2301 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2302 int64_t Register = 0;
2305 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2308 if (getLexer().isNot(AsmToken::Comma))
2309 return TokError("unexpected token in directive");
2312 if (getParser().ParseAbsoluteExpression(Offset))
2315 return getStreamer().EmitCFIOffset(Register, Offset);
2318 static bool isValidEncoding(int64_t Encoding) {
2319 if (Encoding & ~0xff)
2322 if (Encoding == dwarf::DW_EH_PE_omit)
2325 const unsigned Format = Encoding & 0xf;
2326 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2327 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2328 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2329 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2332 const unsigned Application = Encoding & 0x70;
2333 if (Application != dwarf::DW_EH_PE_absptr &&
2334 Application != dwarf::DW_EH_PE_pcrel)
2340 /// ParseDirectiveCFIPersonalityOrLsda
2341 /// ::= .cfi_personality encoding, [symbol_name]
2342 /// ::= .cfi_lsda encoding, [symbol_name]
2343 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2344 SMLoc DirectiveLoc) {
2345 int64_t Encoding = 0;
2346 if (getParser().ParseAbsoluteExpression(Encoding))
2348 if (Encoding == dwarf::DW_EH_PE_omit)
2351 if (!isValidEncoding(Encoding))
2352 return TokError("unsupported encoding.");
2354 if (getLexer().isNot(AsmToken::Comma))
2355 return TokError("unexpected token in directive");
2359 if (getParser().ParseIdentifier(Name))
2360 return TokError("expected identifier in directive");
2362 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2364 if (IDVal == ".cfi_personality")
2365 return getStreamer().EmitCFIPersonality(Sym, Encoding);
2367 assert(IDVal == ".cfi_lsda");
2368 return getStreamer().EmitCFILsda(Sym, Encoding);
2372 /// ParseDirectiveCFIRememberState
2373 /// ::= .cfi_remember_state
2374 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2375 SMLoc DirectiveLoc) {
2376 return getStreamer().EmitCFIRememberState();
2379 /// ParseDirectiveCFIRestoreState
2380 /// ::= .cfi_remember_state
2381 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2382 SMLoc DirectiveLoc) {
2383 return getStreamer().EmitCFIRestoreState();
2386 /// ParseDirectiveMacrosOnOff
2389 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2390 SMLoc DirectiveLoc) {
2391 if (getLexer().isNot(AsmToken::EndOfStatement))
2392 return Error(getLexer().getLoc(),
2393 "unexpected token in '" + Directive + "' directive");
2395 getParser().MacrosEnabled = Directive == ".macros_on";
2400 /// ParseDirectiveMacro
2402 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2403 SMLoc DirectiveLoc) {
2405 if (getParser().ParseIdentifier(Name))
2406 return TokError("expected identifier in directive");
2408 if (getLexer().isNot(AsmToken::EndOfStatement))
2409 return TokError("unexpected token in '.macro' directive");
2411 // Eat the end of statement.
2414 AsmToken EndToken, StartToken = getTok();
2416 // Lex the macro definition.
2418 // Check whether we have reached the end of the file.
2419 if (getLexer().is(AsmToken::Eof))
2420 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2422 // Otherwise, check whether we have reach the .endmacro.
2423 if (getLexer().is(AsmToken::Identifier) &&
2424 (getTok().getIdentifier() == ".endm" ||
2425 getTok().getIdentifier() == ".endmacro")) {
2426 EndToken = getTok();
2428 if (getLexer().isNot(AsmToken::EndOfStatement))
2429 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2434 // Otherwise, scan til the end of the statement.
2435 getParser().EatToEndOfStatement();
2438 if (getParser().MacroMap.lookup(Name)) {
2439 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2442 const char *BodyStart = StartToken.getLoc().getPointer();
2443 const char *BodyEnd = EndToken.getLoc().getPointer();
2444 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2445 getParser().MacroMap[Name] = new Macro(Name, Body);
2449 /// ParseDirectiveEndMacro
2452 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2453 SMLoc DirectiveLoc) {
2454 if (getLexer().isNot(AsmToken::EndOfStatement))
2455 return TokError("unexpected token in '" + Directive + "' directive");
2457 // If we are inside a macro instantiation, terminate the current
2459 if (!getParser().ActiveMacros.empty()) {
2460 getParser().HandleMacroExit();
2464 // Otherwise, this .endmacro is a stray entry in the file; well formed
2465 // .endmacro directives are handled during the macro definition parsing.
2466 return TokError("unexpected '" + Directive + "' in file, "
2467 "no current macro definition");
2470 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2471 getParser().CheckForValidSection();
2473 const MCExpr *Value;
2475 if (getParser().ParseExpression(Value))
2478 if (getLexer().isNot(AsmToken::EndOfStatement))
2479 return TokError("unexpected token in directive");
2481 if (DirName[1] == 's')
2482 getStreamer().EmitSLEB128Value(Value);
2484 getStreamer().EmitULEB128Value(Value);
2490 /// \brief Create an MCAsmParser instance.
2491 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2492 MCContext &C, MCStreamer &Out,
2493 const MCAsmInfo &MAI) {
2494 return new AsmParser(T, SM, C, Out, MAI);