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);
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); // ".set" or ".equ"
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 int64_t IntVal = RealVal.bitcastToAPInt().getSExtValue();
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);
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);
963 if (IDVal == ".ascii")
964 return ParseDirectiveAscii(IDVal, false);
965 if (IDVal == ".asciz" || IDVal == ".string")
966 return ParseDirectiveAscii(IDVal, true);
968 if (IDVal == ".byte")
969 return ParseDirectiveValue(1);
970 if (IDVal == ".short")
971 return ParseDirectiveValue(2);
972 if (IDVal == ".value")
973 return ParseDirectiveValue(2);
974 if (IDVal == ".2byte")
975 return ParseDirectiveValue(2);
976 if (IDVal == ".long")
977 return ParseDirectiveValue(4);
979 return ParseDirectiveValue(4);
980 if (IDVal == ".4byte")
981 return ParseDirectiveValue(4);
982 if (IDVal == ".quad")
983 return ParseDirectiveValue(8);
984 if (IDVal == ".8byte")
985 return ParseDirectiveValue(8);
986 if (IDVal == ".single")
987 return ParseDirectiveRealValue(APFloat::IEEEsingle);
988 if (IDVal == ".double")
989 return ParseDirectiveRealValue(APFloat::IEEEdouble);
991 if (IDVal == ".align") {
992 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
993 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
995 if (IDVal == ".align32") {
996 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
997 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
999 if (IDVal == ".balign")
1000 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1001 if (IDVal == ".balignw")
1002 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1003 if (IDVal == ".balignl")
1004 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1005 if (IDVal == ".p2align")
1006 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1007 if (IDVal == ".p2alignw")
1008 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1009 if (IDVal == ".p2alignl")
1010 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1012 if (IDVal == ".org")
1013 return ParseDirectiveOrg();
1015 if (IDVal == ".fill")
1016 return ParseDirectiveFill();
1017 if (IDVal == ".space")
1018 return ParseDirectiveSpace();
1019 if (IDVal == ".zero")
1020 return ParseDirectiveZero();
1022 // Symbol attribute directives
1024 if (IDVal == ".globl" || IDVal == ".global")
1025 return ParseDirectiveSymbolAttribute(MCSA_Global);
1026 // ELF only? Should it be here?
1027 if (IDVal == ".local")
1028 return ParseDirectiveSymbolAttribute(MCSA_Local);
1029 if (IDVal == ".hidden")
1030 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1031 if (IDVal == ".indirect_symbol")
1032 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1033 if (IDVal == ".internal")
1034 return ParseDirectiveSymbolAttribute(MCSA_Internal);
1035 if (IDVal == ".lazy_reference")
1036 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1037 if (IDVal == ".no_dead_strip")
1038 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1039 if (IDVal == ".symbol_resolver")
1040 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1041 if (IDVal == ".private_extern")
1042 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1043 if (IDVal == ".protected")
1044 return ParseDirectiveSymbolAttribute(MCSA_Protected);
1045 if (IDVal == ".reference")
1046 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1047 if (IDVal == ".weak")
1048 return ParseDirectiveSymbolAttribute(MCSA_Weak);
1049 if (IDVal == ".weak_definition")
1050 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1051 if (IDVal == ".weak_reference")
1052 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1053 if (IDVal == ".weak_def_can_be_hidden")
1054 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1056 if (IDVal == ".comm")
1057 return ParseDirectiveComm(/*IsLocal=*/false);
1058 if (IDVal == ".lcomm")
1059 return ParseDirectiveComm(/*IsLocal=*/true);
1061 if (IDVal == ".abort")
1062 return ParseDirectiveAbort();
1063 if (IDVal == ".include")
1064 return ParseDirectiveInclude();
1066 // Look up the handler in the handler table.
1067 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1068 DirectiveMap.lookup(IDVal);
1070 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1072 // Target hook for parsing target specific directives.
1073 if (!getTargetParser().ParseDirective(ID))
1076 Warning(IDLoc, "ignoring directive for now");
1077 EatToEndOfStatement();
1081 CheckForValidSection();
1083 // Canonicalize the opcode to lower case.
1084 SmallString<128> Opcode;
1085 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1086 Opcode.push_back(tolower(IDVal[i]));
1088 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1089 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1092 // Dump the parsed representation, if requested.
1093 if (getShowParsedOperands()) {
1094 SmallString<256> Str;
1095 raw_svector_ostream OS(Str);
1096 OS << "parsed instruction: [";
1097 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1100 ParsedOperands[i]->dump(OS);
1104 PrintMessage(IDLoc, OS.str(), "note");
1107 // If parsing succeeded, match the instruction.
1109 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1112 // Free any parsed operands.
1113 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1114 delete ParsedOperands[i];
1116 // Don't skip the rest of the line, the instruction parser is responsible for
1121 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1122 const std::vector<std::vector<AsmToken> > &A)
1123 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1125 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1126 // to hold the macro body with substitutions.
1127 SmallString<256> Buf;
1128 raw_svector_ostream OS(Buf);
1130 StringRef Body = M->Body;
1131 while (!Body.empty()) {
1132 // Scan for the next substitution.
1133 std::size_t End = Body.size(), Pos = 0;
1134 for (; Pos != End; ++Pos) {
1135 // Check for a substitution or escape.
1136 if (Body[Pos] != '$' || Pos + 1 == End)
1139 char Next = Body[Pos + 1];
1140 if (Next == '$' || Next == 'n' || isdigit(Next))
1145 OS << Body.slice(0, Pos);
1147 // Check if we reached the end.
1151 switch (Body[Pos+1]) {
1157 // $n => number of arguments
1162 // $[0-9] => argument
1164 // Missing arguments are ignored.
1165 unsigned Index = Body[Pos+1] - '0';
1166 if (Index >= A.size())
1169 // Otherwise substitute with the token values, with spaces eliminated.
1170 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1171 ie = A[Index].end(); it != ie; ++it)
1172 OS << it->getString();
1177 // Update the scan point.
1178 Body = Body.substr(Pos + 2);
1181 // We include the .endmacro in the buffer as our queue to exit the macro
1183 OS << ".endmacro\n";
1185 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1188 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1190 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1191 // this, although we should protect against infinite loops.
1192 if (ActiveMacros.size() == 20)
1193 return TokError("macros cannot be nested more than 20 levels deep");
1195 // Parse the macro instantiation arguments.
1196 std::vector<std::vector<AsmToken> > MacroArguments;
1197 MacroArguments.push_back(std::vector<AsmToken>());
1198 unsigned ParenLevel = 0;
1200 if (Lexer.is(AsmToken::Eof))
1201 return TokError("unexpected token in macro instantiation");
1202 if (Lexer.is(AsmToken::EndOfStatement))
1205 // If we aren't inside parentheses and this is a comma, start a new token
1207 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1208 MacroArguments.push_back(std::vector<AsmToken>());
1210 // Adjust the current parentheses level.
1211 if (Lexer.is(AsmToken::LParen))
1213 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1216 // Append the token to the current argument list.
1217 MacroArguments.back().push_back(getTok());
1222 // Create the macro instantiation object and add to the current macro
1223 // instantiation stack.
1224 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1227 ActiveMacros.push_back(MI);
1229 // Jump to the macro instantiation and prime the lexer.
1230 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1231 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1237 void AsmParser::HandleMacroExit() {
1238 // Jump to the EndOfStatement we should return to, and consume it.
1239 JumpToLoc(ActiveMacros.back()->ExitLoc);
1242 // Pop the instantiation entry.
1243 delete ActiveMacros.back();
1244 ActiveMacros.pop_back();
1247 static void MarkUsed(const MCExpr *Value) {
1248 switch (Value->getKind()) {
1249 case MCExpr::Binary:
1250 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1251 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1253 case MCExpr::Target:
1254 case MCExpr::Constant:
1256 case MCExpr::SymbolRef: {
1257 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1261 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1266 bool AsmParser::ParseAssignment(StringRef Name) {
1267 // FIXME: Use better location, we should use proper tokens.
1268 SMLoc EqualLoc = Lexer.getLoc();
1270 const MCExpr *Value;
1271 if (ParseExpression(Value))
1276 if (Lexer.isNot(AsmToken::EndOfStatement))
1277 return TokError("unexpected token in assignment");
1279 // Eat the end of statement marker.
1282 // Validate that the LHS is allowed to be a variable (either it has not been
1283 // used as a symbol, or it is an absolute symbol).
1284 MCSymbol *Sym = getContext().LookupSymbol(Name);
1286 // Diagnose assignment to a label.
1288 // FIXME: Diagnostics. Note the location of the definition as a label.
1289 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1290 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1291 ; // Allow redefinitions of undefined symbols only used in directives.
1292 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1293 return Error(EqualLoc, "redefinition of '" + Name + "'");
1294 else if (!Sym->isVariable())
1295 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1296 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1297 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1300 // Don't count these checks as uses.
1301 Sym->setUsed(false);
1303 Sym = getContext().GetOrCreateSymbol(Name);
1305 // FIXME: Handle '.'.
1307 // Do the assignment.
1308 Out.EmitAssignment(Sym, Value);
1313 /// ParseIdentifier:
1316 bool AsmParser::ParseIdentifier(StringRef &Res) {
1317 // The assembler has relaxed rules for accepting identifiers, in particular we
1318 // allow things like '.globl $foo', which would normally be separate
1319 // tokens. At this level, we have already lexed so we cannot (currently)
1320 // handle this as a context dependent token, instead we detect adjacent tokens
1321 // and return the combined identifier.
1322 if (Lexer.is(AsmToken::Dollar)) {
1323 SMLoc DollarLoc = getLexer().getLoc();
1325 // Consume the dollar sign, and check for a following identifier.
1327 if (Lexer.isNot(AsmToken::Identifier))
1330 // We have a '$' followed by an identifier, make sure they are adjacent.
1331 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1334 // Construct the joined identifier and consume the token.
1335 Res = StringRef(DollarLoc.getPointer(),
1336 getTok().getIdentifier().size() + 1);
1341 if (Lexer.isNot(AsmToken::Identifier) &&
1342 Lexer.isNot(AsmToken::String))
1345 Res = getTok().getIdentifier();
1347 Lex(); // Consume the identifier token.
1352 /// ParseDirectiveSet:
1353 /// ::= .set identifier ',' expression
1354 bool AsmParser::ParseDirectiveSet(StringRef IDVal) {
1357 if (ParseIdentifier(Name))
1358 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1360 if (getLexer().isNot(AsmToken::Comma))
1361 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1364 return ParseAssignment(Name);
1367 bool AsmParser::ParseEscapedString(std::string &Data) {
1368 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1371 StringRef Str = getTok().getStringContents();
1372 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1373 if (Str[i] != '\\') {
1378 // Recognize escaped characters. Note that this escape semantics currently
1379 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1382 return TokError("unexpected backslash at end of string");
1384 // Recognize octal sequences.
1385 if ((unsigned) (Str[i] - '0') <= 7) {
1386 // Consume up to three octal characters.
1387 unsigned Value = Str[i] - '0';
1389 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1391 Value = Value * 8 + (Str[i] - '0');
1393 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1395 Value = Value * 8 + (Str[i] - '0');
1400 return TokError("invalid octal escape sequence (out of range)");
1402 Data += (unsigned char) Value;
1406 // Otherwise recognize individual escapes.
1409 // Just reject invalid escape sequences for now.
1410 return TokError("invalid escape sequence (unrecognized character)");
1412 case 'b': Data += '\b'; break;
1413 case 'f': Data += '\f'; break;
1414 case 'n': Data += '\n'; break;
1415 case 'r': Data += '\r'; break;
1416 case 't': Data += '\t'; break;
1417 case '"': Data += '"'; break;
1418 case '\\': Data += '\\'; break;
1425 /// ParseDirectiveAscii:
1426 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1427 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1428 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1429 CheckForValidSection();
1432 if (getLexer().isNot(AsmToken::String))
1433 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1436 if (ParseEscapedString(Data))
1439 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1441 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1445 if (getLexer().is(AsmToken::EndOfStatement))
1448 if (getLexer().isNot(AsmToken::Comma))
1449 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1458 /// ParseDirectiveValue
1459 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1460 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1461 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1462 CheckForValidSection();
1465 const MCExpr *Value;
1466 if (ParseExpression(Value))
1469 // Special case constant expressions to match code generator.
1470 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1471 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1473 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1475 if (getLexer().is(AsmToken::EndOfStatement))
1478 // FIXME: Improve diagnostic.
1479 if (getLexer().isNot(AsmToken::Comma))
1480 return TokError("unexpected token in directive");
1489 /// ParseDirectiveRealValue
1490 /// ::= (.single | .double) [ expression (, expression)* ]
1491 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1492 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1493 CheckForValidSection();
1496 // We don't truly support arithmetic on floating point expressions, so we
1497 // have to manually parse unary prefixes.
1499 if (getLexer().is(AsmToken::Minus)) {
1502 } else if (getLexer().is(AsmToken::Plus))
1505 if (getLexer().isNot(AsmToken::Integer) &&
1506 getLexer().isNot(AsmToken::Real))
1507 return TokError("unexpected token in directive");
1509 // Convert to an APFloat.
1510 APFloat Value(Semantics);
1511 if (Value.convertFromString(getTok().getString(),
1512 APFloat::rmNearestTiesToEven) ==
1513 APFloat::opInvalidOp)
1514 return TokError("invalid floating point literal");
1518 // Consume the numeric token.
1521 // Emit the value as an integer.
1522 APInt AsInt = Value.bitcastToAPInt();
1523 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1524 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1526 if (getLexer().is(AsmToken::EndOfStatement))
1529 if (getLexer().isNot(AsmToken::Comma))
1530 return TokError("unexpected token in directive");
1539 /// ParseDirectiveSpace
1540 /// ::= .space expression [ , expression ]
1541 bool AsmParser::ParseDirectiveSpace() {
1542 CheckForValidSection();
1545 if (ParseAbsoluteExpression(NumBytes))
1548 int64_t FillExpr = 0;
1549 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1550 if (getLexer().isNot(AsmToken::Comma))
1551 return TokError("unexpected token in '.space' directive");
1554 if (ParseAbsoluteExpression(FillExpr))
1557 if (getLexer().isNot(AsmToken::EndOfStatement))
1558 return TokError("unexpected token in '.space' directive");
1564 return TokError("invalid number of bytes in '.space' directive");
1566 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1567 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1572 /// ParseDirectiveZero
1573 /// ::= .zero expression
1574 bool AsmParser::ParseDirectiveZero() {
1575 CheckForValidSection();
1578 if (ParseAbsoluteExpression(NumBytes))
1582 if (getLexer().is(AsmToken::Comma)) {
1584 if (ParseAbsoluteExpression(Val))
1588 if (getLexer().isNot(AsmToken::EndOfStatement))
1589 return TokError("unexpected token in '.zero' directive");
1593 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1598 /// ParseDirectiveFill
1599 /// ::= .fill expression , expression , expression
1600 bool AsmParser::ParseDirectiveFill() {
1601 CheckForValidSection();
1604 if (ParseAbsoluteExpression(NumValues))
1607 if (getLexer().isNot(AsmToken::Comma))
1608 return TokError("unexpected token in '.fill' directive");
1612 if (ParseAbsoluteExpression(FillSize))
1615 if (getLexer().isNot(AsmToken::Comma))
1616 return TokError("unexpected token in '.fill' directive");
1620 if (ParseAbsoluteExpression(FillExpr))
1623 if (getLexer().isNot(AsmToken::EndOfStatement))
1624 return TokError("unexpected token in '.fill' directive");
1628 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1629 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1631 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1632 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1637 /// ParseDirectiveOrg
1638 /// ::= .org expression [ , expression ]
1639 bool AsmParser::ParseDirectiveOrg() {
1640 CheckForValidSection();
1642 const MCExpr *Offset;
1643 if (ParseExpression(Offset))
1646 // Parse optional fill expression.
1647 int64_t FillExpr = 0;
1648 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1649 if (getLexer().isNot(AsmToken::Comma))
1650 return TokError("unexpected token in '.org' directive");
1653 if (ParseAbsoluteExpression(FillExpr))
1656 if (getLexer().isNot(AsmToken::EndOfStatement))
1657 return TokError("unexpected token in '.org' directive");
1662 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1663 // has to be relative to the current section.
1664 getStreamer().EmitValueToOffset(Offset, FillExpr);
1669 /// ParseDirectiveAlign
1670 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1671 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1672 CheckForValidSection();
1674 SMLoc AlignmentLoc = getLexer().getLoc();
1676 if (ParseAbsoluteExpression(Alignment))
1680 bool HasFillExpr = false;
1681 int64_t FillExpr = 0;
1682 int64_t MaxBytesToFill = 0;
1683 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1684 if (getLexer().isNot(AsmToken::Comma))
1685 return TokError("unexpected token in directive");
1688 // The fill expression can be omitted while specifying a maximum number of
1689 // alignment bytes, e.g:
1691 if (getLexer().isNot(AsmToken::Comma)) {
1693 if (ParseAbsoluteExpression(FillExpr))
1697 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1698 if (getLexer().isNot(AsmToken::Comma))
1699 return TokError("unexpected token in directive");
1702 MaxBytesLoc = getLexer().getLoc();
1703 if (ParseAbsoluteExpression(MaxBytesToFill))
1706 if (getLexer().isNot(AsmToken::EndOfStatement))
1707 return TokError("unexpected token in directive");
1716 // Compute alignment in bytes.
1718 // FIXME: Diagnose overflow.
1719 if (Alignment >= 32) {
1720 Error(AlignmentLoc, "invalid alignment value");
1724 Alignment = 1ULL << Alignment;
1727 // Diagnose non-sensical max bytes to align.
1728 if (MaxBytesLoc.isValid()) {
1729 if (MaxBytesToFill < 1) {
1730 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1731 "many bytes, ignoring maximum bytes expression");
1735 if (MaxBytesToFill >= Alignment) {
1736 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1742 // Check whether we should use optimal code alignment for this .align
1744 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1745 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1746 ValueSize == 1 && UseCodeAlign) {
1747 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1749 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1750 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1757 /// ParseDirectiveSymbolAttribute
1758 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1759 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1760 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1764 if (ParseIdentifier(Name))
1765 return TokError("expected identifier in directive");
1767 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1769 getStreamer().EmitSymbolAttribute(Sym, Attr);
1771 if (getLexer().is(AsmToken::EndOfStatement))
1774 if (getLexer().isNot(AsmToken::Comma))
1775 return TokError("unexpected token in directive");
1784 /// ParseDirectiveComm
1785 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1786 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1787 CheckForValidSection();
1789 SMLoc IDLoc = getLexer().getLoc();
1791 if (ParseIdentifier(Name))
1792 return TokError("expected identifier in directive");
1794 // Handle the identifier as the key symbol.
1795 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1797 if (getLexer().isNot(AsmToken::Comma))
1798 return TokError("unexpected token in directive");
1802 SMLoc SizeLoc = getLexer().getLoc();
1803 if (ParseAbsoluteExpression(Size))
1806 int64_t Pow2Alignment = 0;
1807 SMLoc Pow2AlignmentLoc;
1808 if (getLexer().is(AsmToken::Comma)) {
1810 Pow2AlignmentLoc = getLexer().getLoc();
1811 if (ParseAbsoluteExpression(Pow2Alignment))
1814 // If this target takes alignments in bytes (not log) validate and convert.
1815 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1816 if (!isPowerOf2_64(Pow2Alignment))
1817 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1818 Pow2Alignment = Log2_64(Pow2Alignment);
1822 if (getLexer().isNot(AsmToken::EndOfStatement))
1823 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1827 // NOTE: a size of zero for a .comm should create a undefined symbol
1828 // but a size of .lcomm creates a bss symbol of size zero.
1830 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1831 "be less than zero");
1833 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1834 // may internally end up wanting an alignment in bytes.
1835 // FIXME: Diagnose overflow.
1836 if (Pow2Alignment < 0)
1837 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1838 "alignment, can't be less than zero");
1840 if (!Sym->isUndefined())
1841 return Error(IDLoc, "invalid symbol redefinition");
1843 // '.lcomm' is equivalent to '.zerofill'.
1844 // Create the Symbol as a common or local common with Size and Pow2Alignment
1846 getStreamer().EmitZerofill(Ctx.getMachOSection(
1847 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1848 0, SectionKind::getBSS()),
1849 Sym, Size, 1 << Pow2Alignment);
1853 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1857 /// ParseDirectiveAbort
1858 /// ::= .abort [... message ...]
1859 bool AsmParser::ParseDirectiveAbort() {
1860 // FIXME: Use loc from directive.
1861 SMLoc Loc = getLexer().getLoc();
1863 StringRef Str = ParseStringToEndOfStatement();
1864 if (getLexer().isNot(AsmToken::EndOfStatement))
1865 return TokError("unexpected token in '.abort' directive");
1870 Error(Loc, ".abort detected. Assembly stopping.");
1872 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1873 // FIXME: Actually abort assembly here.
1878 /// ParseDirectiveInclude
1879 /// ::= .include "filename"
1880 bool AsmParser::ParseDirectiveInclude() {
1881 if (getLexer().isNot(AsmToken::String))
1882 return TokError("expected string in '.include' directive");
1884 std::string Filename = getTok().getString();
1885 SMLoc IncludeLoc = getLexer().getLoc();
1888 if (getLexer().isNot(AsmToken::EndOfStatement))
1889 return TokError("unexpected token in '.include' directive");
1891 // Strip the quotes.
1892 Filename = Filename.substr(1, Filename.size()-2);
1894 // Attempt to switch the lexer to the included file before consuming the end
1895 // of statement to avoid losing it when we switch.
1896 if (EnterIncludeFile(Filename)) {
1897 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1904 /// ParseDirectiveIf
1905 /// ::= .if expression
1906 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1907 TheCondStack.push_back(TheCondState);
1908 TheCondState.TheCond = AsmCond::IfCond;
1909 if(TheCondState.Ignore) {
1910 EatToEndOfStatement();
1914 if (ParseAbsoluteExpression(ExprValue))
1917 if (getLexer().isNot(AsmToken::EndOfStatement))
1918 return TokError("unexpected token in '.if' directive");
1922 TheCondState.CondMet = ExprValue;
1923 TheCondState.Ignore = !TheCondState.CondMet;
1929 /// ParseDirectiveElseIf
1930 /// ::= .elseif expression
1931 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1932 if (TheCondState.TheCond != AsmCond::IfCond &&
1933 TheCondState.TheCond != AsmCond::ElseIfCond)
1934 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1936 TheCondState.TheCond = AsmCond::ElseIfCond;
1938 bool LastIgnoreState = false;
1939 if (!TheCondStack.empty())
1940 LastIgnoreState = TheCondStack.back().Ignore;
1941 if (LastIgnoreState || TheCondState.CondMet) {
1942 TheCondState.Ignore = true;
1943 EatToEndOfStatement();
1947 if (ParseAbsoluteExpression(ExprValue))
1950 if (getLexer().isNot(AsmToken::EndOfStatement))
1951 return TokError("unexpected token in '.elseif' directive");
1954 TheCondState.CondMet = ExprValue;
1955 TheCondState.Ignore = !TheCondState.CondMet;
1961 /// ParseDirectiveElse
1963 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1964 if (getLexer().isNot(AsmToken::EndOfStatement))
1965 return TokError("unexpected token in '.else' directive");
1969 if (TheCondState.TheCond != AsmCond::IfCond &&
1970 TheCondState.TheCond != AsmCond::ElseIfCond)
1971 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1973 TheCondState.TheCond = AsmCond::ElseCond;
1974 bool LastIgnoreState = false;
1975 if (!TheCondStack.empty())
1976 LastIgnoreState = TheCondStack.back().Ignore;
1977 if (LastIgnoreState || TheCondState.CondMet)
1978 TheCondState.Ignore = true;
1980 TheCondState.Ignore = false;
1985 /// ParseDirectiveEndIf
1987 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1988 if (getLexer().isNot(AsmToken::EndOfStatement))
1989 return TokError("unexpected token in '.endif' directive");
1993 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1994 TheCondStack.empty())
1995 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1997 if (!TheCondStack.empty()) {
1998 TheCondState = TheCondStack.back();
1999 TheCondStack.pop_back();
2005 /// ParseDirectiveFile
2006 /// ::= .file [number] string
2007 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2008 // FIXME: I'm not sure what this is.
2009 int64_t FileNumber = -1;
2010 SMLoc FileNumberLoc = getLexer().getLoc();
2011 if (getLexer().is(AsmToken::Integer)) {
2012 FileNumber = getTok().getIntVal();
2016 return TokError("file number less than one");
2019 if (getLexer().isNot(AsmToken::String))
2020 return TokError("unexpected token in '.file' directive");
2022 StringRef Filename = getTok().getString();
2023 Filename = Filename.substr(1, Filename.size()-2);
2026 if (getLexer().isNot(AsmToken::EndOfStatement))
2027 return TokError("unexpected token in '.file' directive");
2029 if (FileNumber == -1)
2030 getStreamer().EmitFileDirective(Filename);
2032 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2033 Error(FileNumberLoc, "file number already allocated");
2039 /// ParseDirectiveLine
2040 /// ::= .line [number]
2041 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2042 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2043 if (getLexer().isNot(AsmToken::Integer))
2044 return TokError("unexpected token in '.line' directive");
2046 int64_t LineNumber = getTok().getIntVal();
2050 // FIXME: Do something with the .line.
2053 if (getLexer().isNot(AsmToken::EndOfStatement))
2054 return TokError("unexpected token in '.line' directive");
2060 /// ParseDirectiveLoc
2061 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2062 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2063 /// The first number is a file number, must have been previously assigned with
2064 /// a .file directive, the second number is the line number and optionally the
2065 /// third number is a column position (zero if not specified). The remaining
2066 /// optional items are .loc sub-directives.
2067 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2069 if (getLexer().isNot(AsmToken::Integer))
2070 return TokError("unexpected token in '.loc' directive");
2071 int64_t FileNumber = getTok().getIntVal();
2073 return TokError("file number less than one in '.loc' directive");
2074 if (!getContext().isValidDwarfFileNumber(FileNumber))
2075 return TokError("unassigned file number in '.loc' directive");
2078 int64_t LineNumber = 0;
2079 if (getLexer().is(AsmToken::Integer)) {
2080 LineNumber = getTok().getIntVal();
2082 return TokError("line number less than one in '.loc' directive");
2086 int64_t ColumnPos = 0;
2087 if (getLexer().is(AsmToken::Integer)) {
2088 ColumnPos = getTok().getIntVal();
2090 return TokError("column position less than zero in '.loc' directive");
2094 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2096 int64_t Discriminator = 0;
2097 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2099 if (getLexer().is(AsmToken::EndOfStatement))
2103 SMLoc Loc = getTok().getLoc();
2104 if (getParser().ParseIdentifier(Name))
2105 return TokError("unexpected token in '.loc' directive");
2107 if (Name == "basic_block")
2108 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2109 else if (Name == "prologue_end")
2110 Flags |= DWARF2_FLAG_PROLOGUE_END;
2111 else if (Name == "epilogue_begin")
2112 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2113 else if (Name == "is_stmt") {
2114 SMLoc Loc = getTok().getLoc();
2115 const MCExpr *Value;
2116 if (getParser().ParseExpression(Value))
2118 // The expression must be the constant 0 or 1.
2119 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2120 int Value = MCE->getValue();
2122 Flags &= ~DWARF2_FLAG_IS_STMT;
2123 else if (Value == 1)
2124 Flags |= DWARF2_FLAG_IS_STMT;
2126 return Error(Loc, "is_stmt value not 0 or 1");
2129 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2132 else if (Name == "isa") {
2133 SMLoc Loc = getTok().getLoc();
2134 const MCExpr *Value;
2135 if (getParser().ParseExpression(Value))
2137 // The expression must be a constant greater or equal to 0.
2138 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2139 int Value = MCE->getValue();
2141 return Error(Loc, "isa number less than zero");
2145 return Error(Loc, "isa number not a constant value");
2148 else if (Name == "discriminator") {
2149 if (getParser().ParseAbsoluteExpression(Discriminator))
2153 return Error(Loc, "unknown sub-directive in '.loc' directive");
2156 if (getLexer().is(AsmToken::EndOfStatement))
2161 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2162 Isa, Discriminator);
2167 /// ParseDirectiveStabs
2168 /// ::= .stabs string, number, number, number
2169 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2170 SMLoc DirectiveLoc) {
2171 return TokError("unsupported directive '" + Directive + "'");
2174 /// ParseDirectiveCFIStartProc
2175 /// ::= .cfi_startproc
2176 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2177 SMLoc DirectiveLoc) {
2178 return getStreamer().EmitCFIStartProc();
2181 /// ParseDirectiveCFIEndProc
2182 /// ::= .cfi_endproc
2183 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2184 return getStreamer().EmitCFIEndProc();
2187 /// ParseRegisterOrRegisterNumber - parse register name or number.
2188 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2189 SMLoc DirectiveLoc) {
2192 if (getLexer().is(AsmToken::Percent)) {
2193 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2196 Register = getContext().getTargetAsmInfo().getDwarfRegNum(RegNo, true);
2198 return getParser().ParseAbsoluteExpression(Register);
2203 /// ParseDirectiveCFIDefCfa
2204 /// ::= .cfi_def_cfa register, offset
2205 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2206 SMLoc DirectiveLoc) {
2207 int64_t Register = 0;
2208 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2211 if (getLexer().isNot(AsmToken::Comma))
2212 return TokError("unexpected token in directive");
2216 if (getParser().ParseAbsoluteExpression(Offset))
2219 return getStreamer().EmitCFIDefCfa(Register, Offset);
2222 /// ParseDirectiveCFIDefCfaOffset
2223 /// ::= .cfi_def_cfa_offset offset
2224 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2225 SMLoc DirectiveLoc) {
2227 if (getParser().ParseAbsoluteExpression(Offset))
2230 return getStreamer().EmitCFIDefCfaOffset(Offset);
2233 /// ParseDirectiveCFIDefCfaRegister
2234 /// ::= .cfi_def_cfa_register register
2235 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2236 SMLoc DirectiveLoc) {
2237 int64_t Register = 0;
2238 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2241 return getStreamer().EmitCFIDefCfaRegister(Register);
2244 /// ParseDirectiveCFIOffset
2245 /// ::= .cfi_off register, offset
2246 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2247 int64_t Register = 0;
2250 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2253 if (getLexer().isNot(AsmToken::Comma))
2254 return TokError("unexpected token in directive");
2257 if (getParser().ParseAbsoluteExpression(Offset))
2260 return getStreamer().EmitCFIOffset(Register, Offset);
2263 static bool isValidEncoding(int64_t Encoding) {
2264 if (Encoding & ~0xff)
2267 if (Encoding == dwarf::DW_EH_PE_omit)
2270 const unsigned Format = Encoding & 0xf;
2271 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2272 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2273 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2274 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2277 const unsigned Application = Encoding & 0x70;
2278 if (Application != dwarf::DW_EH_PE_absptr &&
2279 Application != dwarf::DW_EH_PE_pcrel)
2285 /// ParseDirectiveCFIPersonalityOrLsda
2286 /// ::= .cfi_personality encoding, [symbol_name]
2287 /// ::= .cfi_lsda encoding, [symbol_name]
2288 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2289 SMLoc DirectiveLoc) {
2290 int64_t Encoding = 0;
2291 if (getParser().ParseAbsoluteExpression(Encoding))
2293 if (Encoding == dwarf::DW_EH_PE_omit)
2296 if (!isValidEncoding(Encoding))
2297 return TokError("unsupported encoding.");
2299 if (getLexer().isNot(AsmToken::Comma))
2300 return TokError("unexpected token in directive");
2304 if (getParser().ParseIdentifier(Name))
2305 return TokError("expected identifier in directive");
2307 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2309 if (IDVal == ".cfi_personality")
2310 return getStreamer().EmitCFIPersonality(Sym, Encoding);
2312 assert(IDVal == ".cfi_lsda");
2313 return getStreamer().EmitCFILsda(Sym, Encoding);
2317 /// ParseDirectiveCFIRememberState
2318 /// ::= .cfi_remember_state
2319 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2320 SMLoc DirectiveLoc) {
2321 return getStreamer().EmitCFIRememberState();
2324 /// ParseDirectiveCFIRestoreState
2325 /// ::= .cfi_remember_state
2326 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2327 SMLoc DirectiveLoc) {
2328 return getStreamer().EmitCFIRestoreState();
2331 /// ParseDirectiveMacrosOnOff
2334 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2335 SMLoc DirectiveLoc) {
2336 if (getLexer().isNot(AsmToken::EndOfStatement))
2337 return Error(getLexer().getLoc(),
2338 "unexpected token in '" + Directive + "' directive");
2340 getParser().MacrosEnabled = Directive == ".macros_on";
2345 /// ParseDirectiveMacro
2347 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2348 SMLoc DirectiveLoc) {
2350 if (getParser().ParseIdentifier(Name))
2351 return TokError("expected identifier in directive");
2353 if (getLexer().isNot(AsmToken::EndOfStatement))
2354 return TokError("unexpected token in '.macro' directive");
2356 // Eat the end of statement.
2359 AsmToken EndToken, StartToken = getTok();
2361 // Lex the macro definition.
2363 // Check whether we have reached the end of the file.
2364 if (getLexer().is(AsmToken::Eof))
2365 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2367 // Otherwise, check whether we have reach the .endmacro.
2368 if (getLexer().is(AsmToken::Identifier) &&
2369 (getTok().getIdentifier() == ".endm" ||
2370 getTok().getIdentifier() == ".endmacro")) {
2371 EndToken = getTok();
2373 if (getLexer().isNot(AsmToken::EndOfStatement))
2374 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2379 // Otherwise, scan til the end of the statement.
2380 getParser().EatToEndOfStatement();
2383 if (getParser().MacroMap.lookup(Name)) {
2384 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2387 const char *BodyStart = StartToken.getLoc().getPointer();
2388 const char *BodyEnd = EndToken.getLoc().getPointer();
2389 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2390 getParser().MacroMap[Name] = new Macro(Name, Body);
2394 /// ParseDirectiveEndMacro
2397 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2398 SMLoc DirectiveLoc) {
2399 if (getLexer().isNot(AsmToken::EndOfStatement))
2400 return TokError("unexpected token in '" + Directive + "' directive");
2402 // If we are inside a macro instantiation, terminate the current
2404 if (!getParser().ActiveMacros.empty()) {
2405 getParser().HandleMacroExit();
2409 // Otherwise, this .endmacro is a stray entry in the file; well formed
2410 // .endmacro directives are handled during the macro definition parsing.
2411 return TokError("unexpected '" + Directive + "' in file, "
2412 "no current macro definition");
2415 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2416 getParser().CheckForValidSection();
2418 const MCExpr *Value;
2420 if (getParser().ParseExpression(Value))
2423 if (getLexer().isNot(AsmToken::EndOfStatement))
2424 return TokError("unexpected token in directive");
2426 if (DirName[1] == 's')
2427 getStreamer().EmitSLEB128Value(Value);
2429 getStreamer().EmitULEB128Value(Value);
2435 /// \brief Create an MCAsmParser instance.
2436 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2437 MCContext &C, MCStreamer &Out,
2438 const MCAsmInfo &MAI) {
2439 return new AsmParser(T, SM, C, Out, MAI);