1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCParser/AsmCond.h"
23 #include "llvm/MC/MCParser/AsmLexer.h"
24 #include "llvm/MC/MCParser/MCAsmParser.h"
25 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
26 #include "llvm/MC/MCSectionMachO.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCDwarf.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetAsmInfo.h"
34 #include "llvm/Target/TargetAsmParser.h"
41 /// \brief Helper class for tracking macro definitions.
47 Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
50 /// \brief Helper class for storing information about an active macro
52 struct MacroInstantiation {
53 /// The macro being instantiated.
54 const Macro *TheMacro;
56 /// The macro instantiation with substitutions.
57 MemoryBuffer *Instantiation;
59 /// The location of the instantiation.
60 SMLoc InstantiationLoc;
62 /// The location where parsing should resume upon instantiation completion.
66 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
67 const std::vector<std::vector<AsmToken> > &A);
70 /// \brief The concrete assembly parser instance.
71 class AsmParser : public MCAsmParser {
72 friend class GenericAsmParser;
74 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
75 void operator=(const AsmParser &); // DO NOT IMPLEMENT
81 MCAsmParserExtension *GenericParser;
82 MCAsmParserExtension *PlatformParser;
84 /// This is the current buffer index we're lexing from as managed by the
89 std::vector<AsmCond> TheCondStack;
91 /// DirectiveMap - This is a table handlers for directives. Each handler is
92 /// invoked after the directive identifier is read and is responsible for
93 /// parsing and validating the rest of the directive. The handler is passed
94 /// in the directive name and the location of the directive keyword.
95 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
97 /// MacroMap - Map of currently defined macros.
98 StringMap<Macro*> MacroMap;
100 /// ActiveMacros - Stack of active macro instantiations.
101 std::vector<MacroInstantiation*> ActiveMacros;
103 /// Boolean tracking whether macro substitution is enabled.
104 unsigned MacrosEnabled : 1;
106 /// Flag tracking whether any errors have been encountered.
107 unsigned HadError : 1;
110 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
111 const MCAsmInfo &MAI);
114 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
116 void AddDirectiveHandler(MCAsmParserExtension *Object,
118 DirectiveHandler Handler) {
119 DirectiveMap[Directive] = std::make_pair(Object, Handler);
123 /// @name MCAsmParser Interface
126 virtual SourceMgr &getSourceManager() { return SrcMgr; }
127 virtual MCAsmLexer &getLexer() { return Lexer; }
128 virtual MCContext &getContext() { return Ctx; }
129 virtual MCStreamer &getStreamer() { return Out; }
131 virtual void Warning(SMLoc L, const Twine &Meg);
132 virtual bool Error(SMLoc L, const Twine &Msg);
134 const AsmToken &Lex();
136 bool ParseExpression(const MCExpr *&Res);
137 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
138 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
139 virtual bool ParseAbsoluteExpression(int64_t &Res);
144 void CheckForValidSection();
146 bool ParseStatement();
148 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
149 void HandleMacroExit();
151 void PrintMacroInstantiations();
152 void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type) const {
153 SrcMgr.PrintMessage(Loc, Msg, Type);
156 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
157 bool EnterIncludeFile(const std::string &Filename);
159 /// \brief Reset the current lexer position to that given by \arg Loc. The
160 /// current token is not set; clients should ensure Lex() is called
162 void JumpToLoc(SMLoc Loc);
164 void EatToEndOfStatement();
166 /// \brief Parse up to the end of statement and a return the contents from the
167 /// current token until the end of the statement; the current token on exit
168 /// will be either the EndOfStatement or EOF.
169 StringRef ParseStringToEndOfStatement();
171 bool ParseAssignment(StringRef Name, bool allow_redef);
173 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
174 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
175 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
177 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
178 /// and set \arg Res to the identifier contents.
179 bool ParseIdentifier(StringRef &Res);
181 // Directive Parsing.
183 // ".ascii", ".asciiz", ".string"
184 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
185 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
186 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
187 bool ParseDirectiveFill(); // ".fill"
188 bool ParseDirectiveSpace(); // ".space"
189 bool ParseDirectiveZero(); // ".zero"
190 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
191 bool ParseDirectiveOrg(); // ".org"
192 // ".align{,32}", ".p2align{,w,l}"
193 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
195 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
196 /// accepts a single symbol (which should be a label or an external).
197 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
199 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
201 bool ParseDirectiveAbort(); // ".abort"
202 bool ParseDirectiveInclude(); // ".include"
204 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
205 // ".ifdef" or ".ifndef", depending on expect_defined
206 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
207 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
208 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
209 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
211 /// ParseEscapedString - Parse the current token as a string which may include
212 /// escaped characters and return the string contents.
213 bool ParseEscapedString(std::string &Data);
215 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
216 MCSymbolRefExpr::VariantKind Variant);
219 /// \brief Generic implementations of directive handling, etc. which is shared
220 /// (or the default, at least) for all assembler parser.
221 class GenericAsmParser : public MCAsmParserExtension {
222 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
223 void AddDirectiveHandler(StringRef Directive) {
224 getParser().AddDirectiveHandler(this, Directive,
225 HandleDirective<GenericAsmParser, Handler>);
228 GenericAsmParser() {}
230 AsmParser &getParser() {
231 return (AsmParser&) this->MCAsmParserExtension::getParser();
234 virtual void Initialize(MCAsmParser &Parser) {
235 // Call the base implementation.
236 this->MCAsmParserExtension::Initialize(Parser);
238 // Debugging directives.
239 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
240 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
241 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
242 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
245 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
247 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
249 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
251 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
252 ".cfi_def_cfa_offset");
253 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
254 ".cfi_def_cfa_register");
255 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
258 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
260 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
262 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
264 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
267 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
269 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
271 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
272 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
273 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
275 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
276 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
279 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
281 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
282 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
283 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
284 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
285 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
286 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
287 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
288 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
289 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
290 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
291 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
292 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
293 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
295 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
296 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
297 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
299 bool ParseDirectiveLEB128(StringRef, SMLoc);
306 extern MCAsmParserExtension *createDarwinAsmParser();
307 extern MCAsmParserExtension *createELFAsmParser();
308 extern MCAsmParserExtension *createCOFFAsmParser();
312 enum { DEFAULT_ADDRSPACE = 0 };
314 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
315 MCStreamer &_Out, const MCAsmInfo &_MAI)
316 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
317 GenericParser(new GenericAsmParser), PlatformParser(0),
318 CurBuffer(0), MacrosEnabled(true) {
319 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
321 // Initialize the generic parser.
322 GenericParser->Initialize(*this);
324 // Initialize the platform / file format parser.
326 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
328 if (_MAI.hasMicrosoftFastStdCallMangling()) {
329 PlatformParser = createCOFFAsmParser();
330 PlatformParser->Initialize(*this);
331 } else if (_MAI.hasSubsectionsViaSymbols()) {
332 PlatformParser = createDarwinAsmParser();
333 PlatformParser->Initialize(*this);
335 PlatformParser = createELFAsmParser();
336 PlatformParser->Initialize(*this);
340 AsmParser::~AsmParser() {
341 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
343 // Destroy any macros.
344 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
345 ie = MacroMap.end(); it != ie; ++it)
346 delete it->getValue();
348 delete PlatformParser;
349 delete GenericParser;
352 void AsmParser::PrintMacroInstantiations() {
353 // Print the active macro instantiation stack.
354 for (std::vector<MacroInstantiation*>::const_reverse_iterator
355 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
356 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
360 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
361 PrintMessage(L, Msg, "warning");
362 PrintMacroInstantiations();
365 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
367 PrintMessage(L, Msg, "error");
368 PrintMacroInstantiations();
372 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
373 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
379 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
384 void AsmParser::JumpToLoc(SMLoc Loc) {
385 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
386 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
389 const AsmToken &AsmParser::Lex() {
390 const AsmToken *tok = &Lexer.Lex();
392 if (tok->is(AsmToken::Eof)) {
393 // If this is the end of an included file, pop the parent file off the
395 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
396 if (ParentIncludeLoc != SMLoc()) {
397 JumpToLoc(ParentIncludeLoc);
402 if (tok->is(AsmToken::Error))
403 Error(Lexer.getErrLoc(), Lexer.getErr());
408 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
409 // Create the initial section, if requested.
410 if (!NoInitialTextSection)
417 AsmCond StartingCondState = TheCondState;
419 // While we have input, parse each statement.
420 while (Lexer.isNot(AsmToken::Eof)) {
421 if (!ParseStatement()) continue;
423 // We had an error, validate that one was emitted and recover by skipping to
425 assert(HadError && "Parse statement returned an error, but none emitted!");
426 EatToEndOfStatement();
429 if (TheCondState.TheCond != StartingCondState.TheCond ||
430 TheCondState.Ignore != StartingCondState.Ignore)
431 return TokError("unmatched .ifs or .elses");
433 // Check to see there are no empty DwarfFile slots.
434 const std::vector<MCDwarfFile *> &MCDwarfFiles =
435 getContext().getMCDwarfFiles();
436 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
437 if (!MCDwarfFiles[i])
438 TokError("unassigned file number: " + Twine(i) + " for .file directives");
441 // Finalize the output stream if there are no errors and if the client wants
443 if (!HadError && !NoFinalize)
449 void AsmParser::CheckForValidSection() {
450 if (!getStreamer().getCurrentSection()) {
451 TokError("expected section directive before assembly directive");
452 Out.SwitchSection(Ctx.getMachOSection(
454 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
455 0, SectionKind::getText()));
459 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
460 void AsmParser::EatToEndOfStatement() {
461 while (Lexer.isNot(AsmToken::EndOfStatement) &&
462 Lexer.isNot(AsmToken::Eof))
466 if (Lexer.is(AsmToken::EndOfStatement))
470 StringRef AsmParser::ParseStringToEndOfStatement() {
471 const char *Start = getTok().getLoc().getPointer();
473 while (Lexer.isNot(AsmToken::EndOfStatement) &&
474 Lexer.isNot(AsmToken::Eof))
477 const char *End = getTok().getLoc().getPointer();
478 return StringRef(Start, End - Start);
481 /// ParseParenExpr - Parse a paren expression and return it.
482 /// NOTE: This assumes the leading '(' has already been consumed.
484 /// parenexpr ::= expr)
486 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
487 if (ParseExpression(Res)) return true;
488 if (Lexer.isNot(AsmToken::RParen))
489 return TokError("expected ')' in parentheses expression");
490 EndLoc = Lexer.getLoc();
495 /// ParsePrimaryExpr - Parse a primary expression and return it.
496 /// primaryexpr ::= (parenexpr
497 /// primaryexpr ::= symbol
498 /// primaryexpr ::= number
499 /// primaryexpr ::= '.'
500 /// primaryexpr ::= ~,+,- primaryexpr
501 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
502 switch (Lexer.getKind()) {
504 return TokError("unknown token in expression");
505 case AsmToken::Exclaim:
506 Lex(); // Eat the operator.
507 if (ParsePrimaryExpr(Res, EndLoc))
509 Res = MCUnaryExpr::CreateLNot(Res, getContext());
511 case AsmToken::Dollar:
512 case AsmToken::String:
513 case AsmToken::Identifier: {
514 EndLoc = Lexer.getLoc();
516 StringRef Identifier;
517 if (ParseIdentifier(Identifier))
520 // This is a symbol reference.
521 std::pair<StringRef, StringRef> Split = Identifier.split('@');
522 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
524 // Lookup the symbol variant if used.
525 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
526 if (Split.first.size() != Identifier.size()) {
527 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
528 if (Variant == MCSymbolRefExpr::VK_Invalid) {
529 Variant = MCSymbolRefExpr::VK_None;
530 return TokError("invalid variant '" + Split.second + "'");
534 // If this is an absolute variable reference, substitute it now to preserve
535 // semantics in the face of reassignment.
536 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
538 return Error(EndLoc, "unexpected modifier on variable reference");
540 Res = Sym->getVariableValue();
544 // Otherwise create a symbol ref.
545 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
548 case AsmToken::Integer: {
549 SMLoc Loc = getTok().getLoc();
550 int64_t IntVal = getTok().getIntVal();
551 Res = MCConstantExpr::Create(IntVal, getContext());
552 EndLoc = Lexer.getLoc();
554 // Look for 'b' or 'f' following an Integer as a directional label
555 if (Lexer.getKind() == AsmToken::Identifier) {
556 StringRef IDVal = getTok().getString();
557 if (IDVal == "f" || IDVal == "b"){
558 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
559 IDVal == "f" ? 1 : 0);
560 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
562 if(IDVal == "b" && Sym->isUndefined())
563 return Error(Loc, "invalid reference to undefined symbol");
564 EndLoc = Lexer.getLoc();
565 Lex(); // Eat identifier.
570 case AsmToken::Real: {
571 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
572 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
573 Res = MCConstantExpr::Create(IntVal, getContext());
577 case AsmToken::Dot: {
578 // This is a '.' reference, which references the current PC. Emit a
579 // temporary label to the streamer and refer to it.
580 MCSymbol *Sym = Ctx.CreateTempSymbol();
582 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
583 EndLoc = Lexer.getLoc();
584 Lex(); // Eat identifier.
587 case AsmToken::LParen:
588 Lex(); // Eat the '('.
589 return ParseParenExpr(Res, EndLoc);
590 case AsmToken::Minus:
591 Lex(); // Eat the operator.
592 if (ParsePrimaryExpr(Res, EndLoc))
594 Res = MCUnaryExpr::CreateMinus(Res, getContext());
597 Lex(); // Eat the operator.
598 if (ParsePrimaryExpr(Res, EndLoc))
600 Res = MCUnaryExpr::CreatePlus(Res, getContext());
602 case AsmToken::Tilde:
603 Lex(); // Eat the operator.
604 if (ParsePrimaryExpr(Res, EndLoc))
606 Res = MCUnaryExpr::CreateNot(Res, getContext());
611 bool AsmParser::ParseExpression(const MCExpr *&Res) {
613 return ParseExpression(Res, EndLoc);
617 AsmParser::ApplyModifierToExpr(const MCExpr *E,
618 MCSymbolRefExpr::VariantKind Variant) {
619 // Recurse over the given expression, rebuilding it to apply the given variant
620 // if there is exactly one symbol.
621 switch (E->getKind()) {
623 case MCExpr::Constant:
626 case MCExpr::SymbolRef: {
627 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
629 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
630 TokError("invalid variant on expression '" +
631 getTok().getIdentifier() + "' (already modified)");
635 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
638 case MCExpr::Unary: {
639 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
640 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
643 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
646 case MCExpr::Binary: {
647 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
648 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
649 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
654 if (!LHS) LHS = BE->getLHS();
655 if (!RHS) RHS = BE->getRHS();
657 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
661 assert(0 && "Invalid expression kind!");
665 /// ParseExpression - Parse an expression and return it.
667 /// expr ::= expr +,- expr -> lowest.
668 /// expr ::= expr |,^,&,! expr -> middle.
669 /// expr ::= expr *,/,%,<<,>> expr -> highest.
670 /// expr ::= primaryexpr
672 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
673 // Parse the expression.
675 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
678 // As a special case, we support 'a op b @ modifier' by rewriting the
679 // expression to include the modifier. This is inefficient, but in general we
680 // expect users to use 'a@modifier op b'.
681 if (Lexer.getKind() == AsmToken::At) {
684 if (Lexer.isNot(AsmToken::Identifier))
685 return TokError("unexpected symbol modifier following '@'");
687 MCSymbolRefExpr::VariantKind Variant =
688 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
689 if (Variant == MCSymbolRefExpr::VK_Invalid)
690 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
692 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
694 return TokError("invalid modifier '" + getTok().getIdentifier() +
695 "' (no symbols present)");
703 // Try to constant fold it up front, if possible.
705 if (Res->EvaluateAsAbsolute(Value))
706 Res = MCConstantExpr::Create(Value, getContext());
711 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
713 return ParseParenExpr(Res, EndLoc) ||
714 ParseBinOpRHS(1, Res, EndLoc);
717 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
720 SMLoc StartLoc = Lexer.getLoc();
721 if (ParseExpression(Expr))
724 if (!Expr->EvaluateAsAbsolute(Res))
725 return Error(StartLoc, "expected absolute expression");
730 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
731 MCBinaryExpr::Opcode &Kind) {
734 return 0; // not a binop.
736 // Lowest Precedence: &&, ||, @
737 case AsmToken::AmpAmp:
738 Kind = MCBinaryExpr::LAnd;
740 case AsmToken::PipePipe:
741 Kind = MCBinaryExpr::LOr;
745 // Low Precedence: |, &, ^
747 // FIXME: gas seems to support '!' as an infix operator?
749 Kind = MCBinaryExpr::Or;
751 case AsmToken::Caret:
752 Kind = MCBinaryExpr::Xor;
755 Kind = MCBinaryExpr::And;
758 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
759 case AsmToken::EqualEqual:
760 Kind = MCBinaryExpr::EQ;
762 case AsmToken::ExclaimEqual:
763 case AsmToken::LessGreater:
764 Kind = MCBinaryExpr::NE;
767 Kind = MCBinaryExpr::LT;
769 case AsmToken::LessEqual:
770 Kind = MCBinaryExpr::LTE;
772 case AsmToken::Greater:
773 Kind = MCBinaryExpr::GT;
775 case AsmToken::GreaterEqual:
776 Kind = MCBinaryExpr::GTE;
779 // High Intermediate Precedence: +, -
781 Kind = MCBinaryExpr::Add;
783 case AsmToken::Minus:
784 Kind = MCBinaryExpr::Sub;
787 // Highest Precedence: *, /, %, <<, >>
789 Kind = MCBinaryExpr::Mul;
791 case AsmToken::Slash:
792 Kind = MCBinaryExpr::Div;
794 case AsmToken::Percent:
795 Kind = MCBinaryExpr::Mod;
797 case AsmToken::LessLess:
798 Kind = MCBinaryExpr::Shl;
800 case AsmToken::GreaterGreater:
801 Kind = MCBinaryExpr::Shr;
807 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
808 /// Res contains the LHS of the expression on input.
809 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
812 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
813 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
815 // If the next token is lower precedence than we are allowed to eat, return
816 // successfully with what we ate already.
817 if (TokPrec < Precedence)
822 // Eat the next primary expression.
824 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
826 // If BinOp binds less tightly with RHS than the operator after RHS, let
827 // the pending operator take RHS as its LHS.
828 MCBinaryExpr::Opcode Dummy;
829 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
830 if (TokPrec < NextTokPrec) {
831 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
834 // Merge LHS and RHS according to operator.
835 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
843 /// ::= EndOfStatement
844 /// ::= Label* Directive ...Operands... EndOfStatement
845 /// ::= Label* Identifier OperandList* EndOfStatement
846 bool AsmParser::ParseStatement() {
847 if (Lexer.is(AsmToken::EndOfStatement)) {
853 // Statements always start with an identifier or are a full line comment.
854 AsmToken ID = getTok();
855 SMLoc IDLoc = ID.getLoc();
857 int64_t LocalLabelVal = -1;
858 // A full line comment is a '#' as the first token.
859 if (Lexer.is(AsmToken::Hash)) {
860 EatToEndOfStatement();
863 // Allow an integer followed by a ':' as a directional local label.
864 if (Lexer.is(AsmToken::Integer)) {
865 LocalLabelVal = getTok().getIntVal();
866 if (LocalLabelVal < 0) {
867 if (!TheCondState.Ignore)
868 return TokError("unexpected token at start of statement");
872 IDVal = getTok().getString();
873 Lex(); // Consume the integer token to be used as an identifier token.
874 if (Lexer.getKind() != AsmToken::Colon) {
875 if (!TheCondState.Ignore)
876 return TokError("unexpected token at start of statement");
880 else if (ParseIdentifier(IDVal)) {
881 if (!TheCondState.Ignore)
882 return TokError("unexpected token at start of statement");
886 // Handle conditional assembly here before checking for skipping. We
887 // have to do this so that .endif isn't skipped in a ".if 0" block for
890 return ParseDirectiveIf(IDLoc);
891 if (IDVal == ".ifdef")
892 return ParseDirectiveIfdef(IDLoc, true);
893 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
894 return ParseDirectiveIfdef(IDLoc, false);
895 if (IDVal == ".elseif")
896 return ParseDirectiveElseIf(IDLoc);
897 if (IDVal == ".else")
898 return ParseDirectiveElse(IDLoc);
899 if (IDVal == ".endif")
900 return ParseDirectiveEndIf(IDLoc);
902 // If we are in a ".if 0" block, ignore this statement.
903 if (TheCondState.Ignore) {
904 EatToEndOfStatement();
908 // FIXME: Recurse on local labels?
910 // See what kind of statement we have.
911 switch (Lexer.getKind()) {
912 case AsmToken::Colon: {
913 CheckForValidSection();
915 // identifier ':' -> Label.
918 // Diagnose attempt to use a variable as a label.
920 // FIXME: Diagnostics. Note the location of the definition as a label.
921 // FIXME: This doesn't diagnose assignment to a symbol which has been
922 // implicitly marked as external.
924 if (LocalLabelVal == -1)
925 Sym = getContext().GetOrCreateSymbol(IDVal);
927 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
928 if (!Sym->isUndefined() || Sym->isVariable())
929 return Error(IDLoc, "invalid symbol redefinition");
934 // Consume any end of statement token, if present, to avoid spurious
935 // AddBlankLine calls().
936 if (Lexer.is(AsmToken::EndOfStatement)) {
938 if (Lexer.is(AsmToken::Eof))
942 return ParseStatement();
945 case AsmToken::Equal:
946 // identifier '=' ... -> assignment statement
949 return ParseAssignment(IDVal, true);
951 default: // Normal instruction or directive.
955 // If macros are enabled, check to see if this is a macro instantiation.
957 if (const Macro *M = MacroMap.lookup(IDVal))
958 return HandleMacroEntry(IDVal, IDLoc, M);
960 // Otherwise, we have a normal instruction or directive.
961 if (IDVal[0] == '.') {
962 // Assembler features
963 if (IDVal == ".set" || IDVal == ".equ")
964 return ParseDirectiveSet(IDVal, true);
965 if (IDVal == ".equiv")
966 return ParseDirectiveSet(IDVal, false);
970 if (IDVal == ".ascii")
971 return ParseDirectiveAscii(IDVal, false);
972 if (IDVal == ".asciz" || IDVal == ".string")
973 return ParseDirectiveAscii(IDVal, true);
975 if (IDVal == ".byte")
976 return ParseDirectiveValue(1);
977 if (IDVal == ".short")
978 return ParseDirectiveValue(2);
979 if (IDVal == ".value")
980 return ParseDirectiveValue(2);
981 if (IDVal == ".2byte")
982 return ParseDirectiveValue(2);
983 if (IDVal == ".long")
984 return ParseDirectiveValue(4);
986 return ParseDirectiveValue(4);
987 if (IDVal == ".4byte")
988 return ParseDirectiveValue(4);
989 if (IDVal == ".quad")
990 return ParseDirectiveValue(8);
991 if (IDVal == ".8byte")
992 return ParseDirectiveValue(8);
993 if (IDVal == ".single" || IDVal == ".float")
994 return ParseDirectiveRealValue(APFloat::IEEEsingle);
995 if (IDVal == ".double")
996 return ParseDirectiveRealValue(APFloat::IEEEdouble);
998 if (IDVal == ".align") {
999 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1000 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1002 if (IDVal == ".align32") {
1003 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1004 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1006 if (IDVal == ".balign")
1007 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1008 if (IDVal == ".balignw")
1009 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1010 if (IDVal == ".balignl")
1011 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1012 if (IDVal == ".p2align")
1013 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1014 if (IDVal == ".p2alignw")
1015 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1016 if (IDVal == ".p2alignl")
1017 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1019 if (IDVal == ".org")
1020 return ParseDirectiveOrg();
1022 if (IDVal == ".fill")
1023 return ParseDirectiveFill();
1024 if (IDVal == ".space")
1025 return ParseDirectiveSpace();
1026 if (IDVal == ".zero")
1027 return ParseDirectiveZero();
1029 // Symbol attribute directives
1031 if (IDVal == ".globl" || IDVal == ".global")
1032 return ParseDirectiveSymbolAttribute(MCSA_Global);
1033 // ELF only? Should it be here?
1034 if (IDVal == ".local")
1035 return ParseDirectiveSymbolAttribute(MCSA_Local);
1036 if (IDVal == ".hidden")
1037 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1038 if (IDVal == ".indirect_symbol")
1039 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1040 if (IDVal == ".internal")
1041 return ParseDirectiveSymbolAttribute(MCSA_Internal);
1042 if (IDVal == ".lazy_reference")
1043 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1044 if (IDVal == ".no_dead_strip")
1045 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1046 if (IDVal == ".symbol_resolver")
1047 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1048 if (IDVal == ".private_extern")
1049 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1050 if (IDVal == ".protected")
1051 return ParseDirectiveSymbolAttribute(MCSA_Protected);
1052 if (IDVal == ".reference")
1053 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1054 if (IDVal == ".weak")
1055 return ParseDirectiveSymbolAttribute(MCSA_Weak);
1056 if (IDVal == ".weak_definition")
1057 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1058 if (IDVal == ".weak_reference")
1059 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1060 if (IDVal == ".weak_def_can_be_hidden")
1061 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1063 if (IDVal == ".comm")
1064 return ParseDirectiveComm(/*IsLocal=*/false);
1065 if (IDVal == ".lcomm")
1066 return ParseDirectiveComm(/*IsLocal=*/true);
1068 if (IDVal == ".abort")
1069 return ParseDirectiveAbort();
1070 if (IDVal == ".include")
1071 return ParseDirectiveInclude();
1073 if (IDVal == ".code16" || IDVal == ".code32" || IDVal == ".code64")
1074 return TokError(Twine(IDVal) + " not supported yet");
1076 // Look up the handler in the handler table.
1077 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1078 DirectiveMap.lookup(IDVal);
1080 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1082 // Target hook for parsing target specific directives.
1083 if (!getTargetParser().ParseDirective(ID))
1086 Warning(IDLoc, "ignoring directive for now");
1087 EatToEndOfStatement();
1091 CheckForValidSection();
1093 // Canonicalize the opcode to lower case.
1094 SmallString<128> Opcode;
1095 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1096 Opcode.push_back(tolower(IDVal[i]));
1098 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1099 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1102 // Dump the parsed representation, if requested.
1103 if (getShowParsedOperands()) {
1104 SmallString<256> Str;
1105 raw_svector_ostream OS(Str);
1106 OS << "parsed instruction: [";
1107 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1110 ParsedOperands[i]->dump(OS);
1114 PrintMessage(IDLoc, OS.str(), "note");
1117 // If parsing succeeded, match the instruction.
1119 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1122 // Free any parsed operands.
1123 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1124 delete ParsedOperands[i];
1126 // Don't skip the rest of the line, the instruction parser is responsible for
1131 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1132 const std::vector<std::vector<AsmToken> > &A)
1133 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1135 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1136 // to hold the macro body with substitutions.
1137 SmallString<256> Buf;
1138 raw_svector_ostream OS(Buf);
1140 StringRef Body = M->Body;
1141 while (!Body.empty()) {
1142 // Scan for the next substitution.
1143 std::size_t End = Body.size(), Pos = 0;
1144 for (; Pos != End; ++Pos) {
1145 // Check for a substitution or escape.
1146 if (Body[Pos] != '$' || Pos + 1 == End)
1149 char Next = Body[Pos + 1];
1150 if (Next == '$' || Next == 'n' || isdigit(Next))
1155 OS << Body.slice(0, Pos);
1157 // Check if we reached the end.
1161 switch (Body[Pos+1]) {
1167 // $n => number of arguments
1172 // $[0-9] => argument
1174 // Missing arguments are ignored.
1175 unsigned Index = Body[Pos+1] - '0';
1176 if (Index >= A.size())
1179 // Otherwise substitute with the token values, with spaces eliminated.
1180 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1181 ie = A[Index].end(); it != ie; ++it)
1182 OS << it->getString();
1187 // Update the scan point.
1188 Body = Body.substr(Pos + 2);
1191 // We include the .endmacro in the buffer as our queue to exit the macro
1193 OS << ".endmacro\n";
1195 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1198 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1200 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1201 // this, although we should protect against infinite loops.
1202 if (ActiveMacros.size() == 20)
1203 return TokError("macros cannot be nested more than 20 levels deep");
1205 // Parse the macro instantiation arguments.
1206 std::vector<std::vector<AsmToken> > MacroArguments;
1207 MacroArguments.push_back(std::vector<AsmToken>());
1208 unsigned ParenLevel = 0;
1210 if (Lexer.is(AsmToken::Eof))
1211 return TokError("unexpected token in macro instantiation");
1212 if (Lexer.is(AsmToken::EndOfStatement))
1215 // If we aren't inside parentheses and this is a comma, start a new token
1217 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1218 MacroArguments.push_back(std::vector<AsmToken>());
1220 // Adjust the current parentheses level.
1221 if (Lexer.is(AsmToken::LParen))
1223 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1226 // Append the token to the current argument list.
1227 MacroArguments.back().push_back(getTok());
1232 // Create the macro instantiation object and add to the current macro
1233 // instantiation stack.
1234 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1237 ActiveMacros.push_back(MI);
1239 // Jump to the macro instantiation and prime the lexer.
1240 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1241 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1247 void AsmParser::HandleMacroExit() {
1248 // Jump to the EndOfStatement we should return to, and consume it.
1249 JumpToLoc(ActiveMacros.back()->ExitLoc);
1252 // Pop the instantiation entry.
1253 delete ActiveMacros.back();
1254 ActiveMacros.pop_back();
1257 static void MarkUsed(const MCExpr *Value) {
1258 switch (Value->getKind()) {
1259 case MCExpr::Binary:
1260 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1261 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1263 case MCExpr::Target:
1264 case MCExpr::Constant:
1266 case MCExpr::SymbolRef: {
1267 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1271 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1276 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1277 // FIXME: Use better location, we should use proper tokens.
1278 SMLoc EqualLoc = Lexer.getLoc();
1280 const MCExpr *Value;
1281 if (ParseExpression(Value))
1286 if (Lexer.isNot(AsmToken::EndOfStatement))
1287 return TokError("unexpected token in assignment");
1289 // Eat the end of statement marker.
1292 // Validate that the LHS is allowed to be a variable (either it has not been
1293 // used as a symbol, or it is an absolute symbol).
1294 MCSymbol *Sym = getContext().LookupSymbol(Name);
1296 // Diagnose assignment to a label.
1298 // FIXME: Diagnostics. Note the location of the definition as a label.
1299 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1300 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1301 ; // Allow redefinitions of undefined symbols only used in directives.
1302 else if (!Sym->isUndefined() && (!Sym->isAbsolute() || !allow_redef))
1303 return Error(EqualLoc, "redefinition of '" + Name + "'");
1304 else if (!Sym->isVariable())
1305 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1306 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1307 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1310 // Don't count these checks as uses.
1311 Sym->setUsed(false);
1313 Sym = getContext().GetOrCreateSymbol(Name);
1315 // FIXME: Handle '.'.
1317 // Do the assignment.
1318 Out.EmitAssignment(Sym, Value);
1323 /// ParseIdentifier:
1326 bool AsmParser::ParseIdentifier(StringRef &Res) {
1327 // The assembler has relaxed rules for accepting identifiers, in particular we
1328 // allow things like '.globl $foo', which would normally be separate
1329 // tokens. At this level, we have already lexed so we cannot (currently)
1330 // handle this as a context dependent token, instead we detect adjacent tokens
1331 // and return the combined identifier.
1332 if (Lexer.is(AsmToken::Dollar)) {
1333 SMLoc DollarLoc = getLexer().getLoc();
1335 // Consume the dollar sign, and check for a following identifier.
1337 if (Lexer.isNot(AsmToken::Identifier))
1340 // We have a '$' followed by an identifier, make sure they are adjacent.
1341 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1344 // Construct the joined identifier and consume the token.
1345 Res = StringRef(DollarLoc.getPointer(),
1346 getTok().getIdentifier().size() + 1);
1351 if (Lexer.isNot(AsmToken::Identifier) &&
1352 Lexer.isNot(AsmToken::String))
1355 Res = getTok().getIdentifier();
1357 Lex(); // Consume the identifier token.
1362 /// ParseDirectiveSet:
1363 /// ::= .equ identifier ',' expression
1364 /// ::= .equiv identifier ',' expression
1365 /// ::= .set identifier ',' expression
1366 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1369 if (ParseIdentifier(Name))
1370 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1372 if (getLexer().isNot(AsmToken::Comma))
1373 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1376 return ParseAssignment(Name, allow_redef);
1379 bool AsmParser::ParseEscapedString(std::string &Data) {
1380 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1383 StringRef Str = getTok().getStringContents();
1384 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1385 if (Str[i] != '\\') {
1390 // Recognize escaped characters. Note that this escape semantics currently
1391 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1394 return TokError("unexpected backslash at end of string");
1396 // Recognize octal sequences.
1397 if ((unsigned) (Str[i] - '0') <= 7) {
1398 // Consume up to three octal characters.
1399 unsigned Value = Str[i] - '0';
1401 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1403 Value = Value * 8 + (Str[i] - '0');
1405 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1407 Value = Value * 8 + (Str[i] - '0');
1412 return TokError("invalid octal escape sequence (out of range)");
1414 Data += (unsigned char) Value;
1418 // Otherwise recognize individual escapes.
1421 // Just reject invalid escape sequences for now.
1422 return TokError("invalid escape sequence (unrecognized character)");
1424 case 'b': Data += '\b'; break;
1425 case 'f': Data += '\f'; break;
1426 case 'n': Data += '\n'; break;
1427 case 'r': Data += '\r'; break;
1428 case 't': Data += '\t'; break;
1429 case '"': Data += '"'; break;
1430 case '\\': Data += '\\'; break;
1437 /// ParseDirectiveAscii:
1438 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1439 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1440 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1441 CheckForValidSection();
1444 if (getLexer().isNot(AsmToken::String))
1445 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1448 if (ParseEscapedString(Data))
1451 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1453 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1457 if (getLexer().is(AsmToken::EndOfStatement))
1460 if (getLexer().isNot(AsmToken::Comma))
1461 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1470 /// ParseDirectiveValue
1471 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1472 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1473 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1474 CheckForValidSection();
1477 const MCExpr *Value;
1478 if (ParseExpression(Value))
1481 // Special case constant expressions to match code generator.
1482 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1483 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1485 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1487 if (getLexer().is(AsmToken::EndOfStatement))
1490 // FIXME: Improve diagnostic.
1491 if (getLexer().isNot(AsmToken::Comma))
1492 return TokError("unexpected token in directive");
1501 /// ParseDirectiveRealValue
1502 /// ::= (.single | .double) [ expression (, expression)* ]
1503 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1504 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1505 CheckForValidSection();
1508 // We don't truly support arithmetic on floating point expressions, so we
1509 // have to manually parse unary prefixes.
1511 if (getLexer().is(AsmToken::Minus)) {
1514 } else if (getLexer().is(AsmToken::Plus))
1517 if (getLexer().isNot(AsmToken::Integer) &&
1518 getLexer().isNot(AsmToken::Real))
1519 return TokError("unexpected token in directive");
1521 // Convert to an APFloat.
1522 APFloat Value(Semantics);
1523 if (Value.convertFromString(getTok().getString(),
1524 APFloat::rmNearestTiesToEven) ==
1525 APFloat::opInvalidOp)
1526 return TokError("invalid floating point literal");
1530 // Consume the numeric token.
1533 // Emit the value as an integer.
1534 APInt AsInt = Value.bitcastToAPInt();
1535 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1536 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1538 if (getLexer().is(AsmToken::EndOfStatement))
1541 if (getLexer().isNot(AsmToken::Comma))
1542 return TokError("unexpected token in directive");
1551 /// ParseDirectiveSpace
1552 /// ::= .space expression [ , expression ]
1553 bool AsmParser::ParseDirectiveSpace() {
1554 CheckForValidSection();
1557 if (ParseAbsoluteExpression(NumBytes))
1560 int64_t FillExpr = 0;
1561 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1562 if (getLexer().isNot(AsmToken::Comma))
1563 return TokError("unexpected token in '.space' directive");
1566 if (ParseAbsoluteExpression(FillExpr))
1569 if (getLexer().isNot(AsmToken::EndOfStatement))
1570 return TokError("unexpected token in '.space' directive");
1576 return TokError("invalid number of bytes in '.space' directive");
1578 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1579 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1584 /// ParseDirectiveZero
1585 /// ::= .zero expression
1586 bool AsmParser::ParseDirectiveZero() {
1587 CheckForValidSection();
1590 if (ParseAbsoluteExpression(NumBytes))
1594 if (getLexer().is(AsmToken::Comma)) {
1596 if (ParseAbsoluteExpression(Val))
1600 if (getLexer().isNot(AsmToken::EndOfStatement))
1601 return TokError("unexpected token in '.zero' directive");
1605 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1610 /// ParseDirectiveFill
1611 /// ::= .fill expression , expression , expression
1612 bool AsmParser::ParseDirectiveFill() {
1613 CheckForValidSection();
1616 if (ParseAbsoluteExpression(NumValues))
1619 if (getLexer().isNot(AsmToken::Comma))
1620 return TokError("unexpected token in '.fill' directive");
1624 if (ParseAbsoluteExpression(FillSize))
1627 if (getLexer().isNot(AsmToken::Comma))
1628 return TokError("unexpected token in '.fill' directive");
1632 if (ParseAbsoluteExpression(FillExpr))
1635 if (getLexer().isNot(AsmToken::EndOfStatement))
1636 return TokError("unexpected token in '.fill' directive");
1640 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1641 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1643 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1644 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1649 /// ParseDirectiveOrg
1650 /// ::= .org expression [ , expression ]
1651 bool AsmParser::ParseDirectiveOrg() {
1652 CheckForValidSection();
1654 const MCExpr *Offset;
1655 if (ParseExpression(Offset))
1658 // Parse optional fill expression.
1659 int64_t FillExpr = 0;
1660 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1661 if (getLexer().isNot(AsmToken::Comma))
1662 return TokError("unexpected token in '.org' directive");
1665 if (ParseAbsoluteExpression(FillExpr))
1668 if (getLexer().isNot(AsmToken::EndOfStatement))
1669 return TokError("unexpected token in '.org' directive");
1674 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1675 // has to be relative to the current section.
1676 getStreamer().EmitValueToOffset(Offset, FillExpr);
1681 /// ParseDirectiveAlign
1682 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1683 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1684 CheckForValidSection();
1686 SMLoc AlignmentLoc = getLexer().getLoc();
1688 if (ParseAbsoluteExpression(Alignment))
1692 bool HasFillExpr = false;
1693 int64_t FillExpr = 0;
1694 int64_t MaxBytesToFill = 0;
1695 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1696 if (getLexer().isNot(AsmToken::Comma))
1697 return TokError("unexpected token in directive");
1700 // The fill expression can be omitted while specifying a maximum number of
1701 // alignment bytes, e.g:
1703 if (getLexer().isNot(AsmToken::Comma)) {
1705 if (ParseAbsoluteExpression(FillExpr))
1709 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1710 if (getLexer().isNot(AsmToken::Comma))
1711 return TokError("unexpected token in directive");
1714 MaxBytesLoc = getLexer().getLoc();
1715 if (ParseAbsoluteExpression(MaxBytesToFill))
1718 if (getLexer().isNot(AsmToken::EndOfStatement))
1719 return TokError("unexpected token in directive");
1728 // Compute alignment in bytes.
1730 // FIXME: Diagnose overflow.
1731 if (Alignment >= 32) {
1732 Error(AlignmentLoc, "invalid alignment value");
1736 Alignment = 1ULL << Alignment;
1739 // Diagnose non-sensical max bytes to align.
1740 if (MaxBytesLoc.isValid()) {
1741 if (MaxBytesToFill < 1) {
1742 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1743 "many bytes, ignoring maximum bytes expression");
1747 if (MaxBytesToFill >= Alignment) {
1748 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1754 // Check whether we should use optimal code alignment for this .align
1756 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1757 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1758 ValueSize == 1 && UseCodeAlign) {
1759 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1761 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1762 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1769 /// ParseDirectiveSymbolAttribute
1770 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1771 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1772 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1776 if (ParseIdentifier(Name))
1777 return TokError("expected identifier in directive");
1779 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1781 getStreamer().EmitSymbolAttribute(Sym, Attr);
1783 if (getLexer().is(AsmToken::EndOfStatement))
1786 if (getLexer().isNot(AsmToken::Comma))
1787 return TokError("unexpected token in directive");
1796 /// ParseDirectiveComm
1797 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1798 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1799 CheckForValidSection();
1801 SMLoc IDLoc = getLexer().getLoc();
1803 if (ParseIdentifier(Name))
1804 return TokError("expected identifier in directive");
1806 // Handle the identifier as the key symbol.
1807 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1809 if (getLexer().isNot(AsmToken::Comma))
1810 return TokError("unexpected token in directive");
1814 SMLoc SizeLoc = getLexer().getLoc();
1815 if (ParseAbsoluteExpression(Size))
1818 int64_t Pow2Alignment = 0;
1819 SMLoc Pow2AlignmentLoc;
1820 if (getLexer().is(AsmToken::Comma)) {
1822 Pow2AlignmentLoc = getLexer().getLoc();
1823 if (ParseAbsoluteExpression(Pow2Alignment))
1826 // If this target takes alignments in bytes (not log) validate and convert.
1827 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1828 if (!isPowerOf2_64(Pow2Alignment))
1829 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1830 Pow2Alignment = Log2_64(Pow2Alignment);
1834 if (getLexer().isNot(AsmToken::EndOfStatement))
1835 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1839 // NOTE: a size of zero for a .comm should create a undefined symbol
1840 // but a size of .lcomm creates a bss symbol of size zero.
1842 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1843 "be less than zero");
1845 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1846 // may internally end up wanting an alignment in bytes.
1847 // FIXME: Diagnose overflow.
1848 if (Pow2Alignment < 0)
1849 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1850 "alignment, can't be less than zero");
1852 if (!Sym->isUndefined())
1853 return Error(IDLoc, "invalid symbol redefinition");
1855 // '.lcomm' is equivalent to '.zerofill'.
1856 // Create the Symbol as a common or local common with Size and Pow2Alignment
1858 getStreamer().EmitZerofill(Ctx.getMachOSection(
1859 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1860 0, SectionKind::getBSS()),
1861 Sym, Size, 1 << Pow2Alignment);
1865 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1869 /// ParseDirectiveAbort
1870 /// ::= .abort [... message ...]
1871 bool AsmParser::ParseDirectiveAbort() {
1872 // FIXME: Use loc from directive.
1873 SMLoc Loc = getLexer().getLoc();
1875 StringRef Str = ParseStringToEndOfStatement();
1876 if (getLexer().isNot(AsmToken::EndOfStatement))
1877 return TokError("unexpected token in '.abort' directive");
1882 Error(Loc, ".abort detected. Assembly stopping.");
1884 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1885 // FIXME: Actually abort assembly here.
1890 /// ParseDirectiveInclude
1891 /// ::= .include "filename"
1892 bool AsmParser::ParseDirectiveInclude() {
1893 if (getLexer().isNot(AsmToken::String))
1894 return TokError("expected string in '.include' directive");
1896 std::string Filename = getTok().getString();
1897 SMLoc IncludeLoc = getLexer().getLoc();
1900 if (getLexer().isNot(AsmToken::EndOfStatement))
1901 return TokError("unexpected token in '.include' directive");
1903 // Strip the quotes.
1904 Filename = Filename.substr(1, Filename.size()-2);
1906 // Attempt to switch the lexer to the included file before consuming the end
1907 // of statement to avoid losing it when we switch.
1908 if (EnterIncludeFile(Filename)) {
1909 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1916 /// ParseDirectiveIf
1917 /// ::= .if expression
1918 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1919 TheCondStack.push_back(TheCondState);
1920 TheCondState.TheCond = AsmCond::IfCond;
1921 if(TheCondState.Ignore) {
1922 EatToEndOfStatement();
1926 if (ParseAbsoluteExpression(ExprValue))
1929 if (getLexer().isNot(AsmToken::EndOfStatement))
1930 return TokError("unexpected token in '.if' directive");
1934 TheCondState.CondMet = ExprValue;
1935 TheCondState.Ignore = !TheCondState.CondMet;
1941 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
1943 TheCondStack.push_back(TheCondState);
1944 TheCondState.TheCond = AsmCond::IfCond;
1946 if (TheCondState.Ignore) {
1947 EatToEndOfStatement();
1949 if (ParseIdentifier(Name))
1950 return TokError("expected identifier after '.ifdef'");
1954 MCSymbol *Sym = getContext().LookupSymbol(Name);
1957 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
1959 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
1960 TheCondState.Ignore = !TheCondState.CondMet;
1966 /// ParseDirectiveElseIf
1967 /// ::= .elseif expression
1968 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1969 if (TheCondState.TheCond != AsmCond::IfCond &&
1970 TheCondState.TheCond != AsmCond::ElseIfCond)
1971 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1973 TheCondState.TheCond = AsmCond::ElseIfCond;
1975 bool LastIgnoreState = false;
1976 if (!TheCondStack.empty())
1977 LastIgnoreState = TheCondStack.back().Ignore;
1978 if (LastIgnoreState || TheCondState.CondMet) {
1979 TheCondState.Ignore = true;
1980 EatToEndOfStatement();
1984 if (ParseAbsoluteExpression(ExprValue))
1987 if (getLexer().isNot(AsmToken::EndOfStatement))
1988 return TokError("unexpected token in '.elseif' directive");
1991 TheCondState.CondMet = ExprValue;
1992 TheCondState.Ignore = !TheCondState.CondMet;
1998 /// ParseDirectiveElse
2000 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2001 if (getLexer().isNot(AsmToken::EndOfStatement))
2002 return TokError("unexpected token in '.else' directive");
2006 if (TheCondState.TheCond != AsmCond::IfCond &&
2007 TheCondState.TheCond != AsmCond::ElseIfCond)
2008 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2010 TheCondState.TheCond = AsmCond::ElseCond;
2011 bool LastIgnoreState = false;
2012 if (!TheCondStack.empty())
2013 LastIgnoreState = TheCondStack.back().Ignore;
2014 if (LastIgnoreState || TheCondState.CondMet)
2015 TheCondState.Ignore = true;
2017 TheCondState.Ignore = false;
2022 /// ParseDirectiveEndIf
2024 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2025 if (getLexer().isNot(AsmToken::EndOfStatement))
2026 return TokError("unexpected token in '.endif' directive");
2030 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2031 TheCondStack.empty())
2032 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2034 if (!TheCondStack.empty()) {
2035 TheCondState = TheCondStack.back();
2036 TheCondStack.pop_back();
2042 /// ParseDirectiveFile
2043 /// ::= .file [number] string
2044 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2045 // FIXME: I'm not sure what this is.
2046 int64_t FileNumber = -1;
2047 SMLoc FileNumberLoc = getLexer().getLoc();
2048 if (getLexer().is(AsmToken::Integer)) {
2049 FileNumber = getTok().getIntVal();
2053 return TokError("file number less than one");
2056 if (getLexer().isNot(AsmToken::String))
2057 return TokError("unexpected token in '.file' directive");
2059 StringRef Filename = getTok().getString();
2060 Filename = Filename.substr(1, Filename.size()-2);
2063 if (getLexer().isNot(AsmToken::EndOfStatement))
2064 return TokError("unexpected token in '.file' directive");
2066 if (FileNumber == -1)
2067 getStreamer().EmitFileDirective(Filename);
2069 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2070 Error(FileNumberLoc, "file number already allocated");
2076 /// ParseDirectiveLine
2077 /// ::= .line [number]
2078 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2079 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2080 if (getLexer().isNot(AsmToken::Integer))
2081 return TokError("unexpected token in '.line' directive");
2083 int64_t LineNumber = getTok().getIntVal();
2087 // FIXME: Do something with the .line.
2090 if (getLexer().isNot(AsmToken::EndOfStatement))
2091 return TokError("unexpected token in '.line' directive");
2097 /// ParseDirectiveLoc
2098 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2099 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2100 /// The first number is a file number, must have been previously assigned with
2101 /// a .file directive, the second number is the line number and optionally the
2102 /// third number is a column position (zero if not specified). The remaining
2103 /// optional items are .loc sub-directives.
2104 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2106 if (getLexer().isNot(AsmToken::Integer))
2107 return TokError("unexpected token in '.loc' directive");
2108 int64_t FileNumber = getTok().getIntVal();
2110 return TokError("file number less than one in '.loc' directive");
2111 if (!getContext().isValidDwarfFileNumber(FileNumber))
2112 return TokError("unassigned file number in '.loc' directive");
2115 int64_t LineNumber = 0;
2116 if (getLexer().is(AsmToken::Integer)) {
2117 LineNumber = getTok().getIntVal();
2119 return TokError("line number less than one in '.loc' directive");
2123 int64_t ColumnPos = 0;
2124 if (getLexer().is(AsmToken::Integer)) {
2125 ColumnPos = getTok().getIntVal();
2127 return TokError("column position less than zero in '.loc' directive");
2131 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2133 int64_t Discriminator = 0;
2134 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2136 if (getLexer().is(AsmToken::EndOfStatement))
2140 SMLoc Loc = getTok().getLoc();
2141 if (getParser().ParseIdentifier(Name))
2142 return TokError("unexpected token in '.loc' directive");
2144 if (Name == "basic_block")
2145 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2146 else if (Name == "prologue_end")
2147 Flags |= DWARF2_FLAG_PROLOGUE_END;
2148 else if (Name == "epilogue_begin")
2149 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2150 else if (Name == "is_stmt") {
2151 SMLoc Loc = getTok().getLoc();
2152 const MCExpr *Value;
2153 if (getParser().ParseExpression(Value))
2155 // The expression must be the constant 0 or 1.
2156 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2157 int Value = MCE->getValue();
2159 Flags &= ~DWARF2_FLAG_IS_STMT;
2160 else if (Value == 1)
2161 Flags |= DWARF2_FLAG_IS_STMT;
2163 return Error(Loc, "is_stmt value not 0 or 1");
2166 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2169 else if (Name == "isa") {
2170 SMLoc Loc = getTok().getLoc();
2171 const MCExpr *Value;
2172 if (getParser().ParseExpression(Value))
2174 // The expression must be a constant greater or equal to 0.
2175 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2176 int Value = MCE->getValue();
2178 return Error(Loc, "isa number less than zero");
2182 return Error(Loc, "isa number not a constant value");
2185 else if (Name == "discriminator") {
2186 if (getParser().ParseAbsoluteExpression(Discriminator))
2190 return Error(Loc, "unknown sub-directive in '.loc' directive");
2193 if (getLexer().is(AsmToken::EndOfStatement))
2198 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2199 Isa, Discriminator);
2204 /// ParseDirectiveStabs
2205 /// ::= .stabs string, number, number, number
2206 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2207 SMLoc DirectiveLoc) {
2208 return TokError("unsupported directive '" + Directive + "'");
2211 /// ParseDirectiveCFIStartProc
2212 /// ::= .cfi_startproc
2213 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2214 SMLoc DirectiveLoc) {
2215 return getStreamer().EmitCFIStartProc();
2218 /// ParseDirectiveCFIEndProc
2219 /// ::= .cfi_endproc
2220 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2221 return getStreamer().EmitCFIEndProc();
2224 /// ParseRegisterOrRegisterNumber - parse register name or number.
2225 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2226 SMLoc DirectiveLoc) {
2229 if (getLexer().is(AsmToken::Percent)) {
2230 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2233 Register = getContext().getTargetAsmInfo().getDwarfRegNum(RegNo, true);
2235 return getParser().ParseAbsoluteExpression(Register);
2240 /// ParseDirectiveCFIDefCfa
2241 /// ::= .cfi_def_cfa register, offset
2242 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2243 SMLoc DirectiveLoc) {
2244 int64_t Register = 0;
2245 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2248 if (getLexer().isNot(AsmToken::Comma))
2249 return TokError("unexpected token in directive");
2253 if (getParser().ParseAbsoluteExpression(Offset))
2256 return getStreamer().EmitCFIDefCfa(Register, Offset);
2259 /// ParseDirectiveCFIDefCfaOffset
2260 /// ::= .cfi_def_cfa_offset offset
2261 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2262 SMLoc DirectiveLoc) {
2264 if (getParser().ParseAbsoluteExpression(Offset))
2267 return getStreamer().EmitCFIDefCfaOffset(Offset);
2270 /// ParseDirectiveCFIDefCfaRegister
2271 /// ::= .cfi_def_cfa_register register
2272 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2273 SMLoc DirectiveLoc) {
2274 int64_t Register = 0;
2275 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2278 return getStreamer().EmitCFIDefCfaRegister(Register);
2281 /// ParseDirectiveCFIOffset
2282 /// ::= .cfi_off register, offset
2283 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2284 int64_t Register = 0;
2287 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2290 if (getLexer().isNot(AsmToken::Comma))
2291 return TokError("unexpected token in directive");
2294 if (getParser().ParseAbsoluteExpression(Offset))
2297 return getStreamer().EmitCFIOffset(Register, Offset);
2300 static bool isValidEncoding(int64_t Encoding) {
2301 if (Encoding & ~0xff)
2304 if (Encoding == dwarf::DW_EH_PE_omit)
2307 const unsigned Format = Encoding & 0xf;
2308 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2309 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2310 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2311 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2314 const unsigned Application = Encoding & 0x70;
2315 if (Application != dwarf::DW_EH_PE_absptr &&
2316 Application != dwarf::DW_EH_PE_pcrel)
2322 /// ParseDirectiveCFIPersonalityOrLsda
2323 /// ::= .cfi_personality encoding, [symbol_name]
2324 /// ::= .cfi_lsda encoding, [symbol_name]
2325 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2326 SMLoc DirectiveLoc) {
2327 int64_t Encoding = 0;
2328 if (getParser().ParseAbsoluteExpression(Encoding))
2330 if (Encoding == dwarf::DW_EH_PE_omit)
2333 if (!isValidEncoding(Encoding))
2334 return TokError("unsupported encoding.");
2336 if (getLexer().isNot(AsmToken::Comma))
2337 return TokError("unexpected token in directive");
2341 if (getParser().ParseIdentifier(Name))
2342 return TokError("expected identifier in directive");
2344 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2346 if (IDVal == ".cfi_personality")
2347 return getStreamer().EmitCFIPersonality(Sym, Encoding);
2349 assert(IDVal == ".cfi_lsda");
2350 return getStreamer().EmitCFILsda(Sym, Encoding);
2354 /// ParseDirectiveCFIRememberState
2355 /// ::= .cfi_remember_state
2356 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2357 SMLoc DirectiveLoc) {
2358 return getStreamer().EmitCFIRememberState();
2361 /// ParseDirectiveCFIRestoreState
2362 /// ::= .cfi_remember_state
2363 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2364 SMLoc DirectiveLoc) {
2365 return getStreamer().EmitCFIRestoreState();
2368 /// ParseDirectiveMacrosOnOff
2371 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2372 SMLoc DirectiveLoc) {
2373 if (getLexer().isNot(AsmToken::EndOfStatement))
2374 return Error(getLexer().getLoc(),
2375 "unexpected token in '" + Directive + "' directive");
2377 getParser().MacrosEnabled = Directive == ".macros_on";
2382 /// ParseDirectiveMacro
2384 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2385 SMLoc DirectiveLoc) {
2387 if (getParser().ParseIdentifier(Name))
2388 return TokError("expected identifier in directive");
2390 if (getLexer().isNot(AsmToken::EndOfStatement))
2391 return TokError("unexpected token in '.macro' directive");
2393 // Eat the end of statement.
2396 AsmToken EndToken, StartToken = getTok();
2398 // Lex the macro definition.
2400 // Check whether we have reached the end of the file.
2401 if (getLexer().is(AsmToken::Eof))
2402 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2404 // Otherwise, check whether we have reach the .endmacro.
2405 if (getLexer().is(AsmToken::Identifier) &&
2406 (getTok().getIdentifier() == ".endm" ||
2407 getTok().getIdentifier() == ".endmacro")) {
2408 EndToken = getTok();
2410 if (getLexer().isNot(AsmToken::EndOfStatement))
2411 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2416 // Otherwise, scan til the end of the statement.
2417 getParser().EatToEndOfStatement();
2420 if (getParser().MacroMap.lookup(Name)) {
2421 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2424 const char *BodyStart = StartToken.getLoc().getPointer();
2425 const char *BodyEnd = EndToken.getLoc().getPointer();
2426 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2427 getParser().MacroMap[Name] = new Macro(Name, Body);
2431 /// ParseDirectiveEndMacro
2434 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2435 SMLoc DirectiveLoc) {
2436 if (getLexer().isNot(AsmToken::EndOfStatement))
2437 return TokError("unexpected token in '" + Directive + "' directive");
2439 // If we are inside a macro instantiation, terminate the current
2441 if (!getParser().ActiveMacros.empty()) {
2442 getParser().HandleMacroExit();
2446 // Otherwise, this .endmacro is a stray entry in the file; well formed
2447 // .endmacro directives are handled during the macro definition parsing.
2448 return TokError("unexpected '" + Directive + "' in file, "
2449 "no current macro definition");
2452 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2453 getParser().CheckForValidSection();
2455 const MCExpr *Value;
2457 if (getParser().ParseExpression(Value))
2460 if (getLexer().isNot(AsmToken::EndOfStatement))
2461 return TokError("unexpected token in directive");
2463 if (DirName[1] == 's')
2464 getStreamer().EmitSLEB128Value(Value);
2466 getStreamer().EmitULEB128Value(Value);
2472 /// \brief Create an MCAsmParser instance.
2473 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2474 MCContext &C, MCStreamer &Out,
2475 const MCAsmInfo &MAI) {
2476 return new AsmParser(T, SM, C, Out, MAI);