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);
177 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
178 /// and set \arg Res to the identifier contents.
179 bool ParseIdentifier(StringRef &Res);
181 // Directive Parsing.
183 // ".ascii", ".asciiz", ".string"
184 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
185 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
186 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
187 bool ParseDirectiveFill(); // ".fill"
188 bool ParseDirectiveSpace(); // ".space"
189 bool ParseDirectiveZero(); // ".zero"
190 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
191 bool ParseDirectiveOrg(); // ".org"
192 // ".align{,32}", ".p2align{,w,l}"
193 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
195 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
196 /// accepts a single symbol (which should be a label or an external).
197 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
199 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
201 bool ParseDirectiveAbort(); // ".abort"
202 bool ParseDirectiveInclude(); // ".include"
204 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
205 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
206 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
207 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
209 /// ParseEscapedString - Parse the current token as a string which may include
210 /// escaped characters and return the string contents.
211 bool ParseEscapedString(std::string &Data);
213 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
214 MCSymbolRefExpr::VariantKind Variant);
217 /// \brief Generic implementations of directive handling, etc. which is shared
218 /// (or the default, at least) for all assembler parser.
219 class GenericAsmParser : public MCAsmParserExtension {
220 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
221 void AddDirectiveHandler(StringRef Directive) {
222 getParser().AddDirectiveHandler(this, Directive,
223 HandleDirective<GenericAsmParser, Handler>);
227 GenericAsmParser() {}
229 AsmParser &getParser() {
230 return (AsmParser&) this->MCAsmParserExtension::getParser();
233 virtual void Initialize(MCAsmParser &Parser) {
234 // Call the base implementation.
235 this->MCAsmParserExtension::Initialize(Parser);
237 // Debugging directives.
238 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
239 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
240 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
241 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
244 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
246 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
248 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
250 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
251 ".cfi_def_cfa_offset");
252 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
253 ".cfi_def_cfa_register");
254 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
257 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
259 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
261 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
263 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
266 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
268 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
270 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
271 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
272 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
274 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
275 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
278 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
280 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
281 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
282 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
283 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
284 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
285 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
286 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
287 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
288 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
289 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
290 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
291 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
292 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
294 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
295 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
296 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
298 bool ParseDirectiveLEB128(StringRef, SMLoc);
305 extern MCAsmParserExtension *createDarwinAsmParser();
306 extern MCAsmParserExtension *createELFAsmParser();
307 extern MCAsmParserExtension *createCOFFAsmParser();
311 enum { DEFAULT_ADDRSPACE = 0 };
313 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
314 MCStreamer &_Out, const MCAsmInfo &_MAI)
315 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
316 GenericParser(new GenericAsmParser), PlatformParser(0),
317 CurBuffer(0), MacrosEnabled(true) {
318 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
320 // Initialize the generic parser.
321 GenericParser->Initialize(*this);
323 // Initialize the platform / file format parser.
325 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
327 if (_MAI.hasMicrosoftFastStdCallMangling()) {
328 PlatformParser = createCOFFAsmParser();
329 PlatformParser->Initialize(*this);
330 } else if (_MAI.hasSubsectionsViaSymbols()) {
331 PlatformParser = createDarwinAsmParser();
332 PlatformParser->Initialize(*this);
334 PlatformParser = createELFAsmParser();
335 PlatformParser->Initialize(*this);
339 AsmParser::~AsmParser() {
340 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
342 // Destroy any macros.
343 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
344 ie = MacroMap.end(); it != ie; ++it)
345 delete it->getValue();
347 delete PlatformParser;
348 delete GenericParser;
351 void AsmParser::PrintMacroInstantiations() {
352 // Print the active macro instantiation stack.
353 for (std::vector<MacroInstantiation*>::const_reverse_iterator
354 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
355 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
359 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
360 PrintMessage(L, Msg, "warning");
361 PrintMacroInstantiations();
364 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
366 PrintMessage(L, Msg, "error");
367 PrintMacroInstantiations();
371 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
372 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
378 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
383 void AsmParser::JumpToLoc(SMLoc Loc) {
384 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
385 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
388 const AsmToken &AsmParser::Lex() {
389 const AsmToken *tok = &Lexer.Lex();
391 if (tok->is(AsmToken::Eof)) {
392 // If this is the end of an included file, pop the parent file off the
394 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
395 if (ParentIncludeLoc != SMLoc()) {
396 JumpToLoc(ParentIncludeLoc);
401 if (tok->is(AsmToken::Error))
402 Error(Lexer.getErrLoc(), Lexer.getErr());
407 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
408 // Create the initial section, if requested.
409 if (!NoInitialTextSection)
416 AsmCond StartingCondState = TheCondState;
418 // While we have input, parse each statement.
419 while (Lexer.isNot(AsmToken::Eof)) {
420 if (!ParseStatement()) continue;
422 // We had an error, validate that one was emitted and recover by skipping to
424 assert(HadError && "Parse statement returned an error, but none emitted!");
425 EatToEndOfStatement();
428 if (TheCondState.TheCond != StartingCondState.TheCond ||
429 TheCondState.Ignore != StartingCondState.Ignore)
430 return TokError("unmatched .ifs or .elses");
432 // Check to see there are no empty DwarfFile slots.
433 const std::vector<MCDwarfFile *> &MCDwarfFiles =
434 getContext().getMCDwarfFiles();
435 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
436 if (!MCDwarfFiles[i])
437 TokError("unassigned file number: " + Twine(i) + " for .file directives");
440 // Finalize the output stream if there are no errors and if the client wants
442 if (!HadError && !NoFinalize)
448 void AsmParser::CheckForValidSection() {
449 if (!getStreamer().getCurrentSection()) {
450 TokError("expected section directive before assembly directive");
451 Out.SwitchSection(Ctx.getMachOSection(
453 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
454 0, SectionKind::getText()));
458 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
459 void AsmParser::EatToEndOfStatement() {
460 while (Lexer.isNot(AsmToken::EndOfStatement) &&
461 Lexer.isNot(AsmToken::Eof))
465 if (Lexer.is(AsmToken::EndOfStatement))
469 StringRef AsmParser::ParseStringToEndOfStatement() {
470 const char *Start = getTok().getLoc().getPointer();
472 while (Lexer.isNot(AsmToken::EndOfStatement) &&
473 Lexer.isNot(AsmToken::Eof))
476 const char *End = getTok().getLoc().getPointer();
477 return StringRef(Start, End - Start);
480 /// ParseParenExpr - Parse a paren expression and return it.
481 /// NOTE: This assumes the leading '(' has already been consumed.
483 /// parenexpr ::= expr)
485 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
486 if (ParseExpression(Res)) return true;
487 if (Lexer.isNot(AsmToken::RParen))
488 return TokError("expected ')' in parentheses expression");
489 EndLoc = Lexer.getLoc();
494 /// ParsePrimaryExpr - Parse a primary expression and return it.
495 /// primaryexpr ::= (parenexpr
496 /// primaryexpr ::= symbol
497 /// primaryexpr ::= number
498 /// primaryexpr ::= '.'
499 /// primaryexpr ::= ~,+,- primaryexpr
500 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
501 switch (Lexer.getKind()) {
503 return TokError("unknown token in expression");
504 case AsmToken::Exclaim:
505 Lex(); // Eat the operator.
506 if (ParsePrimaryExpr(Res, EndLoc))
508 Res = MCUnaryExpr::CreateLNot(Res, getContext());
510 case AsmToken::Dollar:
511 case AsmToken::String:
512 case AsmToken::Identifier: {
513 EndLoc = Lexer.getLoc();
515 StringRef Identifier;
516 if (ParseIdentifier(Identifier))
519 // This is a symbol reference.
520 std::pair<StringRef, StringRef> Split = Identifier.split('@');
521 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
523 // Lookup the symbol variant if used.
524 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
525 if (Split.first.size() != Identifier.size()) {
526 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
527 if (Variant == MCSymbolRefExpr::VK_Invalid) {
528 Variant = MCSymbolRefExpr::VK_None;
529 return TokError("invalid variant '" + Split.second + "'");
533 // If this is an absolute variable reference, substitute it now to preserve
534 // semantics in the face of reassignment.
535 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
537 return Error(EndLoc, "unexpected modifier on variable reference");
539 Res = Sym->getVariableValue();
543 // Otherwise create a symbol ref.
544 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
547 case AsmToken::Integer: {
548 SMLoc Loc = getTok().getLoc();
549 int64_t IntVal = getTok().getIntVal();
550 Res = MCConstantExpr::Create(IntVal, getContext());
551 EndLoc = Lexer.getLoc();
553 // Look for 'b' or 'f' following an Integer as a directional label
554 if (Lexer.getKind() == AsmToken::Identifier) {
555 StringRef IDVal = getTok().getString();
556 if (IDVal == "f" || IDVal == "b"){
557 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
558 IDVal == "f" ? 1 : 0);
559 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
561 if(IDVal == "b" && Sym->isUndefined())
562 return Error(Loc, "invalid reference to undefined symbol");
563 EndLoc = Lexer.getLoc();
564 Lex(); // Eat identifier.
569 case AsmToken::Real: {
570 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
571 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
572 Res = MCConstantExpr::Create(IntVal, getContext());
576 case AsmToken::Dot: {
577 // This is a '.' reference, which references the current PC. Emit a
578 // temporary label to the streamer and refer to it.
579 MCSymbol *Sym = Ctx.CreateTempSymbol();
581 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
582 EndLoc = Lexer.getLoc();
583 Lex(); // Eat identifier.
586 case AsmToken::LParen:
587 Lex(); // Eat the '('.
588 return ParseParenExpr(Res, EndLoc);
589 case AsmToken::Minus:
590 Lex(); // Eat the operator.
591 if (ParsePrimaryExpr(Res, EndLoc))
593 Res = MCUnaryExpr::CreateMinus(Res, getContext());
596 Lex(); // Eat the operator.
597 if (ParsePrimaryExpr(Res, EndLoc))
599 Res = MCUnaryExpr::CreatePlus(Res, getContext());
601 case AsmToken::Tilde:
602 Lex(); // Eat the operator.
603 if (ParsePrimaryExpr(Res, EndLoc))
605 Res = MCUnaryExpr::CreateNot(Res, getContext());
610 bool AsmParser::ParseExpression(const MCExpr *&Res) {
612 return ParseExpression(Res, EndLoc);
616 AsmParser::ApplyModifierToExpr(const MCExpr *E,
617 MCSymbolRefExpr::VariantKind Variant) {
618 // Recurse over the given expression, rebuilding it to apply the given variant
619 // if there is exactly one symbol.
620 switch (E->getKind()) {
622 case MCExpr::Constant:
625 case MCExpr::SymbolRef: {
626 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
628 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
629 TokError("invalid variant on expression '" +
630 getTok().getIdentifier() + "' (already modified)");
634 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
637 case MCExpr::Unary: {
638 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
639 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
642 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
645 case MCExpr::Binary: {
646 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
647 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
648 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
653 if (!LHS) LHS = BE->getLHS();
654 if (!RHS) RHS = BE->getRHS();
656 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
660 assert(0 && "Invalid expression kind!");
664 /// ParseExpression - Parse an expression and return it.
666 /// expr ::= expr +,- expr -> lowest.
667 /// expr ::= expr |,^,&,! expr -> middle.
668 /// expr ::= expr *,/,%,<<,>> expr -> highest.
669 /// expr ::= primaryexpr
671 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
672 // Parse the expression.
674 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
677 // As a special case, we support 'a op b @ modifier' by rewriting the
678 // expression to include the modifier. This is inefficient, but in general we
679 // expect users to use 'a@modifier op b'.
680 if (Lexer.getKind() == AsmToken::At) {
683 if (Lexer.isNot(AsmToken::Identifier))
684 return TokError("unexpected symbol modifier following '@'");
686 MCSymbolRefExpr::VariantKind Variant =
687 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
688 if (Variant == MCSymbolRefExpr::VK_Invalid)
689 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
691 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
693 return TokError("invalid modifier '" + getTok().getIdentifier() +
694 "' (no symbols present)");
702 // Try to constant fold it up front, if possible.
704 if (Res->EvaluateAsAbsolute(Value))
705 Res = MCConstantExpr::Create(Value, getContext());
710 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
712 return ParseParenExpr(Res, EndLoc) ||
713 ParseBinOpRHS(1, Res, EndLoc);
716 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
719 SMLoc StartLoc = Lexer.getLoc();
720 if (ParseExpression(Expr))
723 if (!Expr->EvaluateAsAbsolute(Res))
724 return Error(StartLoc, "expected absolute expression");
729 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
730 MCBinaryExpr::Opcode &Kind) {
733 return 0; // not a binop.
735 // Lowest Precedence: &&, ||, @
736 case AsmToken::AmpAmp:
737 Kind = MCBinaryExpr::LAnd;
739 case AsmToken::PipePipe:
740 Kind = MCBinaryExpr::LOr;
744 // Low Precedence: |, &, ^
746 // FIXME: gas seems to support '!' as an infix operator?
748 Kind = MCBinaryExpr::Or;
750 case AsmToken::Caret:
751 Kind = MCBinaryExpr::Xor;
754 Kind = MCBinaryExpr::And;
757 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
758 case AsmToken::EqualEqual:
759 Kind = MCBinaryExpr::EQ;
761 case AsmToken::ExclaimEqual:
762 case AsmToken::LessGreater:
763 Kind = MCBinaryExpr::NE;
766 Kind = MCBinaryExpr::LT;
768 case AsmToken::LessEqual:
769 Kind = MCBinaryExpr::LTE;
771 case AsmToken::Greater:
772 Kind = MCBinaryExpr::GT;
774 case AsmToken::GreaterEqual:
775 Kind = MCBinaryExpr::GTE;
778 // High Intermediate Precedence: +, -
780 Kind = MCBinaryExpr::Add;
782 case AsmToken::Minus:
783 Kind = MCBinaryExpr::Sub;
786 // Highest Precedence: *, /, %, <<, >>
788 Kind = MCBinaryExpr::Mul;
790 case AsmToken::Slash:
791 Kind = MCBinaryExpr::Div;
793 case AsmToken::Percent:
794 Kind = MCBinaryExpr::Mod;
796 case AsmToken::LessLess:
797 Kind = MCBinaryExpr::Shl;
799 case AsmToken::GreaterGreater:
800 Kind = MCBinaryExpr::Shr;
806 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
807 /// Res contains the LHS of the expression on input.
808 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
811 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
812 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
814 // If the next token is lower precedence than we are allowed to eat, return
815 // successfully with what we ate already.
816 if (TokPrec < Precedence)
821 // Eat the next primary expression.
823 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
825 // If BinOp binds less tightly with RHS than the operator after RHS, let
826 // the pending operator take RHS as its LHS.
827 MCBinaryExpr::Opcode Dummy;
828 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
829 if (TokPrec < NextTokPrec) {
830 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
833 // Merge LHS and RHS according to operator.
834 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
842 /// ::= EndOfStatement
843 /// ::= Label* Directive ...Operands... EndOfStatement
844 /// ::= Label* Identifier OperandList* EndOfStatement
845 bool AsmParser::ParseStatement() {
846 if (Lexer.is(AsmToken::EndOfStatement)) {
852 // Statements always start with an identifier or are a full line comment.
853 AsmToken ID = getTok();
854 SMLoc IDLoc = ID.getLoc();
856 int64_t LocalLabelVal = -1;
857 // A full line comment is a '#' as the first token.
858 if (Lexer.is(AsmToken::Hash)) {
859 EatToEndOfStatement();
862 // Allow an integer followed by a ':' as a directional local label.
863 if (Lexer.is(AsmToken::Integer)) {
864 LocalLabelVal = getTok().getIntVal();
865 if (LocalLabelVal < 0) {
866 if (!TheCondState.Ignore)
867 return TokError("unexpected token at start of statement");
871 IDVal = getTok().getString();
872 Lex(); // Consume the integer token to be used as an identifier token.
873 if (Lexer.getKind() != AsmToken::Colon) {
874 if (!TheCondState.Ignore)
875 return TokError("unexpected token at start of statement");
879 else if (ParseIdentifier(IDVal)) {
880 if (!TheCondState.Ignore)
881 return TokError("unexpected token at start of statement");
885 // Handle conditional assembly here before checking for skipping. We
886 // have to do this so that .endif isn't skipped in a ".if 0" block for
889 return ParseDirectiveIf(IDLoc);
890 if (IDVal == ".elseif")
891 return ParseDirectiveElseIf(IDLoc);
892 if (IDVal == ".else")
893 return ParseDirectiveElse(IDLoc);
894 if (IDVal == ".endif")
895 return ParseDirectiveEndIf(IDLoc);
897 // If we are in a ".if 0" block, ignore this statement.
898 if (TheCondState.Ignore) {
899 EatToEndOfStatement();
903 // FIXME: Recurse on local labels?
905 // See what kind of statement we have.
906 switch (Lexer.getKind()) {
907 case AsmToken::Colon: {
908 CheckForValidSection();
910 // identifier ':' -> Label.
913 // Diagnose attempt to use a variable as a label.
915 // FIXME: Diagnostics. Note the location of the definition as a label.
916 // FIXME: This doesn't diagnose assignment to a symbol which has been
917 // implicitly marked as external.
919 if (LocalLabelVal == -1)
920 Sym = getContext().GetOrCreateSymbol(IDVal);
922 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
923 if (!Sym->isUndefined() || Sym->isVariable())
924 return Error(IDLoc, "invalid symbol redefinition");
929 // Consume any end of statement token, if present, to avoid spurious
930 // AddBlankLine calls().
931 if (Lexer.is(AsmToken::EndOfStatement)) {
933 if (Lexer.is(AsmToken::Eof))
937 return ParseStatement();
940 case AsmToken::Equal:
941 // identifier '=' ... -> assignment statement
944 return ParseAssignment(IDVal, true);
946 default: // Normal instruction or directive.
950 // If macros are enabled, check to see if this is a macro instantiation.
952 if (const Macro *M = MacroMap.lookup(IDVal))
953 return HandleMacroEntry(IDVal, IDLoc, M);
955 // Otherwise, we have a normal instruction or directive.
956 if (IDVal[0] == '.') {
957 // Assembler features
958 if (IDVal == ".set" || IDVal == ".equ")
959 return ParseDirectiveSet(IDVal, true);
960 if (IDVal == ".equiv")
961 return ParseDirectiveSet(IDVal, false);
965 if (IDVal == ".ascii")
966 return ParseDirectiveAscii(IDVal, false);
967 if (IDVal == ".asciz" || IDVal == ".string")
968 return ParseDirectiveAscii(IDVal, true);
970 if (IDVal == ".byte")
971 return ParseDirectiveValue(1);
972 if (IDVal == ".short")
973 return ParseDirectiveValue(2);
974 if (IDVal == ".value")
975 return ParseDirectiveValue(2);
976 if (IDVal == ".2byte")
977 return ParseDirectiveValue(2);
978 if (IDVal == ".long")
979 return ParseDirectiveValue(4);
981 return ParseDirectiveValue(4);
982 if (IDVal == ".4byte")
983 return ParseDirectiveValue(4);
984 if (IDVal == ".quad")
985 return ParseDirectiveValue(8);
986 if (IDVal == ".8byte")
987 return ParseDirectiveValue(8);
988 if (IDVal == ".single" || IDVal == ".float")
989 return ParseDirectiveRealValue(APFloat::IEEEsingle);
990 if (IDVal == ".double")
991 return ParseDirectiveRealValue(APFloat::IEEEdouble);
993 if (IDVal == ".align") {
994 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
995 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
997 if (IDVal == ".align32") {
998 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
999 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1001 if (IDVal == ".balign")
1002 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1003 if (IDVal == ".balignw")
1004 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1005 if (IDVal == ".balignl")
1006 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1007 if (IDVal == ".p2align")
1008 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1009 if (IDVal == ".p2alignw")
1010 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1011 if (IDVal == ".p2alignl")
1012 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1014 if (IDVal == ".org")
1015 return ParseDirectiveOrg();
1017 if (IDVal == ".fill")
1018 return ParseDirectiveFill();
1019 if (IDVal == ".space")
1020 return ParseDirectiveSpace();
1021 if (IDVal == ".zero")
1022 return ParseDirectiveZero();
1024 // Symbol attribute directives
1026 if (IDVal == ".globl" || IDVal == ".global")
1027 return ParseDirectiveSymbolAttribute(MCSA_Global);
1028 // ELF only? Should it be here?
1029 if (IDVal == ".local")
1030 return ParseDirectiveSymbolAttribute(MCSA_Local);
1031 if (IDVal == ".hidden")
1032 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1033 if (IDVal == ".indirect_symbol")
1034 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1035 if (IDVal == ".internal")
1036 return ParseDirectiveSymbolAttribute(MCSA_Internal);
1037 if (IDVal == ".lazy_reference")
1038 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1039 if (IDVal == ".no_dead_strip")
1040 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1041 if (IDVal == ".symbol_resolver")
1042 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1043 if (IDVal == ".private_extern")
1044 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1045 if (IDVal == ".protected")
1046 return ParseDirectiveSymbolAttribute(MCSA_Protected);
1047 if (IDVal == ".reference")
1048 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1049 if (IDVal == ".weak")
1050 return ParseDirectiveSymbolAttribute(MCSA_Weak);
1051 if (IDVal == ".weak_definition")
1052 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1053 if (IDVal == ".weak_reference")
1054 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1055 if (IDVal == ".weak_def_can_be_hidden")
1056 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1058 if (IDVal == ".comm")
1059 return ParseDirectiveComm(/*IsLocal=*/false);
1060 if (IDVal == ".lcomm")
1061 return ParseDirectiveComm(/*IsLocal=*/true);
1063 if (IDVal == ".abort")
1064 return ParseDirectiveAbort();
1065 if (IDVal == ".include")
1066 return ParseDirectiveInclude();
1068 if (IDVal == ".code16" || IDVal == ".code32" || IDVal == ".code64")
1069 return TokError(Twine(IDVal) + " not supported yet");
1071 // Look up the handler in the handler table.
1072 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1073 DirectiveMap.lookup(IDVal);
1075 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1077 // Target hook for parsing target specific directives.
1078 if (!getTargetParser().ParseDirective(ID))
1081 Warning(IDLoc, "ignoring directive for now");
1082 EatToEndOfStatement();
1086 CheckForValidSection();
1088 // Canonicalize the opcode to lower case.
1089 SmallString<128> Opcode;
1090 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1091 Opcode.push_back(tolower(IDVal[i]));
1093 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1094 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1097 // Dump the parsed representation, if requested.
1098 if (getShowParsedOperands()) {
1099 SmallString<256> Str;
1100 raw_svector_ostream OS(Str);
1101 OS << "parsed instruction: [";
1102 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1105 ParsedOperands[i]->dump(OS);
1109 PrintMessage(IDLoc, OS.str(), "note");
1112 // If parsing succeeded, match the instruction.
1114 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1117 // Free any parsed operands.
1118 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1119 delete ParsedOperands[i];
1121 // Don't skip the rest of the line, the instruction parser is responsible for
1126 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1127 const std::vector<std::vector<AsmToken> > &A)
1128 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1130 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1131 // to hold the macro body with substitutions.
1132 SmallString<256> Buf;
1133 raw_svector_ostream OS(Buf);
1135 StringRef Body = M->Body;
1136 while (!Body.empty()) {
1137 // Scan for the next substitution.
1138 std::size_t End = Body.size(), Pos = 0;
1139 for (; Pos != End; ++Pos) {
1140 // Check for a substitution or escape.
1141 if (Body[Pos] != '$' || Pos + 1 == End)
1144 char Next = Body[Pos + 1];
1145 if (Next == '$' || Next == 'n' || isdigit(Next))
1150 OS << Body.slice(0, Pos);
1152 // Check if we reached the end.
1156 switch (Body[Pos+1]) {
1162 // $n => number of arguments
1167 // $[0-9] => argument
1169 // Missing arguments are ignored.
1170 unsigned Index = Body[Pos+1] - '0';
1171 if (Index >= A.size())
1174 // Otherwise substitute with the token values, with spaces eliminated.
1175 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1176 ie = A[Index].end(); it != ie; ++it)
1177 OS << it->getString();
1182 // Update the scan point.
1183 Body = Body.substr(Pos + 2);
1186 // We include the .endmacro in the buffer as our queue to exit the macro
1188 OS << ".endmacro\n";
1190 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1193 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1195 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1196 // this, although we should protect against infinite loops.
1197 if (ActiveMacros.size() == 20)
1198 return TokError("macros cannot be nested more than 20 levels deep");
1200 // Parse the macro instantiation arguments.
1201 std::vector<std::vector<AsmToken> > MacroArguments;
1202 MacroArguments.push_back(std::vector<AsmToken>());
1203 unsigned ParenLevel = 0;
1205 if (Lexer.is(AsmToken::Eof))
1206 return TokError("unexpected token in macro instantiation");
1207 if (Lexer.is(AsmToken::EndOfStatement))
1210 // If we aren't inside parentheses and this is a comma, start a new token
1212 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1213 MacroArguments.push_back(std::vector<AsmToken>());
1215 // Adjust the current parentheses level.
1216 if (Lexer.is(AsmToken::LParen))
1218 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1221 // Append the token to the current argument list.
1222 MacroArguments.back().push_back(getTok());
1227 // Create the macro instantiation object and add to the current macro
1228 // instantiation stack.
1229 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1232 ActiveMacros.push_back(MI);
1234 // Jump to the macro instantiation and prime the lexer.
1235 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1236 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1242 void AsmParser::HandleMacroExit() {
1243 // Jump to the EndOfStatement we should return to, and consume it.
1244 JumpToLoc(ActiveMacros.back()->ExitLoc);
1247 // Pop the instantiation entry.
1248 delete ActiveMacros.back();
1249 ActiveMacros.pop_back();
1252 static void MarkUsed(const MCExpr *Value) {
1253 switch (Value->getKind()) {
1254 case MCExpr::Binary:
1255 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1256 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1258 case MCExpr::Target:
1259 case MCExpr::Constant:
1261 case MCExpr::SymbolRef: {
1262 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1266 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1271 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1272 // FIXME: Use better location, we should use proper tokens.
1273 SMLoc EqualLoc = Lexer.getLoc();
1275 const MCExpr *Value;
1276 if (ParseExpression(Value))
1281 if (Lexer.isNot(AsmToken::EndOfStatement))
1282 return TokError("unexpected token in assignment");
1284 // Eat the end of statement marker.
1287 // Validate that the LHS is allowed to be a variable (either it has not been
1288 // used as a symbol, or it is an absolute symbol).
1289 MCSymbol *Sym = getContext().LookupSymbol(Name);
1291 // Diagnose assignment to a label.
1293 // FIXME: Diagnostics. Note the location of the definition as a label.
1294 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1295 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1296 ; // Allow redefinitions of undefined symbols only used in directives.
1297 else if (!Sym->isUndefined() && (!Sym->isAbsolute() || !allow_redef))
1298 return Error(EqualLoc, "redefinition of '" + Name + "'");
1299 else if (!Sym->isVariable())
1300 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1301 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1302 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1305 // Don't count these checks as uses.
1306 Sym->setUsed(false);
1308 Sym = getContext().GetOrCreateSymbol(Name);
1310 // FIXME: Handle '.'.
1312 // Do the assignment.
1313 Out.EmitAssignment(Sym, Value);
1318 /// ParseIdentifier:
1321 bool AsmParser::ParseIdentifier(StringRef &Res) {
1322 // The assembler has relaxed rules for accepting identifiers, in particular we
1323 // allow things like '.globl $foo', which would normally be separate
1324 // tokens. At this level, we have already lexed so we cannot (currently)
1325 // handle this as a context dependent token, instead we detect adjacent tokens
1326 // and return the combined identifier.
1327 if (Lexer.is(AsmToken::Dollar)) {
1328 SMLoc DollarLoc = getLexer().getLoc();
1330 // Consume the dollar sign, and check for a following identifier.
1332 if (Lexer.isNot(AsmToken::Identifier))
1335 // We have a '$' followed by an identifier, make sure they are adjacent.
1336 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1339 // Construct the joined identifier and consume the token.
1340 Res = StringRef(DollarLoc.getPointer(),
1341 getTok().getIdentifier().size() + 1);
1346 if (Lexer.isNot(AsmToken::Identifier) &&
1347 Lexer.isNot(AsmToken::String))
1350 Res = getTok().getIdentifier();
1352 Lex(); // Consume the identifier token.
1357 /// ParseDirectiveSet:
1358 /// ::= .equ identifier ',' expression
1359 /// ::= .equiv identifier ',' expression
1360 /// ::= .set identifier ',' expression
1361 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1364 if (ParseIdentifier(Name))
1365 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1367 if (getLexer().isNot(AsmToken::Comma))
1368 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1371 return ParseAssignment(Name, allow_redef);
1374 bool AsmParser::ParseEscapedString(std::string &Data) {
1375 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1378 StringRef Str = getTok().getStringContents();
1379 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1380 if (Str[i] != '\\') {
1385 // Recognize escaped characters. Note that this escape semantics currently
1386 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1389 return TokError("unexpected backslash at end of string");
1391 // Recognize octal sequences.
1392 if ((unsigned) (Str[i] - '0') <= 7) {
1393 // Consume up to three octal characters.
1394 unsigned Value = Str[i] - '0';
1396 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1398 Value = Value * 8 + (Str[i] - '0');
1400 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1402 Value = Value * 8 + (Str[i] - '0');
1407 return TokError("invalid octal escape sequence (out of range)");
1409 Data += (unsigned char) Value;
1413 // Otherwise recognize individual escapes.
1416 // Just reject invalid escape sequences for now.
1417 return TokError("invalid escape sequence (unrecognized character)");
1419 case 'b': Data += '\b'; break;
1420 case 'f': Data += '\f'; break;
1421 case 'n': Data += '\n'; break;
1422 case 'r': Data += '\r'; break;
1423 case 't': Data += '\t'; break;
1424 case '"': Data += '"'; break;
1425 case '\\': Data += '\\'; break;
1432 /// ParseDirectiveAscii:
1433 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1434 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1435 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1436 CheckForValidSection();
1439 if (getLexer().isNot(AsmToken::String))
1440 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1443 if (ParseEscapedString(Data))
1446 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1448 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1452 if (getLexer().is(AsmToken::EndOfStatement))
1455 if (getLexer().isNot(AsmToken::Comma))
1456 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1465 /// ParseDirectiveValue
1466 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1467 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1468 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1469 CheckForValidSection();
1472 const MCExpr *Value;
1473 if (ParseExpression(Value))
1476 // Special case constant expressions to match code generator.
1477 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1478 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1480 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1482 if (getLexer().is(AsmToken::EndOfStatement))
1485 // FIXME: Improve diagnostic.
1486 if (getLexer().isNot(AsmToken::Comma))
1487 return TokError("unexpected token in directive");
1496 /// ParseDirectiveRealValue
1497 /// ::= (.single | .double) [ expression (, expression)* ]
1498 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1499 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1500 CheckForValidSection();
1503 // We don't truly support arithmetic on floating point expressions, so we
1504 // have to manually parse unary prefixes.
1506 if (getLexer().is(AsmToken::Minus)) {
1509 } else if (getLexer().is(AsmToken::Plus))
1512 if (getLexer().isNot(AsmToken::Integer) &&
1513 getLexer().isNot(AsmToken::Real))
1514 return TokError("unexpected token in directive");
1516 // Convert to an APFloat.
1517 APFloat Value(Semantics);
1518 if (Value.convertFromString(getTok().getString(),
1519 APFloat::rmNearestTiesToEven) ==
1520 APFloat::opInvalidOp)
1521 return TokError("invalid floating point literal");
1525 // Consume the numeric token.
1528 // Emit the value as an integer.
1529 APInt AsInt = Value.bitcastToAPInt();
1530 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1531 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1533 if (getLexer().is(AsmToken::EndOfStatement))
1536 if (getLexer().isNot(AsmToken::Comma))
1537 return TokError("unexpected token in directive");
1546 /// ParseDirectiveSpace
1547 /// ::= .space expression [ , expression ]
1548 bool AsmParser::ParseDirectiveSpace() {
1549 CheckForValidSection();
1552 if (ParseAbsoluteExpression(NumBytes))
1555 int64_t FillExpr = 0;
1556 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1557 if (getLexer().isNot(AsmToken::Comma))
1558 return TokError("unexpected token in '.space' directive");
1561 if (ParseAbsoluteExpression(FillExpr))
1564 if (getLexer().isNot(AsmToken::EndOfStatement))
1565 return TokError("unexpected token in '.space' directive");
1571 return TokError("invalid number of bytes in '.space' directive");
1573 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1574 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1579 /// ParseDirectiveZero
1580 /// ::= .zero expression
1581 bool AsmParser::ParseDirectiveZero() {
1582 CheckForValidSection();
1585 if (ParseAbsoluteExpression(NumBytes))
1589 if (getLexer().is(AsmToken::Comma)) {
1591 if (ParseAbsoluteExpression(Val))
1595 if (getLexer().isNot(AsmToken::EndOfStatement))
1596 return TokError("unexpected token in '.zero' directive");
1600 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1605 /// ParseDirectiveFill
1606 /// ::= .fill expression , expression , expression
1607 bool AsmParser::ParseDirectiveFill() {
1608 CheckForValidSection();
1611 if (ParseAbsoluteExpression(NumValues))
1614 if (getLexer().isNot(AsmToken::Comma))
1615 return TokError("unexpected token in '.fill' directive");
1619 if (ParseAbsoluteExpression(FillSize))
1622 if (getLexer().isNot(AsmToken::Comma))
1623 return TokError("unexpected token in '.fill' directive");
1627 if (ParseAbsoluteExpression(FillExpr))
1630 if (getLexer().isNot(AsmToken::EndOfStatement))
1631 return TokError("unexpected token in '.fill' directive");
1635 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1636 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1638 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1639 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1644 /// ParseDirectiveOrg
1645 /// ::= .org expression [ , expression ]
1646 bool AsmParser::ParseDirectiveOrg() {
1647 CheckForValidSection();
1649 const MCExpr *Offset;
1650 if (ParseExpression(Offset))
1653 // Parse optional fill expression.
1654 int64_t FillExpr = 0;
1655 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1656 if (getLexer().isNot(AsmToken::Comma))
1657 return TokError("unexpected token in '.org' directive");
1660 if (ParseAbsoluteExpression(FillExpr))
1663 if (getLexer().isNot(AsmToken::EndOfStatement))
1664 return TokError("unexpected token in '.org' directive");
1669 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1670 // has to be relative to the current section.
1671 getStreamer().EmitValueToOffset(Offset, FillExpr);
1676 /// ParseDirectiveAlign
1677 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1678 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1679 CheckForValidSection();
1681 SMLoc AlignmentLoc = getLexer().getLoc();
1683 if (ParseAbsoluteExpression(Alignment))
1687 bool HasFillExpr = false;
1688 int64_t FillExpr = 0;
1689 int64_t MaxBytesToFill = 0;
1690 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1691 if (getLexer().isNot(AsmToken::Comma))
1692 return TokError("unexpected token in directive");
1695 // The fill expression can be omitted while specifying a maximum number of
1696 // alignment bytes, e.g:
1698 if (getLexer().isNot(AsmToken::Comma)) {
1700 if (ParseAbsoluteExpression(FillExpr))
1704 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1705 if (getLexer().isNot(AsmToken::Comma))
1706 return TokError("unexpected token in directive");
1709 MaxBytesLoc = getLexer().getLoc();
1710 if (ParseAbsoluteExpression(MaxBytesToFill))
1713 if (getLexer().isNot(AsmToken::EndOfStatement))
1714 return TokError("unexpected token in directive");
1723 // Compute alignment in bytes.
1725 // FIXME: Diagnose overflow.
1726 if (Alignment >= 32) {
1727 Error(AlignmentLoc, "invalid alignment value");
1731 Alignment = 1ULL << Alignment;
1734 // Diagnose non-sensical max bytes to align.
1735 if (MaxBytesLoc.isValid()) {
1736 if (MaxBytesToFill < 1) {
1737 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1738 "many bytes, ignoring maximum bytes expression");
1742 if (MaxBytesToFill >= Alignment) {
1743 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1749 // Check whether we should use optimal code alignment for this .align
1751 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1752 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1753 ValueSize == 1 && UseCodeAlign) {
1754 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1756 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1757 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1764 /// ParseDirectiveSymbolAttribute
1765 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1766 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1767 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1771 if (ParseIdentifier(Name))
1772 return TokError("expected identifier in directive");
1774 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1776 getStreamer().EmitSymbolAttribute(Sym, Attr);
1778 if (getLexer().is(AsmToken::EndOfStatement))
1781 if (getLexer().isNot(AsmToken::Comma))
1782 return TokError("unexpected token in directive");
1791 /// ParseDirectiveComm
1792 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1793 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1794 CheckForValidSection();
1796 SMLoc IDLoc = getLexer().getLoc();
1798 if (ParseIdentifier(Name))
1799 return TokError("expected identifier in directive");
1801 // Handle the identifier as the key symbol.
1802 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1804 if (getLexer().isNot(AsmToken::Comma))
1805 return TokError("unexpected token in directive");
1809 SMLoc SizeLoc = getLexer().getLoc();
1810 if (ParseAbsoluteExpression(Size))
1813 int64_t Pow2Alignment = 0;
1814 SMLoc Pow2AlignmentLoc;
1815 if (getLexer().is(AsmToken::Comma)) {
1817 Pow2AlignmentLoc = getLexer().getLoc();
1818 if (ParseAbsoluteExpression(Pow2Alignment))
1821 // If this target takes alignments in bytes (not log) validate and convert.
1822 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1823 if (!isPowerOf2_64(Pow2Alignment))
1824 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1825 Pow2Alignment = Log2_64(Pow2Alignment);
1829 if (getLexer().isNot(AsmToken::EndOfStatement))
1830 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1834 // NOTE: a size of zero for a .comm should create a undefined symbol
1835 // but a size of .lcomm creates a bss symbol of size zero.
1837 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1838 "be less than zero");
1840 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1841 // may internally end up wanting an alignment in bytes.
1842 // FIXME: Diagnose overflow.
1843 if (Pow2Alignment < 0)
1844 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1845 "alignment, can't be less than zero");
1847 if (!Sym->isUndefined())
1848 return Error(IDLoc, "invalid symbol redefinition");
1850 // '.lcomm' is equivalent to '.zerofill'.
1851 // Create the Symbol as a common or local common with Size and Pow2Alignment
1853 getStreamer().EmitZerofill(Ctx.getMachOSection(
1854 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1855 0, SectionKind::getBSS()),
1856 Sym, Size, 1 << Pow2Alignment);
1860 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1864 /// ParseDirectiveAbort
1865 /// ::= .abort [... message ...]
1866 bool AsmParser::ParseDirectiveAbort() {
1867 // FIXME: Use loc from directive.
1868 SMLoc Loc = getLexer().getLoc();
1870 StringRef Str = ParseStringToEndOfStatement();
1871 if (getLexer().isNot(AsmToken::EndOfStatement))
1872 return TokError("unexpected token in '.abort' directive");
1877 Error(Loc, ".abort detected. Assembly stopping.");
1879 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1880 // FIXME: Actually abort assembly here.
1885 /// ParseDirectiveInclude
1886 /// ::= .include "filename"
1887 bool AsmParser::ParseDirectiveInclude() {
1888 if (getLexer().isNot(AsmToken::String))
1889 return TokError("expected string in '.include' directive");
1891 std::string Filename = getTok().getString();
1892 SMLoc IncludeLoc = getLexer().getLoc();
1895 if (getLexer().isNot(AsmToken::EndOfStatement))
1896 return TokError("unexpected token in '.include' directive");
1898 // Strip the quotes.
1899 Filename = Filename.substr(1, Filename.size()-2);
1901 // Attempt to switch the lexer to the included file before consuming the end
1902 // of statement to avoid losing it when we switch.
1903 if (EnterIncludeFile(Filename)) {
1904 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1911 /// ParseDirectiveIf
1912 /// ::= .if expression
1913 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1914 TheCondStack.push_back(TheCondState);
1915 TheCondState.TheCond = AsmCond::IfCond;
1916 if(TheCondState.Ignore) {
1917 EatToEndOfStatement();
1921 if (ParseAbsoluteExpression(ExprValue))
1924 if (getLexer().isNot(AsmToken::EndOfStatement))
1925 return TokError("unexpected token in '.if' directive");
1929 TheCondState.CondMet = ExprValue;
1930 TheCondState.Ignore = !TheCondState.CondMet;
1936 /// ParseDirectiveElseIf
1937 /// ::= .elseif expression
1938 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1939 if (TheCondState.TheCond != AsmCond::IfCond &&
1940 TheCondState.TheCond != AsmCond::ElseIfCond)
1941 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1943 TheCondState.TheCond = AsmCond::ElseIfCond;
1945 bool LastIgnoreState = false;
1946 if (!TheCondStack.empty())
1947 LastIgnoreState = TheCondStack.back().Ignore;
1948 if (LastIgnoreState || TheCondState.CondMet) {
1949 TheCondState.Ignore = true;
1950 EatToEndOfStatement();
1954 if (ParseAbsoluteExpression(ExprValue))
1957 if (getLexer().isNot(AsmToken::EndOfStatement))
1958 return TokError("unexpected token in '.elseif' directive");
1961 TheCondState.CondMet = ExprValue;
1962 TheCondState.Ignore = !TheCondState.CondMet;
1968 /// ParseDirectiveElse
1970 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1971 if (getLexer().isNot(AsmToken::EndOfStatement))
1972 return TokError("unexpected token in '.else' directive");
1976 if (TheCondState.TheCond != AsmCond::IfCond &&
1977 TheCondState.TheCond != AsmCond::ElseIfCond)
1978 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1980 TheCondState.TheCond = AsmCond::ElseCond;
1981 bool LastIgnoreState = false;
1982 if (!TheCondStack.empty())
1983 LastIgnoreState = TheCondStack.back().Ignore;
1984 if (LastIgnoreState || TheCondState.CondMet)
1985 TheCondState.Ignore = true;
1987 TheCondState.Ignore = false;
1992 /// ParseDirectiveEndIf
1994 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1995 if (getLexer().isNot(AsmToken::EndOfStatement))
1996 return TokError("unexpected token in '.endif' directive");
2000 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2001 TheCondStack.empty())
2002 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2004 if (!TheCondStack.empty()) {
2005 TheCondState = TheCondStack.back();
2006 TheCondStack.pop_back();
2012 /// ParseDirectiveFile
2013 /// ::= .file [number] string
2014 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2015 // FIXME: I'm not sure what this is.
2016 int64_t FileNumber = -1;
2017 SMLoc FileNumberLoc = getLexer().getLoc();
2018 if (getLexer().is(AsmToken::Integer)) {
2019 FileNumber = getTok().getIntVal();
2023 return TokError("file number less than one");
2026 if (getLexer().isNot(AsmToken::String))
2027 return TokError("unexpected token in '.file' directive");
2029 StringRef Filename = getTok().getString();
2030 Filename = Filename.substr(1, Filename.size()-2);
2033 if (getLexer().isNot(AsmToken::EndOfStatement))
2034 return TokError("unexpected token in '.file' directive");
2036 if (FileNumber == -1)
2037 getStreamer().EmitFileDirective(Filename);
2039 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2040 Error(FileNumberLoc, "file number already allocated");
2046 /// ParseDirectiveLine
2047 /// ::= .line [number]
2048 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2049 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2050 if (getLexer().isNot(AsmToken::Integer))
2051 return TokError("unexpected token in '.line' directive");
2053 int64_t LineNumber = getTok().getIntVal();
2057 // FIXME: Do something with the .line.
2060 if (getLexer().isNot(AsmToken::EndOfStatement))
2061 return TokError("unexpected token in '.line' directive");
2067 /// ParseDirectiveLoc
2068 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2069 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2070 /// The first number is a file number, must have been previously assigned with
2071 /// a .file directive, the second number is the line number and optionally the
2072 /// third number is a column position (zero if not specified). The remaining
2073 /// optional items are .loc sub-directives.
2074 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2076 if (getLexer().isNot(AsmToken::Integer))
2077 return TokError("unexpected token in '.loc' directive");
2078 int64_t FileNumber = getTok().getIntVal();
2080 return TokError("file number less than one in '.loc' directive");
2081 if (!getContext().isValidDwarfFileNumber(FileNumber))
2082 return TokError("unassigned file number in '.loc' directive");
2085 int64_t LineNumber = 0;
2086 if (getLexer().is(AsmToken::Integer)) {
2087 LineNumber = getTok().getIntVal();
2089 return TokError("line number less than one in '.loc' directive");
2093 int64_t ColumnPos = 0;
2094 if (getLexer().is(AsmToken::Integer)) {
2095 ColumnPos = getTok().getIntVal();
2097 return TokError("column position less than zero in '.loc' directive");
2101 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2103 int64_t Discriminator = 0;
2104 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2106 if (getLexer().is(AsmToken::EndOfStatement))
2110 SMLoc Loc = getTok().getLoc();
2111 if (getParser().ParseIdentifier(Name))
2112 return TokError("unexpected token in '.loc' directive");
2114 if (Name == "basic_block")
2115 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2116 else if (Name == "prologue_end")
2117 Flags |= DWARF2_FLAG_PROLOGUE_END;
2118 else if (Name == "epilogue_begin")
2119 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2120 else if (Name == "is_stmt") {
2121 SMLoc Loc = getTok().getLoc();
2122 const MCExpr *Value;
2123 if (getParser().ParseExpression(Value))
2125 // The expression must be the constant 0 or 1.
2126 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2127 int Value = MCE->getValue();
2129 Flags &= ~DWARF2_FLAG_IS_STMT;
2130 else if (Value == 1)
2131 Flags |= DWARF2_FLAG_IS_STMT;
2133 return Error(Loc, "is_stmt value not 0 or 1");
2136 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2139 else if (Name == "isa") {
2140 SMLoc Loc = getTok().getLoc();
2141 const MCExpr *Value;
2142 if (getParser().ParseExpression(Value))
2144 // The expression must be a constant greater or equal to 0.
2145 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2146 int Value = MCE->getValue();
2148 return Error(Loc, "isa number less than zero");
2152 return Error(Loc, "isa number not a constant value");
2155 else if (Name == "discriminator") {
2156 if (getParser().ParseAbsoluteExpression(Discriminator))
2160 return Error(Loc, "unknown sub-directive in '.loc' directive");
2163 if (getLexer().is(AsmToken::EndOfStatement))
2168 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2169 Isa, Discriminator);
2174 /// ParseDirectiveStabs
2175 /// ::= .stabs string, number, number, number
2176 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2177 SMLoc DirectiveLoc) {
2178 return TokError("unsupported directive '" + Directive + "'");
2181 /// ParseDirectiveCFIStartProc
2182 /// ::= .cfi_startproc
2183 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2184 SMLoc DirectiveLoc) {
2185 return getStreamer().EmitCFIStartProc();
2188 /// ParseDirectiveCFIEndProc
2189 /// ::= .cfi_endproc
2190 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2191 return getStreamer().EmitCFIEndProc();
2194 /// ParseRegisterOrRegisterNumber - parse register name or number.
2195 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2196 SMLoc DirectiveLoc) {
2199 if (getLexer().is(AsmToken::Percent)) {
2200 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2203 Register = getContext().getTargetAsmInfo().getDwarfRegNum(RegNo, true);
2205 return getParser().ParseAbsoluteExpression(Register);
2210 /// ParseDirectiveCFIDefCfa
2211 /// ::= .cfi_def_cfa register, offset
2212 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2213 SMLoc DirectiveLoc) {
2214 int64_t Register = 0;
2215 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2218 if (getLexer().isNot(AsmToken::Comma))
2219 return TokError("unexpected token in directive");
2223 if (getParser().ParseAbsoluteExpression(Offset))
2226 return getStreamer().EmitCFIDefCfa(Register, Offset);
2229 /// ParseDirectiveCFIDefCfaOffset
2230 /// ::= .cfi_def_cfa_offset offset
2231 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2232 SMLoc DirectiveLoc) {
2234 if (getParser().ParseAbsoluteExpression(Offset))
2237 return getStreamer().EmitCFIDefCfaOffset(Offset);
2240 /// ParseDirectiveCFIDefCfaRegister
2241 /// ::= .cfi_def_cfa_register register
2242 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2243 SMLoc DirectiveLoc) {
2244 int64_t Register = 0;
2245 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2248 return getStreamer().EmitCFIDefCfaRegister(Register);
2251 /// ParseDirectiveCFIOffset
2252 /// ::= .cfi_off register, offset
2253 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2254 int64_t Register = 0;
2257 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2260 if (getLexer().isNot(AsmToken::Comma))
2261 return TokError("unexpected token in directive");
2264 if (getParser().ParseAbsoluteExpression(Offset))
2267 return getStreamer().EmitCFIOffset(Register, Offset);
2270 static bool isValidEncoding(int64_t Encoding) {
2271 if (Encoding & ~0xff)
2274 if (Encoding == dwarf::DW_EH_PE_omit)
2277 const unsigned Format = Encoding & 0xf;
2278 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2279 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2280 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2281 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2284 const unsigned Application = Encoding & 0x70;
2285 if (Application != dwarf::DW_EH_PE_absptr &&
2286 Application != dwarf::DW_EH_PE_pcrel)
2292 /// ParseDirectiveCFIPersonalityOrLsda
2293 /// ::= .cfi_personality encoding, [symbol_name]
2294 /// ::= .cfi_lsda encoding, [symbol_name]
2295 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2296 SMLoc DirectiveLoc) {
2297 int64_t Encoding = 0;
2298 if (getParser().ParseAbsoluteExpression(Encoding))
2300 if (Encoding == dwarf::DW_EH_PE_omit)
2303 if (!isValidEncoding(Encoding))
2304 return TokError("unsupported encoding.");
2306 if (getLexer().isNot(AsmToken::Comma))
2307 return TokError("unexpected token in directive");
2311 if (getParser().ParseIdentifier(Name))
2312 return TokError("expected identifier in directive");
2314 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2316 if (IDVal == ".cfi_personality")
2317 return getStreamer().EmitCFIPersonality(Sym, Encoding);
2319 assert(IDVal == ".cfi_lsda");
2320 return getStreamer().EmitCFILsda(Sym, Encoding);
2324 /// ParseDirectiveCFIRememberState
2325 /// ::= .cfi_remember_state
2326 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2327 SMLoc DirectiveLoc) {
2328 return getStreamer().EmitCFIRememberState();
2331 /// ParseDirectiveCFIRestoreState
2332 /// ::= .cfi_remember_state
2333 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2334 SMLoc DirectiveLoc) {
2335 return getStreamer().EmitCFIRestoreState();
2338 /// ParseDirectiveMacrosOnOff
2341 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2342 SMLoc DirectiveLoc) {
2343 if (getLexer().isNot(AsmToken::EndOfStatement))
2344 return Error(getLexer().getLoc(),
2345 "unexpected token in '" + Directive + "' directive");
2347 getParser().MacrosEnabled = Directive == ".macros_on";
2352 /// ParseDirectiveMacro
2354 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2355 SMLoc DirectiveLoc) {
2357 if (getParser().ParseIdentifier(Name))
2358 return TokError("expected identifier in directive");
2360 if (getLexer().isNot(AsmToken::EndOfStatement))
2361 return TokError("unexpected token in '.macro' directive");
2363 // Eat the end of statement.
2366 AsmToken EndToken, StartToken = getTok();
2368 // Lex the macro definition.
2370 // Check whether we have reached the end of the file.
2371 if (getLexer().is(AsmToken::Eof))
2372 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2374 // Otherwise, check whether we have reach the .endmacro.
2375 if (getLexer().is(AsmToken::Identifier) &&
2376 (getTok().getIdentifier() == ".endm" ||
2377 getTok().getIdentifier() == ".endmacro")) {
2378 EndToken = getTok();
2380 if (getLexer().isNot(AsmToken::EndOfStatement))
2381 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2386 // Otherwise, scan til the end of the statement.
2387 getParser().EatToEndOfStatement();
2390 if (getParser().MacroMap.lookup(Name)) {
2391 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2394 const char *BodyStart = StartToken.getLoc().getPointer();
2395 const char *BodyEnd = EndToken.getLoc().getPointer();
2396 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2397 getParser().MacroMap[Name] = new Macro(Name, Body);
2401 /// ParseDirectiveEndMacro
2404 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2405 SMLoc DirectiveLoc) {
2406 if (getLexer().isNot(AsmToken::EndOfStatement))
2407 return TokError("unexpected token in '" + Directive + "' directive");
2409 // If we are inside a macro instantiation, terminate the current
2411 if (!getParser().ActiveMacros.empty()) {
2412 getParser().HandleMacroExit();
2416 // Otherwise, this .endmacro is a stray entry in the file; well formed
2417 // .endmacro directives are handled during the macro definition parsing.
2418 return TokError("unexpected '" + Directive + "' in file, "
2419 "no current macro definition");
2422 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2423 getParser().CheckForValidSection();
2425 const MCExpr *Value;
2427 if (getParser().ParseExpression(Value))
2430 if (getLexer().isNot(AsmToken::EndOfStatement))
2431 return TokError("unexpected token in directive");
2433 if (DirName[1] == 's')
2434 getStreamer().EmitSLEB128Value(Value);
2436 getStreamer().EmitULEB128Value(Value);
2442 /// \brief Create an MCAsmParser instance.
2443 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2444 MCContext &C, MCStreamer &Out,
2445 const MCAsmInfo &MAI) {
2446 return new AsmParser(T, SM, C, Out, MAI);