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/TargetAsmParser.h"
40 /// \brief Helper class for tracking macro definitions.
46 Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
49 /// \brief Helper class for storing information about an active macro
51 struct MacroInstantiation {
52 /// The macro being instantiated.
53 const Macro *TheMacro;
55 /// The macro instantiation with substitutions.
56 MemoryBuffer *Instantiation;
58 /// The location of the instantiation.
59 SMLoc InstantiationLoc;
61 /// The location where parsing should resume upon instantiation completion.
65 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
66 const std::vector<std::vector<AsmToken> > &A);
69 /// \brief The concrete assembly parser instance.
70 class AsmParser : public MCAsmParser {
71 friend class GenericAsmParser;
73 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
74 void operator=(const AsmParser &); // DO NOT IMPLEMENT
80 MCAsmParserExtension *GenericParser;
81 MCAsmParserExtension *PlatformParser;
83 /// This is the current buffer index we're lexing from as managed by the
88 std::vector<AsmCond> TheCondStack;
90 /// DirectiveMap - This is a table handlers for directives. Each handler is
91 /// invoked after the directive identifier is read and is responsible for
92 /// parsing and validating the rest of the directive. The handler is passed
93 /// in the directive name and the location of the directive keyword.
94 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
96 /// MacroMap - Map of currently defined macros.
97 StringMap<Macro*> MacroMap;
99 /// ActiveMacros - Stack of active macro instantiations.
100 std::vector<MacroInstantiation*> ActiveMacros;
102 /// Boolean tracking whether macro substitution is enabled.
103 unsigned MacrosEnabled : 1;
105 /// Flag tracking whether any errors have been encountered.
106 unsigned HadError : 1;
109 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
110 const MCAsmInfo &MAI);
113 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
115 void AddDirectiveHandler(MCAsmParserExtension *Object,
117 DirectiveHandler Handler) {
118 DirectiveMap[Directive] = std::make_pair(Object, Handler);
122 /// @name MCAsmParser Interface
125 virtual SourceMgr &getSourceManager() { return SrcMgr; }
126 virtual MCAsmLexer &getLexer() { return Lexer; }
127 virtual MCContext &getContext() { return Ctx; }
128 virtual MCStreamer &getStreamer() { return Out; }
130 virtual void Warning(SMLoc L, const Twine &Meg);
131 virtual bool Error(SMLoc L, const Twine &Msg);
133 const AsmToken &Lex();
135 bool ParseExpression(const MCExpr *&Res);
136 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
137 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
138 virtual bool ParseAbsoluteExpression(int64_t &Res);
143 void CheckForValidSection();
145 bool ParseStatement();
147 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
148 void HandleMacroExit();
150 void PrintMacroInstantiations();
151 void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type) const {
152 SrcMgr.PrintMessage(Loc, Msg, Type);
155 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
156 bool EnterIncludeFile(const std::string &Filename);
158 /// \brief Reset the current lexer position to that given by \arg Loc. The
159 /// current token is not set; clients should ensure Lex() is called
161 void JumpToLoc(SMLoc Loc);
163 void EatToEndOfStatement();
165 /// \brief Parse up to the end of statement and a return the contents from the
166 /// current token until the end of the statement; the current token on exit
167 /// will be either the EndOfStatement or EOF.
168 StringRef ParseStringToEndOfStatement();
170 bool ParseAssignment(StringRef Name);
172 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
173 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
174 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
176 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
177 /// and set \arg Res to the identifier contents.
178 bool ParseIdentifier(StringRef &Res);
180 // Directive Parsing.
182 // ".ascii", ".asciiz", ".string"
183 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
184 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
185 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
186 bool ParseDirectiveFill(); // ".fill"
187 bool ParseDirectiveSpace(); // ".space"
188 bool ParseDirectiveZero(); // ".zero"
189 bool ParseDirectiveSet(StringRef IDVal); // ".set" or ".equ"
190 bool ParseDirectiveOrg(); // ".org"
191 // ".align{,32}", ".p2align{,w,l}"
192 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
194 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
195 /// accepts a single symbol (which should be a label or an external).
196 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
198 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
200 bool ParseDirectiveAbort(); // ".abort"
201 bool ParseDirectiveInclude(); // ".include"
203 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
204 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
205 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
206 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
208 /// ParseEscapedString - Parse the current token as a string which may include
209 /// escaped characters and return the string contents.
210 bool ParseEscapedString(std::string &Data);
212 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
213 MCSymbolRefExpr::VariantKind Variant);
216 /// \brief Generic implementations of directive handling, etc. which is shared
217 /// (or the default, at least) for all assembler parser.
218 class GenericAsmParser : public MCAsmParserExtension {
219 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
220 void AddDirectiveHandler(StringRef Directive) {
221 getParser().AddDirectiveHandler(this, Directive,
222 HandleDirective<GenericAsmParser, Handler>);
226 GenericAsmParser() {}
228 AsmParser &getParser() {
229 return (AsmParser&) this->MCAsmParserExtension::getParser();
232 virtual void Initialize(MCAsmParser &Parser) {
233 // Call the base implementation.
234 this->MCAsmParserExtension::Initialize(Parser);
236 // Debugging directives.
237 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
238 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
239 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
240 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
243 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
245 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
247 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
249 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
250 ".cfi_def_cfa_offset");
251 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
252 ".cfi_def_cfa_register");
253 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
256 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
258 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
260 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
262 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
265 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
267 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
269 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
270 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
271 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
273 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
274 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
277 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
278 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
279 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
280 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
281 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
282 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
283 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
284 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
285 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
286 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
287 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
288 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
289 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
291 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
292 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
293 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
295 bool ParseDirectiveLEB128(StringRef, SMLoc);
302 extern MCAsmParserExtension *createDarwinAsmParser();
303 extern MCAsmParserExtension *createELFAsmParser();
304 extern MCAsmParserExtension *createCOFFAsmParser();
308 enum { DEFAULT_ADDRSPACE = 0 };
310 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
311 MCStreamer &_Out, const MCAsmInfo &_MAI)
312 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
313 GenericParser(new GenericAsmParser), PlatformParser(0),
314 CurBuffer(0), MacrosEnabled(true) {
315 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
317 // Initialize the generic parser.
318 GenericParser->Initialize(*this);
320 // Initialize the platform / file format parser.
322 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
324 if (_MAI.hasMicrosoftFastStdCallMangling()) {
325 PlatformParser = createCOFFAsmParser();
326 PlatformParser->Initialize(*this);
327 } else if (_MAI.hasSubsectionsViaSymbols()) {
328 PlatformParser = createDarwinAsmParser();
329 PlatformParser->Initialize(*this);
331 PlatformParser = createELFAsmParser();
332 PlatformParser->Initialize(*this);
336 AsmParser::~AsmParser() {
337 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
339 // Destroy any macros.
340 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
341 ie = MacroMap.end(); it != ie; ++it)
342 delete it->getValue();
344 delete PlatformParser;
345 delete GenericParser;
348 void AsmParser::PrintMacroInstantiations() {
349 // Print the active macro instantiation stack.
350 for (std::vector<MacroInstantiation*>::const_reverse_iterator
351 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
352 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
356 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
357 PrintMessage(L, Msg, "warning");
358 PrintMacroInstantiations();
361 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
363 PrintMessage(L, Msg, "error");
364 PrintMacroInstantiations();
368 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
369 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
375 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
380 void AsmParser::JumpToLoc(SMLoc Loc) {
381 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
382 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
385 const AsmToken &AsmParser::Lex() {
386 const AsmToken *tok = &Lexer.Lex();
388 if (tok->is(AsmToken::Eof)) {
389 // If this is the end of an included file, pop the parent file off the
391 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
392 if (ParentIncludeLoc != SMLoc()) {
393 JumpToLoc(ParentIncludeLoc);
398 if (tok->is(AsmToken::Error))
399 Error(Lexer.getErrLoc(), Lexer.getErr());
404 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
405 // Create the initial section, if requested.
406 if (!NoInitialTextSection)
413 AsmCond StartingCondState = TheCondState;
415 // While we have input, parse each statement.
416 while (Lexer.isNot(AsmToken::Eof)) {
417 if (!ParseStatement()) continue;
419 // We had an error, validate that one was emitted and recover by skipping to
421 assert(HadError && "Parse statement returned an error, but none emitted!");
422 EatToEndOfStatement();
425 if (TheCondState.TheCond != StartingCondState.TheCond ||
426 TheCondState.Ignore != StartingCondState.Ignore)
427 return TokError("unmatched .ifs or .elses");
429 // Check to see there are no empty DwarfFile slots.
430 const std::vector<MCDwarfFile *> &MCDwarfFiles =
431 getContext().getMCDwarfFiles();
432 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
433 if (!MCDwarfFiles[i])
434 TokError("unassigned file number: " + Twine(i) + " for .file directives");
437 // Finalize the output stream if there are no errors and if the client wants
439 if (!HadError && !NoFinalize)
445 void AsmParser::CheckForValidSection() {
446 if (!getStreamer().getCurrentSection()) {
447 TokError("expected section directive before assembly directive");
448 Out.SwitchSection(Ctx.getMachOSection(
450 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
451 0, SectionKind::getText()));
455 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
456 void AsmParser::EatToEndOfStatement() {
457 while (Lexer.isNot(AsmToken::EndOfStatement) &&
458 Lexer.isNot(AsmToken::Eof))
462 if (Lexer.is(AsmToken::EndOfStatement))
466 StringRef AsmParser::ParseStringToEndOfStatement() {
467 const char *Start = getTok().getLoc().getPointer();
469 while (Lexer.isNot(AsmToken::EndOfStatement) &&
470 Lexer.isNot(AsmToken::Eof))
473 const char *End = getTok().getLoc().getPointer();
474 return StringRef(Start, End - Start);
477 /// ParseParenExpr - Parse a paren expression and return it.
478 /// NOTE: This assumes the leading '(' has already been consumed.
480 /// parenexpr ::= expr)
482 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
483 if (ParseExpression(Res)) return true;
484 if (Lexer.isNot(AsmToken::RParen))
485 return TokError("expected ')' in parentheses expression");
486 EndLoc = Lexer.getLoc();
491 /// ParsePrimaryExpr - Parse a primary expression and return it.
492 /// primaryexpr ::= (parenexpr
493 /// primaryexpr ::= symbol
494 /// primaryexpr ::= number
495 /// primaryexpr ::= '.'
496 /// primaryexpr ::= ~,+,- primaryexpr
497 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
498 switch (Lexer.getKind()) {
500 return TokError("unknown token in expression");
501 case AsmToken::Exclaim:
502 Lex(); // Eat the operator.
503 if (ParsePrimaryExpr(Res, EndLoc))
505 Res = MCUnaryExpr::CreateLNot(Res, getContext());
507 case AsmToken::Dollar:
508 case AsmToken::String:
509 case AsmToken::Identifier: {
510 EndLoc = Lexer.getLoc();
512 StringRef Identifier;
513 if (ParseIdentifier(Identifier))
516 // This is a symbol reference.
517 std::pair<StringRef, StringRef> Split = Identifier.split('@');
518 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
520 // Lookup the symbol variant if used.
521 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
522 if (Split.first.size() != Identifier.size()) {
523 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
524 if (Variant == MCSymbolRefExpr::VK_Invalid) {
525 Variant = MCSymbolRefExpr::VK_None;
526 return TokError("invalid variant '" + Split.second + "'");
530 // If this is an absolute variable reference, substitute it now to preserve
531 // semantics in the face of reassignment.
532 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
534 return Error(EndLoc, "unexpected modifier on variable reference");
536 Res = Sym->getVariableValue();
540 // Otherwise create a symbol ref.
541 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
544 case AsmToken::Integer: {
545 SMLoc Loc = getTok().getLoc();
546 int64_t IntVal = getTok().getIntVal();
547 Res = MCConstantExpr::Create(IntVal, getContext());
548 EndLoc = Lexer.getLoc();
550 // Look for 'b' or 'f' following an Integer as a directional label
551 if (Lexer.getKind() == AsmToken::Identifier) {
552 StringRef IDVal = getTok().getString();
553 if (IDVal == "f" || IDVal == "b"){
554 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
555 IDVal == "f" ? 1 : 0);
556 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
558 if(IDVal == "b" && Sym->isUndefined())
559 return Error(Loc, "invalid reference to undefined symbol");
560 EndLoc = Lexer.getLoc();
561 Lex(); // Eat identifier.
566 case AsmToken::Real: {
567 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
568 int64_t IntVal = RealVal.bitcastToAPInt().getSExtValue();
569 Res = MCConstantExpr::Create(IntVal, getContext());
573 case AsmToken::Dot: {
574 // This is a '.' reference, which references the current PC. Emit a
575 // temporary label to the streamer and refer to it.
576 MCSymbol *Sym = Ctx.CreateTempSymbol();
578 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
579 EndLoc = Lexer.getLoc();
580 Lex(); // Eat identifier.
583 case AsmToken::LParen:
584 Lex(); // Eat the '('.
585 return ParseParenExpr(Res, EndLoc);
586 case AsmToken::Minus:
587 Lex(); // Eat the operator.
588 if (ParsePrimaryExpr(Res, EndLoc))
590 Res = MCUnaryExpr::CreateMinus(Res, getContext());
593 Lex(); // Eat the operator.
594 if (ParsePrimaryExpr(Res, EndLoc))
596 Res = MCUnaryExpr::CreatePlus(Res, getContext());
598 case AsmToken::Tilde:
599 Lex(); // Eat the operator.
600 if (ParsePrimaryExpr(Res, EndLoc))
602 Res = MCUnaryExpr::CreateNot(Res, getContext());
607 bool AsmParser::ParseExpression(const MCExpr *&Res) {
609 return ParseExpression(Res, EndLoc);
613 AsmParser::ApplyModifierToExpr(const MCExpr *E,
614 MCSymbolRefExpr::VariantKind Variant) {
615 // Recurse over the given expression, rebuilding it to apply the given variant
616 // if there is exactly one symbol.
617 switch (E->getKind()) {
619 case MCExpr::Constant:
622 case MCExpr::SymbolRef: {
623 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
625 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
626 TokError("invalid variant on expression '" +
627 getTok().getIdentifier() + "' (already modified)");
631 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
634 case MCExpr::Unary: {
635 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
636 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
639 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
642 case MCExpr::Binary: {
643 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
644 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
645 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
650 if (!LHS) LHS = BE->getLHS();
651 if (!RHS) RHS = BE->getRHS();
653 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
657 assert(0 && "Invalid expression kind!");
661 /// ParseExpression - Parse an expression and return it.
663 /// expr ::= expr +,- expr -> lowest.
664 /// expr ::= expr |,^,&,! expr -> middle.
665 /// expr ::= expr *,/,%,<<,>> expr -> highest.
666 /// expr ::= primaryexpr
668 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
669 // Parse the expression.
671 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
674 // As a special case, we support 'a op b @ modifier' by rewriting the
675 // expression to include the modifier. This is inefficient, but in general we
676 // expect users to use 'a@modifier op b'.
677 if (Lexer.getKind() == AsmToken::At) {
680 if (Lexer.isNot(AsmToken::Identifier))
681 return TokError("unexpected symbol modifier following '@'");
683 MCSymbolRefExpr::VariantKind Variant =
684 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
685 if (Variant == MCSymbolRefExpr::VK_Invalid)
686 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
688 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
690 return TokError("invalid modifier '" + getTok().getIdentifier() +
691 "' (no symbols present)");
699 // Try to constant fold it up front, if possible.
701 if (Res->EvaluateAsAbsolute(Value))
702 Res = MCConstantExpr::Create(Value, getContext());
707 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
709 return ParseParenExpr(Res, EndLoc) ||
710 ParseBinOpRHS(1, Res, EndLoc);
713 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
716 SMLoc StartLoc = Lexer.getLoc();
717 if (ParseExpression(Expr))
720 if (!Expr->EvaluateAsAbsolute(Res))
721 return Error(StartLoc, "expected absolute expression");
726 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
727 MCBinaryExpr::Opcode &Kind) {
730 return 0; // not a binop.
732 // Lowest Precedence: &&, ||, @
733 case AsmToken::AmpAmp:
734 Kind = MCBinaryExpr::LAnd;
736 case AsmToken::PipePipe:
737 Kind = MCBinaryExpr::LOr;
741 // Low Precedence: |, &, ^
743 // FIXME: gas seems to support '!' as an infix operator?
745 Kind = MCBinaryExpr::Or;
747 case AsmToken::Caret:
748 Kind = MCBinaryExpr::Xor;
751 Kind = MCBinaryExpr::And;
754 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
755 case AsmToken::EqualEqual:
756 Kind = MCBinaryExpr::EQ;
758 case AsmToken::ExclaimEqual:
759 case AsmToken::LessGreater:
760 Kind = MCBinaryExpr::NE;
763 Kind = MCBinaryExpr::LT;
765 case AsmToken::LessEqual:
766 Kind = MCBinaryExpr::LTE;
768 case AsmToken::Greater:
769 Kind = MCBinaryExpr::GT;
771 case AsmToken::GreaterEqual:
772 Kind = MCBinaryExpr::GTE;
775 // High Intermediate Precedence: +, -
777 Kind = MCBinaryExpr::Add;
779 case AsmToken::Minus:
780 Kind = MCBinaryExpr::Sub;
783 // Highest Precedence: *, /, %, <<, >>
785 Kind = MCBinaryExpr::Mul;
787 case AsmToken::Slash:
788 Kind = MCBinaryExpr::Div;
790 case AsmToken::Percent:
791 Kind = MCBinaryExpr::Mod;
793 case AsmToken::LessLess:
794 Kind = MCBinaryExpr::Shl;
796 case AsmToken::GreaterGreater:
797 Kind = MCBinaryExpr::Shr;
803 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
804 /// Res contains the LHS of the expression on input.
805 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
808 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
809 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
811 // If the next token is lower precedence than we are allowed to eat, return
812 // successfully with what we ate already.
813 if (TokPrec < Precedence)
818 // Eat the next primary expression.
820 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
822 // If BinOp binds less tightly with RHS than the operator after RHS, let
823 // the pending operator take RHS as its LHS.
824 MCBinaryExpr::Opcode Dummy;
825 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
826 if (TokPrec < NextTokPrec) {
827 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
830 // Merge LHS and RHS according to operator.
831 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
839 /// ::= EndOfStatement
840 /// ::= Label* Directive ...Operands... EndOfStatement
841 /// ::= Label* Identifier OperandList* EndOfStatement
842 bool AsmParser::ParseStatement() {
843 if (Lexer.is(AsmToken::EndOfStatement)) {
849 // Statements always start with an identifier or are a full line comment.
850 AsmToken ID = getTok();
851 SMLoc IDLoc = ID.getLoc();
853 int64_t LocalLabelVal = -1;
854 // A full line comment is a '#' as the first token.
855 if (Lexer.is(AsmToken::Hash)) {
856 EatToEndOfStatement();
859 // Allow an integer followed by a ':' as a directional local label.
860 if (Lexer.is(AsmToken::Integer)) {
861 LocalLabelVal = getTok().getIntVal();
862 if (LocalLabelVal < 0) {
863 if (!TheCondState.Ignore)
864 return TokError("unexpected token at start of statement");
868 IDVal = getTok().getString();
869 Lex(); // Consume the integer token to be used as an identifier token.
870 if (Lexer.getKind() != AsmToken::Colon) {
871 if (!TheCondState.Ignore)
872 return TokError("unexpected token at start of statement");
876 else if (ParseIdentifier(IDVal)) {
877 if (!TheCondState.Ignore)
878 return TokError("unexpected token at start of statement");
882 // Handle conditional assembly here before checking for skipping. We
883 // have to do this so that .endif isn't skipped in a ".if 0" block for
886 return ParseDirectiveIf(IDLoc);
887 if (IDVal == ".elseif")
888 return ParseDirectiveElseIf(IDLoc);
889 if (IDVal == ".else")
890 return ParseDirectiveElse(IDLoc);
891 if (IDVal == ".endif")
892 return ParseDirectiveEndIf(IDLoc);
894 // If we are in a ".if 0" block, ignore this statement.
895 if (TheCondState.Ignore) {
896 EatToEndOfStatement();
900 // FIXME: Recurse on local labels?
902 // See what kind of statement we have.
903 switch (Lexer.getKind()) {
904 case AsmToken::Colon: {
905 CheckForValidSection();
907 // identifier ':' -> Label.
910 // Diagnose attempt to use a variable as a label.
912 // FIXME: Diagnostics. Note the location of the definition as a label.
913 // FIXME: This doesn't diagnose assignment to a symbol which has been
914 // implicitly marked as external.
916 if (LocalLabelVal == -1)
917 Sym = getContext().GetOrCreateSymbol(IDVal);
919 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
920 if (!Sym->isUndefined() || Sym->isVariable())
921 return Error(IDLoc, "invalid symbol redefinition");
926 // Consume any end of statement token, if present, to avoid spurious
927 // AddBlankLine calls().
928 if (Lexer.is(AsmToken::EndOfStatement)) {
930 if (Lexer.is(AsmToken::Eof))
934 return ParseStatement();
937 case AsmToken::Equal:
938 // identifier '=' ... -> assignment statement
941 return ParseAssignment(IDVal);
943 default: // Normal instruction or directive.
947 // If macros are enabled, check to see if this is a macro instantiation.
949 if (const Macro *M = MacroMap.lookup(IDVal))
950 return HandleMacroEntry(IDVal, IDLoc, M);
952 // Otherwise, we have a normal instruction or directive.
953 if (IDVal[0] == '.') {
954 // Assembler features
955 if (IDVal == ".set" || IDVal == ".equ")
956 return ParseDirectiveSet(IDVal);
960 if (IDVal == ".ascii")
961 return ParseDirectiveAscii(IDVal, false);
962 if (IDVal == ".asciz" || IDVal == ".string")
963 return ParseDirectiveAscii(IDVal, true);
965 if (IDVal == ".byte")
966 return ParseDirectiveValue(1);
967 if (IDVal == ".short")
968 return ParseDirectiveValue(2);
969 if (IDVal == ".value")
970 return ParseDirectiveValue(2);
971 if (IDVal == ".2byte")
972 return ParseDirectiveValue(2);
973 if (IDVal == ".long")
974 return ParseDirectiveValue(4);
976 return ParseDirectiveValue(4);
977 if (IDVal == ".4byte")
978 return ParseDirectiveValue(4);
979 if (IDVal == ".quad")
980 return ParseDirectiveValue(8);
981 if (IDVal == ".8byte")
982 return ParseDirectiveValue(8);
983 if (IDVal == ".single")
984 return ParseDirectiveRealValue(APFloat::IEEEsingle);
985 if (IDVal == ".double")
986 return ParseDirectiveRealValue(APFloat::IEEEdouble);
988 if (IDVal == ".align") {
989 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
990 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
992 if (IDVal == ".align32") {
993 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
994 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
996 if (IDVal == ".balign")
997 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
998 if (IDVal == ".balignw")
999 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1000 if (IDVal == ".balignl")
1001 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1002 if (IDVal == ".p2align")
1003 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1004 if (IDVal == ".p2alignw")
1005 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1006 if (IDVal == ".p2alignl")
1007 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1009 if (IDVal == ".org")
1010 return ParseDirectiveOrg();
1012 if (IDVal == ".fill")
1013 return ParseDirectiveFill();
1014 if (IDVal == ".space")
1015 return ParseDirectiveSpace();
1016 if (IDVal == ".zero")
1017 return ParseDirectiveZero();
1019 // Symbol attribute directives
1021 if (IDVal == ".globl" || IDVal == ".global")
1022 return ParseDirectiveSymbolAttribute(MCSA_Global);
1023 // ELF only? Should it be here?
1024 if (IDVal == ".local")
1025 return ParseDirectiveSymbolAttribute(MCSA_Local);
1026 if (IDVal == ".hidden")
1027 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1028 if (IDVal == ".indirect_symbol")
1029 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1030 if (IDVal == ".internal")
1031 return ParseDirectiveSymbolAttribute(MCSA_Internal);
1032 if (IDVal == ".lazy_reference")
1033 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1034 if (IDVal == ".no_dead_strip")
1035 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1036 if (IDVal == ".symbol_resolver")
1037 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1038 if (IDVal == ".private_extern")
1039 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1040 if (IDVal == ".protected")
1041 return ParseDirectiveSymbolAttribute(MCSA_Protected);
1042 if (IDVal == ".reference")
1043 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1044 if (IDVal == ".weak")
1045 return ParseDirectiveSymbolAttribute(MCSA_Weak);
1046 if (IDVal == ".weak_definition")
1047 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1048 if (IDVal == ".weak_reference")
1049 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1050 if (IDVal == ".weak_def_can_be_hidden")
1051 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1053 if (IDVal == ".comm")
1054 return ParseDirectiveComm(/*IsLocal=*/false);
1055 if (IDVal == ".lcomm")
1056 return ParseDirectiveComm(/*IsLocal=*/true);
1058 if (IDVal == ".abort")
1059 return ParseDirectiveAbort();
1060 if (IDVal == ".include")
1061 return ParseDirectiveInclude();
1063 // Look up the handler in the handler table.
1064 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1065 DirectiveMap.lookup(IDVal);
1067 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1069 // Target hook for parsing target specific directives.
1070 if (!getTargetParser().ParseDirective(ID))
1073 Warning(IDLoc, "ignoring directive for now");
1074 EatToEndOfStatement();
1078 CheckForValidSection();
1080 // Canonicalize the opcode to lower case.
1081 SmallString<128> Opcode;
1082 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1083 Opcode.push_back(tolower(IDVal[i]));
1085 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1086 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1089 // Dump the parsed representation, if requested.
1090 if (getShowParsedOperands()) {
1091 SmallString<256> Str;
1092 raw_svector_ostream OS(Str);
1093 OS << "parsed instruction: [";
1094 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1097 ParsedOperands[i]->dump(OS);
1101 PrintMessage(IDLoc, OS.str(), "note");
1104 // If parsing succeeded, match the instruction.
1106 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1109 // Free any parsed operands.
1110 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1111 delete ParsedOperands[i];
1113 // Don't skip the rest of the line, the instruction parser is responsible for
1118 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1119 const std::vector<std::vector<AsmToken> > &A)
1120 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1122 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1123 // to hold the macro body with substitutions.
1124 SmallString<256> Buf;
1125 raw_svector_ostream OS(Buf);
1127 StringRef Body = M->Body;
1128 while (!Body.empty()) {
1129 // Scan for the next substitution.
1130 std::size_t End = Body.size(), Pos = 0;
1131 for (; Pos != End; ++Pos) {
1132 // Check for a substitution or escape.
1133 if (Body[Pos] != '$' || Pos + 1 == End)
1136 char Next = Body[Pos + 1];
1137 if (Next == '$' || Next == 'n' || isdigit(Next))
1142 OS << Body.slice(0, Pos);
1144 // Check if we reached the end.
1148 switch (Body[Pos+1]) {
1154 // $n => number of arguments
1159 // $[0-9] => argument
1161 // Missing arguments are ignored.
1162 unsigned Index = Body[Pos+1] - '0';
1163 if (Index >= A.size())
1166 // Otherwise substitute with the token values, with spaces eliminated.
1167 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1168 ie = A[Index].end(); it != ie; ++it)
1169 OS << it->getString();
1174 // Update the scan point.
1175 Body = Body.substr(Pos + 2);
1178 // We include the .endmacro in the buffer as our queue to exit the macro
1180 OS << ".endmacro\n";
1182 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1185 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1187 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1188 // this, although we should protect against infinite loops.
1189 if (ActiveMacros.size() == 20)
1190 return TokError("macros cannot be nested more than 20 levels deep");
1192 // Parse the macro instantiation arguments.
1193 std::vector<std::vector<AsmToken> > MacroArguments;
1194 MacroArguments.push_back(std::vector<AsmToken>());
1195 unsigned ParenLevel = 0;
1197 if (Lexer.is(AsmToken::Eof))
1198 return TokError("unexpected token in macro instantiation");
1199 if (Lexer.is(AsmToken::EndOfStatement))
1202 // If we aren't inside parentheses and this is a comma, start a new token
1204 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1205 MacroArguments.push_back(std::vector<AsmToken>());
1207 // Adjust the current parentheses level.
1208 if (Lexer.is(AsmToken::LParen))
1210 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1213 // Append the token to the current argument list.
1214 MacroArguments.back().push_back(getTok());
1219 // Create the macro instantiation object and add to the current macro
1220 // instantiation stack.
1221 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1224 ActiveMacros.push_back(MI);
1226 // Jump to the macro instantiation and prime the lexer.
1227 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1228 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1234 void AsmParser::HandleMacroExit() {
1235 // Jump to the EndOfStatement we should return to, and consume it.
1236 JumpToLoc(ActiveMacros.back()->ExitLoc);
1239 // Pop the instantiation entry.
1240 delete ActiveMacros.back();
1241 ActiveMacros.pop_back();
1244 static void MarkUsed(const MCExpr *Value) {
1245 switch (Value->getKind()) {
1246 case MCExpr::Binary:
1247 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1248 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1250 case MCExpr::Target:
1251 case MCExpr::Constant:
1253 case MCExpr::SymbolRef: {
1254 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1258 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1263 bool AsmParser::ParseAssignment(StringRef Name) {
1264 // FIXME: Use better location, we should use proper tokens.
1265 SMLoc EqualLoc = Lexer.getLoc();
1267 const MCExpr *Value;
1268 if (ParseExpression(Value))
1273 if (Lexer.isNot(AsmToken::EndOfStatement))
1274 return TokError("unexpected token in assignment");
1276 // Eat the end of statement marker.
1279 // Validate that the LHS is allowed to be a variable (either it has not been
1280 // used as a symbol, or it is an absolute symbol).
1281 MCSymbol *Sym = getContext().LookupSymbol(Name);
1283 // Diagnose assignment to a label.
1285 // FIXME: Diagnostics. Note the location of the definition as a label.
1286 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1287 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1288 ; // Allow redefinitions of undefined symbols only used in directives.
1289 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1290 return Error(EqualLoc, "redefinition of '" + Name + "'");
1291 else if (!Sym->isVariable())
1292 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1293 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1294 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1297 // Don't count these checks as uses.
1298 Sym->setUsed(false);
1300 Sym = getContext().GetOrCreateSymbol(Name);
1302 // FIXME: Handle '.'.
1304 // Do the assignment.
1305 Out.EmitAssignment(Sym, Value);
1310 /// ParseIdentifier:
1313 bool AsmParser::ParseIdentifier(StringRef &Res) {
1314 // The assembler has relaxed rules for accepting identifiers, in particular we
1315 // allow things like '.globl $foo', which would normally be separate
1316 // tokens. At this level, we have already lexed so we cannot (currently)
1317 // handle this as a context dependent token, instead we detect adjacent tokens
1318 // and return the combined identifier.
1319 if (Lexer.is(AsmToken::Dollar)) {
1320 SMLoc DollarLoc = getLexer().getLoc();
1322 // Consume the dollar sign, and check for a following identifier.
1324 if (Lexer.isNot(AsmToken::Identifier))
1327 // We have a '$' followed by an identifier, make sure they are adjacent.
1328 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1331 // Construct the joined identifier and consume the token.
1332 Res = StringRef(DollarLoc.getPointer(),
1333 getTok().getIdentifier().size() + 1);
1338 if (Lexer.isNot(AsmToken::Identifier) &&
1339 Lexer.isNot(AsmToken::String))
1342 Res = getTok().getIdentifier();
1344 Lex(); // Consume the identifier token.
1349 /// ParseDirectiveSet:
1350 /// ::= .set identifier ',' expression
1351 bool AsmParser::ParseDirectiveSet(StringRef IDVal) {
1354 if (ParseIdentifier(Name))
1355 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1357 if (getLexer().isNot(AsmToken::Comma))
1358 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1361 return ParseAssignment(Name);
1364 bool AsmParser::ParseEscapedString(std::string &Data) {
1365 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1368 StringRef Str = getTok().getStringContents();
1369 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1370 if (Str[i] != '\\') {
1375 // Recognize escaped characters. Note that this escape semantics currently
1376 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1379 return TokError("unexpected backslash at end of string");
1381 // Recognize octal sequences.
1382 if ((unsigned) (Str[i] - '0') <= 7) {
1383 // Consume up to three octal characters.
1384 unsigned Value = Str[i] - '0';
1386 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1388 Value = Value * 8 + (Str[i] - '0');
1390 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1392 Value = Value * 8 + (Str[i] - '0');
1397 return TokError("invalid octal escape sequence (out of range)");
1399 Data += (unsigned char) Value;
1403 // Otherwise recognize individual escapes.
1406 // Just reject invalid escape sequences for now.
1407 return TokError("invalid escape sequence (unrecognized character)");
1409 case 'b': Data += '\b'; break;
1410 case 'f': Data += '\f'; break;
1411 case 'n': Data += '\n'; break;
1412 case 'r': Data += '\r'; break;
1413 case 't': Data += '\t'; break;
1414 case '"': Data += '"'; break;
1415 case '\\': Data += '\\'; break;
1422 /// ParseDirectiveAscii:
1423 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1424 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1425 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1426 CheckForValidSection();
1429 if (getLexer().isNot(AsmToken::String))
1430 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1433 if (ParseEscapedString(Data))
1436 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1438 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1442 if (getLexer().is(AsmToken::EndOfStatement))
1445 if (getLexer().isNot(AsmToken::Comma))
1446 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1455 /// ParseDirectiveValue
1456 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1457 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1458 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1459 CheckForValidSection();
1462 const MCExpr *Value;
1463 if (ParseExpression(Value))
1466 // Special case constant expressions to match code generator.
1467 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1468 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1470 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1472 if (getLexer().is(AsmToken::EndOfStatement))
1475 // FIXME: Improve diagnostic.
1476 if (getLexer().isNot(AsmToken::Comma))
1477 return TokError("unexpected token in directive");
1486 /// ParseDirectiveRealValue
1487 /// ::= (.single | .double) [ expression (, expression)* ]
1488 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1489 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1490 CheckForValidSection();
1493 // We don't truly support arithmetic on floating point expressions, so we
1494 // have to manually parse unary prefixes.
1496 if (getLexer().is(AsmToken::Minus)) {
1499 } else if (getLexer().is(AsmToken::Plus))
1502 if (getLexer().isNot(AsmToken::Integer) &&
1503 getLexer().isNot(AsmToken::Real))
1504 return TokError("unexpected token in directive");
1506 // Convert to an APFloat.
1507 APFloat Value(Semantics);
1508 if (Value.convertFromString(getTok().getString(),
1509 APFloat::rmNearestTiesToEven) ==
1510 APFloat::opInvalidOp)
1511 return TokError("invalid floating point literal");
1515 // Consume the numeric token.
1518 // Emit the value as an integer.
1519 APInt AsInt = Value.bitcastToAPInt();
1520 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1521 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1523 if (getLexer().is(AsmToken::EndOfStatement))
1526 if (getLexer().isNot(AsmToken::Comma))
1527 return TokError("unexpected token in directive");
1536 /// ParseDirectiveSpace
1537 /// ::= .space expression [ , expression ]
1538 bool AsmParser::ParseDirectiveSpace() {
1539 CheckForValidSection();
1542 if (ParseAbsoluteExpression(NumBytes))
1545 int64_t FillExpr = 0;
1546 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1547 if (getLexer().isNot(AsmToken::Comma))
1548 return TokError("unexpected token in '.space' directive");
1551 if (ParseAbsoluteExpression(FillExpr))
1554 if (getLexer().isNot(AsmToken::EndOfStatement))
1555 return TokError("unexpected token in '.space' directive");
1561 return TokError("invalid number of bytes in '.space' directive");
1563 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1564 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1569 /// ParseDirectiveZero
1570 /// ::= .zero expression
1571 bool AsmParser::ParseDirectiveZero() {
1572 CheckForValidSection();
1575 if (ParseAbsoluteExpression(NumBytes))
1579 if (getLexer().is(AsmToken::Comma)) {
1581 if (ParseAbsoluteExpression(Val))
1585 if (getLexer().isNot(AsmToken::EndOfStatement))
1586 return TokError("unexpected token in '.zero' directive");
1590 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1595 /// ParseDirectiveFill
1596 /// ::= .fill expression , expression , expression
1597 bool AsmParser::ParseDirectiveFill() {
1598 CheckForValidSection();
1601 if (ParseAbsoluteExpression(NumValues))
1604 if (getLexer().isNot(AsmToken::Comma))
1605 return TokError("unexpected token in '.fill' directive");
1609 if (ParseAbsoluteExpression(FillSize))
1612 if (getLexer().isNot(AsmToken::Comma))
1613 return TokError("unexpected token in '.fill' directive");
1617 if (ParseAbsoluteExpression(FillExpr))
1620 if (getLexer().isNot(AsmToken::EndOfStatement))
1621 return TokError("unexpected token in '.fill' directive");
1625 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1626 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1628 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1629 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1634 /// ParseDirectiveOrg
1635 /// ::= .org expression [ , expression ]
1636 bool AsmParser::ParseDirectiveOrg() {
1637 CheckForValidSection();
1639 const MCExpr *Offset;
1640 if (ParseExpression(Offset))
1643 // Parse optional fill expression.
1644 int64_t FillExpr = 0;
1645 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1646 if (getLexer().isNot(AsmToken::Comma))
1647 return TokError("unexpected token in '.org' directive");
1650 if (ParseAbsoluteExpression(FillExpr))
1653 if (getLexer().isNot(AsmToken::EndOfStatement))
1654 return TokError("unexpected token in '.org' directive");
1659 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1660 // has to be relative to the current section.
1661 getStreamer().EmitValueToOffset(Offset, FillExpr);
1666 /// ParseDirectiveAlign
1667 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1668 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1669 CheckForValidSection();
1671 SMLoc AlignmentLoc = getLexer().getLoc();
1673 if (ParseAbsoluteExpression(Alignment))
1677 bool HasFillExpr = false;
1678 int64_t FillExpr = 0;
1679 int64_t MaxBytesToFill = 0;
1680 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1681 if (getLexer().isNot(AsmToken::Comma))
1682 return TokError("unexpected token in directive");
1685 // The fill expression can be omitted while specifying a maximum number of
1686 // alignment bytes, e.g:
1688 if (getLexer().isNot(AsmToken::Comma)) {
1690 if (ParseAbsoluteExpression(FillExpr))
1694 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1695 if (getLexer().isNot(AsmToken::Comma))
1696 return TokError("unexpected token in directive");
1699 MaxBytesLoc = getLexer().getLoc();
1700 if (ParseAbsoluteExpression(MaxBytesToFill))
1703 if (getLexer().isNot(AsmToken::EndOfStatement))
1704 return TokError("unexpected token in directive");
1713 // Compute alignment in bytes.
1715 // FIXME: Diagnose overflow.
1716 if (Alignment >= 32) {
1717 Error(AlignmentLoc, "invalid alignment value");
1721 Alignment = 1ULL << Alignment;
1724 // Diagnose non-sensical max bytes to align.
1725 if (MaxBytesLoc.isValid()) {
1726 if (MaxBytesToFill < 1) {
1727 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1728 "many bytes, ignoring maximum bytes expression");
1732 if (MaxBytesToFill >= Alignment) {
1733 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1739 // Check whether we should use optimal code alignment for this .align
1741 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1742 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1743 ValueSize == 1 && UseCodeAlign) {
1744 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1746 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1747 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1754 /// ParseDirectiveSymbolAttribute
1755 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1756 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1757 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1761 if (ParseIdentifier(Name))
1762 return TokError("expected identifier in directive");
1764 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1766 getStreamer().EmitSymbolAttribute(Sym, Attr);
1768 if (getLexer().is(AsmToken::EndOfStatement))
1771 if (getLexer().isNot(AsmToken::Comma))
1772 return TokError("unexpected token in directive");
1781 /// ParseDirectiveComm
1782 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1783 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1784 CheckForValidSection();
1786 SMLoc IDLoc = getLexer().getLoc();
1788 if (ParseIdentifier(Name))
1789 return TokError("expected identifier in directive");
1791 // Handle the identifier as the key symbol.
1792 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1794 if (getLexer().isNot(AsmToken::Comma))
1795 return TokError("unexpected token in directive");
1799 SMLoc SizeLoc = getLexer().getLoc();
1800 if (ParseAbsoluteExpression(Size))
1803 int64_t Pow2Alignment = 0;
1804 SMLoc Pow2AlignmentLoc;
1805 if (getLexer().is(AsmToken::Comma)) {
1807 Pow2AlignmentLoc = getLexer().getLoc();
1808 if (ParseAbsoluteExpression(Pow2Alignment))
1811 // If this target takes alignments in bytes (not log) validate and convert.
1812 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1813 if (!isPowerOf2_64(Pow2Alignment))
1814 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1815 Pow2Alignment = Log2_64(Pow2Alignment);
1819 if (getLexer().isNot(AsmToken::EndOfStatement))
1820 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1824 // NOTE: a size of zero for a .comm should create a undefined symbol
1825 // but a size of .lcomm creates a bss symbol of size zero.
1827 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1828 "be less than zero");
1830 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1831 // may internally end up wanting an alignment in bytes.
1832 // FIXME: Diagnose overflow.
1833 if (Pow2Alignment < 0)
1834 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1835 "alignment, can't be less than zero");
1837 if (!Sym->isUndefined())
1838 return Error(IDLoc, "invalid symbol redefinition");
1840 // '.lcomm' is equivalent to '.zerofill'.
1841 // Create the Symbol as a common or local common with Size and Pow2Alignment
1843 getStreamer().EmitZerofill(Ctx.getMachOSection(
1844 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1845 0, SectionKind::getBSS()),
1846 Sym, Size, 1 << Pow2Alignment);
1850 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1854 /// ParseDirectiveAbort
1855 /// ::= .abort [... message ...]
1856 bool AsmParser::ParseDirectiveAbort() {
1857 // FIXME: Use loc from directive.
1858 SMLoc Loc = getLexer().getLoc();
1860 StringRef Str = ParseStringToEndOfStatement();
1861 if (getLexer().isNot(AsmToken::EndOfStatement))
1862 return TokError("unexpected token in '.abort' directive");
1867 Error(Loc, ".abort detected. Assembly stopping.");
1869 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1870 // FIXME: Actually abort assembly here.
1875 /// ParseDirectiveInclude
1876 /// ::= .include "filename"
1877 bool AsmParser::ParseDirectiveInclude() {
1878 if (getLexer().isNot(AsmToken::String))
1879 return TokError("expected string in '.include' directive");
1881 std::string Filename = getTok().getString();
1882 SMLoc IncludeLoc = getLexer().getLoc();
1885 if (getLexer().isNot(AsmToken::EndOfStatement))
1886 return TokError("unexpected token in '.include' directive");
1888 // Strip the quotes.
1889 Filename = Filename.substr(1, Filename.size()-2);
1891 // Attempt to switch the lexer to the included file before consuming the end
1892 // of statement to avoid losing it when we switch.
1893 if (EnterIncludeFile(Filename)) {
1894 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1901 /// ParseDirectiveIf
1902 /// ::= .if expression
1903 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1904 TheCondStack.push_back(TheCondState);
1905 TheCondState.TheCond = AsmCond::IfCond;
1906 if(TheCondState.Ignore) {
1907 EatToEndOfStatement();
1911 if (ParseAbsoluteExpression(ExprValue))
1914 if (getLexer().isNot(AsmToken::EndOfStatement))
1915 return TokError("unexpected token in '.if' directive");
1919 TheCondState.CondMet = ExprValue;
1920 TheCondState.Ignore = !TheCondState.CondMet;
1926 /// ParseDirectiveElseIf
1927 /// ::= .elseif expression
1928 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1929 if (TheCondState.TheCond != AsmCond::IfCond &&
1930 TheCondState.TheCond != AsmCond::ElseIfCond)
1931 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1933 TheCondState.TheCond = AsmCond::ElseIfCond;
1935 bool LastIgnoreState = false;
1936 if (!TheCondStack.empty())
1937 LastIgnoreState = TheCondStack.back().Ignore;
1938 if (LastIgnoreState || TheCondState.CondMet) {
1939 TheCondState.Ignore = true;
1940 EatToEndOfStatement();
1944 if (ParseAbsoluteExpression(ExprValue))
1947 if (getLexer().isNot(AsmToken::EndOfStatement))
1948 return TokError("unexpected token in '.elseif' directive");
1951 TheCondState.CondMet = ExprValue;
1952 TheCondState.Ignore = !TheCondState.CondMet;
1958 /// ParseDirectiveElse
1960 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1961 if (getLexer().isNot(AsmToken::EndOfStatement))
1962 return TokError("unexpected token in '.else' directive");
1966 if (TheCondState.TheCond != AsmCond::IfCond &&
1967 TheCondState.TheCond != AsmCond::ElseIfCond)
1968 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1970 TheCondState.TheCond = AsmCond::ElseCond;
1971 bool LastIgnoreState = false;
1972 if (!TheCondStack.empty())
1973 LastIgnoreState = TheCondStack.back().Ignore;
1974 if (LastIgnoreState || TheCondState.CondMet)
1975 TheCondState.Ignore = true;
1977 TheCondState.Ignore = false;
1982 /// ParseDirectiveEndIf
1984 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1985 if (getLexer().isNot(AsmToken::EndOfStatement))
1986 return TokError("unexpected token in '.endif' directive");
1990 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1991 TheCondStack.empty())
1992 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1994 if (!TheCondStack.empty()) {
1995 TheCondState = TheCondStack.back();
1996 TheCondStack.pop_back();
2002 /// ParseDirectiveFile
2003 /// ::= .file [number] string
2004 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2005 // FIXME: I'm not sure what this is.
2006 int64_t FileNumber = -1;
2007 SMLoc FileNumberLoc = getLexer().getLoc();
2008 if (getLexer().is(AsmToken::Integer)) {
2009 FileNumber = getTok().getIntVal();
2013 return TokError("file number less than one");
2016 if (getLexer().isNot(AsmToken::String))
2017 return TokError("unexpected token in '.file' directive");
2019 StringRef Filename = getTok().getString();
2020 Filename = Filename.substr(1, Filename.size()-2);
2023 if (getLexer().isNot(AsmToken::EndOfStatement))
2024 return TokError("unexpected token in '.file' directive");
2026 if (FileNumber == -1)
2027 getStreamer().EmitFileDirective(Filename);
2029 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2030 Error(FileNumberLoc, "file number already allocated");
2036 /// ParseDirectiveLine
2037 /// ::= .line [number]
2038 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2039 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2040 if (getLexer().isNot(AsmToken::Integer))
2041 return TokError("unexpected token in '.line' directive");
2043 int64_t LineNumber = getTok().getIntVal();
2047 // FIXME: Do something with the .line.
2050 if (getLexer().isNot(AsmToken::EndOfStatement))
2051 return TokError("unexpected token in '.line' directive");
2057 /// ParseDirectiveLoc
2058 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2059 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2060 /// The first number is a file number, must have been previously assigned with
2061 /// a .file directive, the second number is the line number and optionally the
2062 /// third number is a column position (zero if not specified). The remaining
2063 /// optional items are .loc sub-directives.
2064 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2066 if (getLexer().isNot(AsmToken::Integer))
2067 return TokError("unexpected token in '.loc' directive");
2068 int64_t FileNumber = getTok().getIntVal();
2070 return TokError("file number less than one in '.loc' directive");
2071 if (!getContext().isValidDwarfFileNumber(FileNumber))
2072 return TokError("unassigned file number in '.loc' directive");
2075 int64_t LineNumber = 0;
2076 if (getLexer().is(AsmToken::Integer)) {
2077 LineNumber = getTok().getIntVal();
2079 return TokError("line number less than one in '.loc' directive");
2083 int64_t ColumnPos = 0;
2084 if (getLexer().is(AsmToken::Integer)) {
2085 ColumnPos = getTok().getIntVal();
2087 return TokError("column position less than zero in '.loc' directive");
2091 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2093 int64_t Discriminator = 0;
2094 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2096 if (getLexer().is(AsmToken::EndOfStatement))
2100 SMLoc Loc = getTok().getLoc();
2101 if (getParser().ParseIdentifier(Name))
2102 return TokError("unexpected token in '.loc' directive");
2104 if (Name == "basic_block")
2105 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2106 else if (Name == "prologue_end")
2107 Flags |= DWARF2_FLAG_PROLOGUE_END;
2108 else if (Name == "epilogue_begin")
2109 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2110 else if (Name == "is_stmt") {
2111 SMLoc Loc = getTok().getLoc();
2112 const MCExpr *Value;
2113 if (getParser().ParseExpression(Value))
2115 // The expression must be the constant 0 or 1.
2116 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2117 int Value = MCE->getValue();
2119 Flags &= ~DWARF2_FLAG_IS_STMT;
2120 else if (Value == 1)
2121 Flags |= DWARF2_FLAG_IS_STMT;
2123 return Error(Loc, "is_stmt value not 0 or 1");
2126 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2129 else if (Name == "isa") {
2130 SMLoc Loc = getTok().getLoc();
2131 const MCExpr *Value;
2132 if (getParser().ParseExpression(Value))
2134 // The expression must be a constant greater or equal to 0.
2135 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2136 int Value = MCE->getValue();
2138 return Error(Loc, "isa number less than zero");
2142 return Error(Loc, "isa number not a constant value");
2145 else if (Name == "discriminator") {
2146 if (getParser().ParseAbsoluteExpression(Discriminator))
2150 return Error(Loc, "unknown sub-directive in '.loc' directive");
2153 if (getLexer().is(AsmToken::EndOfStatement))
2158 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2159 Isa, Discriminator);
2164 /// ParseDirectiveStabs
2165 /// ::= .stabs string, number, number, number
2166 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2167 SMLoc DirectiveLoc) {
2168 return TokError("unsupported directive '" + Directive + "'");
2171 /// ParseDirectiveCFIStartProc
2172 /// ::= .cfi_startproc
2173 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2174 SMLoc DirectiveLoc) {
2175 return getStreamer().EmitCFIStartProc();
2178 /// ParseDirectiveCFIEndProc
2179 /// ::= .cfi_endproc
2180 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2181 return getStreamer().EmitCFIEndProc();
2184 /// ParseDirectiveCFIDefCfa
2185 /// ::= .cfi_def_cfa register, offset
2186 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2187 SMLoc DirectiveLoc) {
2188 int64_t Register = 0;
2189 if (getParser().ParseAbsoluteExpression(Register))
2192 if (getLexer().isNot(AsmToken::Comma))
2193 return TokError("unexpected token in directive");
2197 if (getParser().ParseAbsoluteExpression(Offset))
2200 return getStreamer().EmitCFIDefCfa(Register, Offset);
2203 /// ParseDirectiveCFIDefCfaOffset
2204 /// ::= .cfi_def_cfa_offset offset
2205 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2206 SMLoc DirectiveLoc) {
2208 if (getParser().ParseAbsoluteExpression(Offset))
2211 return getStreamer().EmitCFIDefCfaOffset(Offset);
2214 /// ParseDirectiveCFIDefCfaRegister
2215 /// ::= .cfi_def_cfa_register register
2216 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2217 SMLoc DirectiveLoc) {
2218 int64_t Register = 0;
2219 if (getParser().ParseAbsoluteExpression(Register))
2222 return getStreamer().EmitCFIDefCfaRegister(Register);
2225 /// ParseDirectiveCFIOffset
2226 /// ::= .cfi_off register, offset
2227 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2228 int64_t Register = 0;
2230 if (getParser().ParseAbsoluteExpression(Register))
2233 if (getLexer().isNot(AsmToken::Comma))
2234 return TokError("unexpected token in directive");
2237 if (getParser().ParseAbsoluteExpression(Offset))
2240 return getStreamer().EmitCFIOffset(Register, Offset);
2243 static bool isValidEncoding(int64_t Encoding) {
2244 if (Encoding & ~0xff)
2247 if (Encoding == dwarf::DW_EH_PE_omit)
2250 const unsigned Format = Encoding & 0xf;
2251 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2252 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2253 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2254 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2257 const unsigned Application = Encoding & 0x70;
2258 if (Application != dwarf::DW_EH_PE_absptr &&
2259 Application != dwarf::DW_EH_PE_pcrel)
2265 /// ParseDirectiveCFIPersonalityOrLsda
2266 /// ::= .cfi_personality encoding, [symbol_name]
2267 /// ::= .cfi_lsda encoding, [symbol_name]
2268 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2269 SMLoc DirectiveLoc) {
2270 int64_t Encoding = 0;
2271 if (getParser().ParseAbsoluteExpression(Encoding))
2273 if (Encoding == dwarf::DW_EH_PE_omit)
2276 if (!isValidEncoding(Encoding))
2277 return TokError("unsupported encoding.");
2279 if (getLexer().isNot(AsmToken::Comma))
2280 return TokError("unexpected token in directive");
2284 if (getParser().ParseIdentifier(Name))
2285 return TokError("expected identifier in directive");
2287 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2289 if (IDVal == ".cfi_personality")
2290 return getStreamer().EmitCFIPersonality(Sym, Encoding);
2292 assert(IDVal == ".cfi_lsda");
2293 return getStreamer().EmitCFILsda(Sym, Encoding);
2297 /// ParseDirectiveCFIRememberState
2298 /// ::= .cfi_remember_state
2299 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2300 SMLoc DirectiveLoc) {
2301 return getStreamer().EmitCFIRememberState();
2304 /// ParseDirectiveCFIRestoreState
2305 /// ::= .cfi_remember_state
2306 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2307 SMLoc DirectiveLoc) {
2308 return getStreamer().EmitCFIRestoreState();
2311 /// ParseDirectiveMacrosOnOff
2314 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2315 SMLoc DirectiveLoc) {
2316 if (getLexer().isNot(AsmToken::EndOfStatement))
2317 return Error(getLexer().getLoc(),
2318 "unexpected token in '" + Directive + "' directive");
2320 getParser().MacrosEnabled = Directive == ".macros_on";
2325 /// ParseDirectiveMacro
2327 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2328 SMLoc DirectiveLoc) {
2330 if (getParser().ParseIdentifier(Name))
2331 return TokError("expected identifier in directive");
2333 if (getLexer().isNot(AsmToken::EndOfStatement))
2334 return TokError("unexpected token in '.macro' directive");
2336 // Eat the end of statement.
2339 AsmToken EndToken, StartToken = getTok();
2341 // Lex the macro definition.
2343 // Check whether we have reached the end of the file.
2344 if (getLexer().is(AsmToken::Eof))
2345 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2347 // Otherwise, check whether we have reach the .endmacro.
2348 if (getLexer().is(AsmToken::Identifier) &&
2349 (getTok().getIdentifier() == ".endm" ||
2350 getTok().getIdentifier() == ".endmacro")) {
2351 EndToken = getTok();
2353 if (getLexer().isNot(AsmToken::EndOfStatement))
2354 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2359 // Otherwise, scan til the end of the statement.
2360 getParser().EatToEndOfStatement();
2363 if (getParser().MacroMap.lookup(Name)) {
2364 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2367 const char *BodyStart = StartToken.getLoc().getPointer();
2368 const char *BodyEnd = EndToken.getLoc().getPointer();
2369 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2370 getParser().MacroMap[Name] = new Macro(Name, Body);
2374 /// ParseDirectiveEndMacro
2377 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2378 SMLoc DirectiveLoc) {
2379 if (getLexer().isNot(AsmToken::EndOfStatement))
2380 return TokError("unexpected token in '" + Directive + "' directive");
2382 // If we are inside a macro instantiation, terminate the current
2384 if (!getParser().ActiveMacros.empty()) {
2385 getParser().HandleMacroExit();
2389 // Otherwise, this .endmacro is a stray entry in the file; well formed
2390 // .endmacro directives are handled during the macro definition parsing.
2391 return TokError("unexpected '" + Directive + "' in file, "
2392 "no current macro definition");
2395 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2396 getParser().CheckForValidSection();
2398 const MCExpr *Value;
2400 if (getParser().ParseExpression(Value))
2403 if (getLexer().isNot(AsmToken::EndOfStatement))
2404 return TokError("unexpected token in directive");
2406 if (DirName[1] == 's')
2407 getStreamer().EmitSLEB128Value(Value);
2409 getStreamer().EmitULEB128Value(Value);
2415 /// \brief Create an MCAsmParser instance.
2416 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2417 MCContext &C, MCStreamer &Out,
2418 const MCAsmInfo &MAI) {
2419 return new AsmParser(T, SM, C, Out, MAI);