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/MCRegisterInfo.h"
27 #include "llvm/MC/MCSectionMachO.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/MC/MCDwarf.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/SourceMgr.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetAsmInfo.h"
37 #include "llvm/Target/TargetAsmParser.h"
43 FatalAssemblerWarnings("fatal-assembler-warnings",
44 cl::desc("Consider warnings as error"));
48 /// \brief Helper class for tracking macro definitions.
52 std::vector<StringRef> Parameters;
55 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
56 Name(N), Body(B), Parameters(P) {}
59 /// \brief Helper class for storing information about an active macro
61 struct MacroInstantiation {
62 /// The macro being instantiated.
63 const Macro *TheMacro;
65 /// The macro instantiation with substitutions.
66 MemoryBuffer *Instantiation;
68 /// The location of the instantiation.
69 SMLoc InstantiationLoc;
71 /// The location where parsing should resume upon instantiation completion.
75 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
79 /// \brief The concrete assembly parser instance.
80 class AsmParser : public MCAsmParser {
81 friend class GenericAsmParser;
83 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
84 void operator=(const AsmParser &); // DO NOT IMPLEMENT
91 MCAsmParserExtension *GenericParser;
92 MCAsmParserExtension *PlatformParser;
94 /// This is the current buffer index we're lexing from as managed by the
99 std::vector<AsmCond> TheCondStack;
101 /// DirectiveMap - This is a table handlers for directives. Each handler is
102 /// invoked after the directive identifier is read and is responsible for
103 /// parsing and validating the rest of the directive. The handler is passed
104 /// in the directive name and the location of the directive keyword.
105 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
107 /// MacroMap - Map of currently defined macros.
108 StringMap<Macro*> MacroMap;
110 /// ActiveMacros - Stack of active macro instantiations.
111 std::vector<MacroInstantiation*> ActiveMacros;
113 /// Boolean tracking whether macro substitution is enabled.
114 unsigned MacrosEnabled : 1;
116 /// Flag tracking whether any errors have been encountered.
117 unsigned HadError : 1;
120 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
121 const MCAsmInfo &MAI);
124 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
126 void AddDirectiveHandler(MCAsmParserExtension *Object,
128 DirectiveHandler Handler) {
129 DirectiveMap[Directive] = std::make_pair(Object, Handler);
133 /// @name MCAsmParser Interface
136 virtual SourceMgr &getSourceManager() { return SrcMgr; }
137 virtual MCAsmLexer &getLexer() { return Lexer; }
138 virtual MCContext &getContext() { return Ctx; }
139 virtual MCStreamer &getStreamer() { return Out; }
141 virtual bool Warning(SMLoc L, const Twine &Msg);
142 virtual bool Error(SMLoc L, const Twine &Msg);
144 const AsmToken &Lex();
146 bool ParseExpression(const MCExpr *&Res);
147 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
148 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
149 virtual bool ParseAbsoluteExpression(int64_t &Res);
154 void CheckForValidSection();
156 bool ParseStatement();
158 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
159 bool expandMacro(SmallString<256> &Buf, StringRef Body,
160 const std::vector<StringRef> &Parameters,
161 const std::vector<std::vector<AsmToken> > &A,
163 void HandleMacroExit();
165 void PrintMacroInstantiations();
166 void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type,
167 bool ShowLine = true) const {
168 SrcMgr.PrintMessage(Loc, Msg, Type, ShowLine);
171 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
172 bool EnterIncludeFile(const std::string &Filename);
174 /// \brief Reset the current lexer position to that given by \arg Loc. The
175 /// current token is not set; clients should ensure Lex() is called
177 void JumpToLoc(SMLoc Loc);
179 void EatToEndOfStatement();
181 /// \brief Parse up to the end of statement and a return the contents from the
182 /// current token until the end of the statement; the current token on exit
183 /// will be either the EndOfStatement or EOF.
184 StringRef ParseStringToEndOfStatement();
186 bool ParseAssignment(StringRef Name, bool allow_redef);
188 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
189 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
190 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
191 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
193 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
194 /// and set \arg Res to the identifier contents.
195 bool ParseIdentifier(StringRef &Res);
197 // Directive Parsing.
199 // ".ascii", ".asciiz", ".string"
200 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
201 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
202 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
203 bool ParseDirectiveFill(); // ".fill"
204 bool ParseDirectiveSpace(); // ".space"
205 bool ParseDirectiveZero(); // ".zero"
206 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
207 bool ParseDirectiveOrg(); // ".org"
208 // ".align{,32}", ".p2align{,w,l}"
209 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
211 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
212 /// accepts a single symbol (which should be a label or an external).
213 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
215 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
217 bool ParseDirectiveAbort(); // ".abort"
218 bool ParseDirectiveInclude(); // ".include"
220 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
221 // ".ifdef" or ".ifndef", depending on expect_defined
222 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
223 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
224 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
225 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
227 /// ParseEscapedString - Parse the current token as a string which may include
228 /// escaped characters and return the string contents.
229 bool ParseEscapedString(std::string &Data);
231 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
232 MCSymbolRefExpr::VariantKind Variant);
235 /// \brief Generic implementations of directive handling, etc. which is shared
236 /// (or the default, at least) for all assembler parser.
237 class GenericAsmParser : public MCAsmParserExtension {
238 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
239 void AddDirectiveHandler(StringRef Directive) {
240 getParser().AddDirectiveHandler(this, Directive,
241 HandleDirective<GenericAsmParser, Handler>);
244 GenericAsmParser() {}
246 AsmParser &getParser() {
247 return (AsmParser&) this->MCAsmParserExtension::getParser();
250 virtual void Initialize(MCAsmParser &Parser) {
251 // Call the base implementation.
252 this->MCAsmParserExtension::Initialize(Parser);
254 // Debugging directives.
255 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
256 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
257 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
258 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
261 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
263 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
265 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
267 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
269 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
270 ".cfi_def_cfa_offset");
271 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
272 ".cfi_adjust_cfa_offset");
273 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
274 ".cfi_def_cfa_register");
275 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
277 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
280 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
282 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
284 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
286 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
288 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
291 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
293 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
295 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
296 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
297 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
299 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
300 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
303 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
305 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
306 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
307 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
308 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
309 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
310 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
311 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
312 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
313 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
314 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
315 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
316 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
317 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
318 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
319 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
320 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
321 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
323 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
324 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
325 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
327 bool ParseDirectiveLEB128(StringRef, SMLoc);
334 extern MCAsmParserExtension *createDarwinAsmParser();
335 extern MCAsmParserExtension *createELFAsmParser();
336 extern MCAsmParserExtension *createCOFFAsmParser();
340 enum { DEFAULT_ADDRSPACE = 0 };
342 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
343 MCStreamer &_Out, const MCAsmInfo &_MAI)
344 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
345 GenericParser(new GenericAsmParser), PlatformParser(0),
346 CurBuffer(0), MacrosEnabled(true) {
347 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
349 // Initialize the generic parser.
350 GenericParser->Initialize(*this);
352 // Initialize the platform / file format parser.
354 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
356 if (_MAI.hasMicrosoftFastStdCallMangling()) {
357 PlatformParser = createCOFFAsmParser();
358 PlatformParser->Initialize(*this);
359 } else if (_MAI.hasSubsectionsViaSymbols()) {
360 PlatformParser = createDarwinAsmParser();
361 PlatformParser->Initialize(*this);
363 PlatformParser = createELFAsmParser();
364 PlatformParser->Initialize(*this);
368 AsmParser::~AsmParser() {
369 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
371 // Destroy any macros.
372 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
373 ie = MacroMap.end(); it != ie; ++it)
374 delete it->getValue();
376 delete PlatformParser;
377 delete GenericParser;
380 void AsmParser::PrintMacroInstantiations() {
381 // Print the active macro instantiation stack.
382 for (std::vector<MacroInstantiation*>::const_reverse_iterator
383 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
384 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
388 bool AsmParser::Warning(SMLoc L, const Twine &Msg) {
389 if (FatalAssemblerWarnings)
390 return Error(L, Msg);
391 PrintMessage(L, Msg, "warning");
392 PrintMacroInstantiations();
396 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
398 PrintMessage(L, Msg, "error");
399 PrintMacroInstantiations();
403 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
404 std::string IncludedFile;
405 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
411 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
416 void AsmParser::JumpToLoc(SMLoc Loc) {
417 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
418 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
421 const AsmToken &AsmParser::Lex() {
422 const AsmToken *tok = &Lexer.Lex();
424 if (tok->is(AsmToken::Eof)) {
425 // If this is the end of an included file, pop the parent file off the
427 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
428 if (ParentIncludeLoc != SMLoc()) {
429 JumpToLoc(ParentIncludeLoc);
434 if (tok->is(AsmToken::Error))
435 Error(Lexer.getErrLoc(), Lexer.getErr());
440 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
441 // Create the initial section, if requested.
442 if (!NoInitialTextSection)
449 AsmCond StartingCondState = TheCondState;
451 // While we have input, parse each statement.
452 while (Lexer.isNot(AsmToken::Eof)) {
453 if (!ParseStatement()) continue;
455 // We had an error, validate that one was emitted and recover by skipping to
457 assert(HadError && "Parse statement returned an error, but none emitted!");
458 EatToEndOfStatement();
461 if (TheCondState.TheCond != StartingCondState.TheCond ||
462 TheCondState.Ignore != StartingCondState.Ignore)
463 return TokError("unmatched .ifs or .elses");
465 // Check to see there are no empty DwarfFile slots.
466 const std::vector<MCDwarfFile *> &MCDwarfFiles =
467 getContext().getMCDwarfFiles();
468 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
469 if (!MCDwarfFiles[i])
470 TokError("unassigned file number: " + Twine(i) + " for .file directives");
473 // Check to see that all assembler local symbols were actually defined.
474 // Targets that don't do subsections via symbols may not want this, though,
475 // so conservatively exclude them. Only do this if we're finalizing, though,
476 // as otherwise we won't necessarilly have seen everything yet.
477 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
478 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
479 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
482 MCSymbol *Sym = i->getValue();
483 // Variable symbols may not be marked as defined, so check those
484 // explicitly. If we know it's a variable, we have a definition for
485 // the purposes of this check.
486 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
487 // FIXME: We would really like to refer back to where the symbol was
488 // first referenced for a source location. We need to add something
489 // to track that. Currently, we just point to the end of the file.
490 PrintMessage(getLexer().getLoc(), "assembler local symbol '" +
491 Sym->getName() + "' not defined", "error", false);
496 // Finalize the output stream if there are no errors and if the client wants
498 if (!HadError && !NoFinalize)
504 void AsmParser::CheckForValidSection() {
505 if (!getStreamer().getCurrentSection()) {
506 TokError("expected section directive before assembly directive");
507 Out.SwitchSection(Ctx.getMachOSection(
509 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
510 0, SectionKind::getText()));
514 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
515 void AsmParser::EatToEndOfStatement() {
516 while (Lexer.isNot(AsmToken::EndOfStatement) &&
517 Lexer.isNot(AsmToken::Eof))
521 if (Lexer.is(AsmToken::EndOfStatement))
525 StringRef AsmParser::ParseStringToEndOfStatement() {
526 const char *Start = getTok().getLoc().getPointer();
528 while (Lexer.isNot(AsmToken::EndOfStatement) &&
529 Lexer.isNot(AsmToken::Eof))
532 const char *End = getTok().getLoc().getPointer();
533 return StringRef(Start, End - Start);
536 /// ParseParenExpr - Parse a paren expression and return it.
537 /// NOTE: This assumes the leading '(' has already been consumed.
539 /// parenexpr ::= expr)
541 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
542 if (ParseExpression(Res)) return true;
543 if (Lexer.isNot(AsmToken::RParen))
544 return TokError("expected ')' in parentheses expression");
545 EndLoc = Lexer.getLoc();
550 /// ParseBracketExpr - Parse a bracket expression and return it.
551 /// NOTE: This assumes the leading '[' has already been consumed.
553 /// bracketexpr ::= expr]
555 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
556 if (ParseExpression(Res)) return true;
557 if (Lexer.isNot(AsmToken::RBrac))
558 return TokError("expected ']' in brackets expression");
559 EndLoc = Lexer.getLoc();
564 /// ParsePrimaryExpr - Parse a primary expression and return it.
565 /// primaryexpr ::= (parenexpr
566 /// primaryexpr ::= symbol
567 /// primaryexpr ::= number
568 /// primaryexpr ::= '.'
569 /// primaryexpr ::= ~,+,- primaryexpr
570 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
571 switch (Lexer.getKind()) {
573 return TokError("unknown token in expression");
574 // If we have an error assume that we've already handled it.
575 case AsmToken::Error:
577 case AsmToken::Exclaim:
578 Lex(); // Eat the operator.
579 if (ParsePrimaryExpr(Res, EndLoc))
581 Res = MCUnaryExpr::CreateLNot(Res, getContext());
583 case AsmToken::Dollar:
584 case AsmToken::String:
585 case AsmToken::Identifier: {
586 EndLoc = Lexer.getLoc();
588 StringRef Identifier;
589 if (ParseIdentifier(Identifier))
592 // This is a symbol reference.
593 std::pair<StringRef, StringRef> Split = Identifier.split('@');
594 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
596 // Lookup the symbol variant if used.
597 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
598 if (Split.first.size() != Identifier.size()) {
599 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
600 if (Variant == MCSymbolRefExpr::VK_Invalid) {
601 Variant = MCSymbolRefExpr::VK_None;
602 return TokError("invalid variant '" + Split.second + "'");
606 // If this is an absolute variable reference, substitute it now to preserve
607 // semantics in the face of reassignment.
608 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
610 return Error(EndLoc, "unexpected modifier on variable reference");
612 Res = Sym->getVariableValue();
616 // Otherwise create a symbol ref.
617 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
620 case AsmToken::Integer: {
621 SMLoc Loc = getTok().getLoc();
622 int64_t IntVal = getTok().getIntVal();
623 Res = MCConstantExpr::Create(IntVal, getContext());
624 EndLoc = Lexer.getLoc();
626 // Look for 'b' or 'f' following an Integer as a directional label
627 if (Lexer.getKind() == AsmToken::Identifier) {
628 StringRef IDVal = getTok().getString();
629 if (IDVal == "f" || IDVal == "b"){
630 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
631 IDVal == "f" ? 1 : 0);
632 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
634 if(IDVal == "b" && Sym->isUndefined())
635 return Error(Loc, "invalid reference to undefined symbol");
636 EndLoc = Lexer.getLoc();
637 Lex(); // Eat identifier.
642 case AsmToken::Real: {
643 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
644 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
645 Res = MCConstantExpr::Create(IntVal, getContext());
649 case AsmToken::Dot: {
650 // This is a '.' reference, which references the current PC. Emit a
651 // temporary label to the streamer and refer to it.
652 MCSymbol *Sym = Ctx.CreateTempSymbol();
654 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
655 EndLoc = Lexer.getLoc();
656 Lex(); // Eat identifier.
659 case AsmToken::LParen:
660 Lex(); // Eat the '('.
661 return ParseParenExpr(Res, EndLoc);
662 case AsmToken::LBrac:
663 if (!PlatformParser->HasBracketExpressions())
664 return TokError("brackets expression not supported on this target");
665 Lex(); // Eat the '['.
666 return ParseBracketExpr(Res, EndLoc);
667 case AsmToken::Minus:
668 Lex(); // Eat the operator.
669 if (ParsePrimaryExpr(Res, EndLoc))
671 Res = MCUnaryExpr::CreateMinus(Res, getContext());
674 Lex(); // Eat the operator.
675 if (ParsePrimaryExpr(Res, EndLoc))
677 Res = MCUnaryExpr::CreatePlus(Res, getContext());
679 case AsmToken::Tilde:
680 Lex(); // Eat the operator.
681 if (ParsePrimaryExpr(Res, EndLoc))
683 Res = MCUnaryExpr::CreateNot(Res, getContext());
688 bool AsmParser::ParseExpression(const MCExpr *&Res) {
690 return ParseExpression(Res, EndLoc);
694 AsmParser::ApplyModifierToExpr(const MCExpr *E,
695 MCSymbolRefExpr::VariantKind Variant) {
696 // Recurse over the given expression, rebuilding it to apply the given variant
697 // if there is exactly one symbol.
698 switch (E->getKind()) {
700 case MCExpr::Constant:
703 case MCExpr::SymbolRef: {
704 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
706 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
707 TokError("invalid variant on expression '" +
708 getTok().getIdentifier() + "' (already modified)");
712 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
715 case MCExpr::Unary: {
716 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
717 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
720 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
723 case MCExpr::Binary: {
724 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
725 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
726 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
731 if (!LHS) LHS = BE->getLHS();
732 if (!RHS) RHS = BE->getRHS();
734 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
738 assert(0 && "Invalid expression kind!");
742 /// ParseExpression - Parse an expression and return it.
744 /// expr ::= expr +,- expr -> lowest.
745 /// expr ::= expr |,^,&,! expr -> middle.
746 /// expr ::= expr *,/,%,<<,>> expr -> highest.
747 /// expr ::= primaryexpr
749 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
750 // Parse the expression.
752 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
755 // As a special case, we support 'a op b @ modifier' by rewriting the
756 // expression to include the modifier. This is inefficient, but in general we
757 // expect users to use 'a@modifier op b'.
758 if (Lexer.getKind() == AsmToken::At) {
761 if (Lexer.isNot(AsmToken::Identifier))
762 return TokError("unexpected symbol modifier following '@'");
764 MCSymbolRefExpr::VariantKind Variant =
765 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
766 if (Variant == MCSymbolRefExpr::VK_Invalid)
767 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
769 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
771 return TokError("invalid modifier '" + getTok().getIdentifier() +
772 "' (no symbols present)");
780 // Try to constant fold it up front, if possible.
782 if (Res->EvaluateAsAbsolute(Value))
783 Res = MCConstantExpr::Create(Value, getContext());
788 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
790 return ParseParenExpr(Res, EndLoc) ||
791 ParseBinOpRHS(1, Res, EndLoc);
794 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
797 SMLoc StartLoc = Lexer.getLoc();
798 if (ParseExpression(Expr))
801 if (!Expr->EvaluateAsAbsolute(Res))
802 return Error(StartLoc, "expected absolute expression");
807 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
808 MCBinaryExpr::Opcode &Kind) {
811 return 0; // not a binop.
813 // Lowest Precedence: &&, ||, @
814 case AsmToken::AmpAmp:
815 Kind = MCBinaryExpr::LAnd;
817 case AsmToken::PipePipe:
818 Kind = MCBinaryExpr::LOr;
822 // Low Precedence: |, &, ^
824 // FIXME: gas seems to support '!' as an infix operator?
826 Kind = MCBinaryExpr::Or;
828 case AsmToken::Caret:
829 Kind = MCBinaryExpr::Xor;
832 Kind = MCBinaryExpr::And;
835 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
836 case AsmToken::EqualEqual:
837 Kind = MCBinaryExpr::EQ;
839 case AsmToken::ExclaimEqual:
840 case AsmToken::LessGreater:
841 Kind = MCBinaryExpr::NE;
844 Kind = MCBinaryExpr::LT;
846 case AsmToken::LessEqual:
847 Kind = MCBinaryExpr::LTE;
849 case AsmToken::Greater:
850 Kind = MCBinaryExpr::GT;
852 case AsmToken::GreaterEqual:
853 Kind = MCBinaryExpr::GTE;
856 // High Intermediate Precedence: +, -
858 Kind = MCBinaryExpr::Add;
860 case AsmToken::Minus:
861 Kind = MCBinaryExpr::Sub;
864 // Highest Precedence: *, /, %, <<, >>
866 Kind = MCBinaryExpr::Mul;
868 case AsmToken::Slash:
869 Kind = MCBinaryExpr::Div;
871 case AsmToken::Percent:
872 Kind = MCBinaryExpr::Mod;
874 case AsmToken::LessLess:
875 Kind = MCBinaryExpr::Shl;
877 case AsmToken::GreaterGreater:
878 Kind = MCBinaryExpr::Shr;
884 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
885 /// Res contains the LHS of the expression on input.
886 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
889 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
890 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
892 // If the next token is lower precedence than we are allowed to eat, return
893 // successfully with what we ate already.
894 if (TokPrec < Precedence)
899 // Eat the next primary expression.
901 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
903 // If BinOp binds less tightly with RHS than the operator after RHS, let
904 // the pending operator take RHS as its LHS.
905 MCBinaryExpr::Opcode Dummy;
906 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
907 if (TokPrec < NextTokPrec) {
908 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
911 // Merge LHS and RHS according to operator.
912 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
920 /// ::= EndOfStatement
921 /// ::= Label* Directive ...Operands... EndOfStatement
922 /// ::= Label* Identifier OperandList* EndOfStatement
923 bool AsmParser::ParseStatement() {
924 if (Lexer.is(AsmToken::EndOfStatement)) {
930 // Statements always start with an identifier or are a full line comment.
931 AsmToken ID = getTok();
932 SMLoc IDLoc = ID.getLoc();
934 int64_t LocalLabelVal = -1;
935 // A full line comment is a '#' as the first token.
936 if (Lexer.is(AsmToken::Hash)) {
937 EatToEndOfStatement();
941 // Allow an integer followed by a ':' as a directional local label.
942 if (Lexer.is(AsmToken::Integer)) {
943 LocalLabelVal = getTok().getIntVal();
944 if (LocalLabelVal < 0) {
945 if (!TheCondState.Ignore)
946 return TokError("unexpected token at start of statement");
950 IDVal = getTok().getString();
951 Lex(); // Consume the integer token to be used as an identifier token.
952 if (Lexer.getKind() != AsmToken::Colon) {
953 if (!TheCondState.Ignore)
954 return TokError("unexpected token at start of statement");
958 } else if (Lexer.is(AsmToken::Dot)) {
959 // Treat '.' as a valid identifier in this context.
963 } else if (ParseIdentifier(IDVal)) {
964 if (!TheCondState.Ignore)
965 return TokError("unexpected token at start of statement");
970 // Handle conditional assembly here before checking for skipping. We
971 // have to do this so that .endif isn't skipped in a ".if 0" block for
974 return ParseDirectiveIf(IDLoc);
975 if (IDVal == ".ifdef")
976 return ParseDirectiveIfdef(IDLoc, true);
977 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
978 return ParseDirectiveIfdef(IDLoc, false);
979 if (IDVal == ".elseif")
980 return ParseDirectiveElseIf(IDLoc);
981 if (IDVal == ".else")
982 return ParseDirectiveElse(IDLoc);
983 if (IDVal == ".endif")
984 return ParseDirectiveEndIf(IDLoc);
986 // If we are in a ".if 0" block, ignore this statement.
987 if (TheCondState.Ignore) {
988 EatToEndOfStatement();
992 // FIXME: Recurse on local labels?
994 // See what kind of statement we have.
995 switch (Lexer.getKind()) {
996 case AsmToken::Colon: {
997 CheckForValidSection();
999 // identifier ':' -> Label.
1002 // Diagnose attempt to use '.' as a label.
1004 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1006 // Diagnose attempt to use a variable as a label.
1008 // FIXME: Diagnostics. Note the location of the definition as a label.
1009 // FIXME: This doesn't diagnose assignment to a symbol which has been
1010 // implicitly marked as external.
1012 if (LocalLabelVal == -1)
1013 Sym = getContext().GetOrCreateSymbol(IDVal);
1015 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1016 if (!Sym->isUndefined() || Sym->isVariable())
1017 return Error(IDLoc, "invalid symbol redefinition");
1022 // Consume any end of statement token, if present, to avoid spurious
1023 // AddBlankLine calls().
1024 if (Lexer.is(AsmToken::EndOfStatement)) {
1026 if (Lexer.is(AsmToken::Eof))
1030 return ParseStatement();
1033 case AsmToken::Equal:
1034 // identifier '=' ... -> assignment statement
1037 return ParseAssignment(IDVal, true);
1039 default: // Normal instruction or directive.
1043 // If macros are enabled, check to see if this is a macro instantiation.
1045 if (const Macro *M = MacroMap.lookup(IDVal))
1046 return HandleMacroEntry(IDVal, IDLoc, M);
1048 // Otherwise, we have a normal instruction or directive.
1049 if (IDVal[0] == '.' && IDVal != ".") {
1050 // Assembler features
1051 if (IDVal == ".set" || IDVal == ".equ")
1052 return ParseDirectiveSet(IDVal, true);
1053 if (IDVal == ".equiv")
1054 return ParseDirectiveSet(IDVal, false);
1058 if (IDVal == ".ascii")
1059 return ParseDirectiveAscii(IDVal, false);
1060 if (IDVal == ".asciz" || IDVal == ".string")
1061 return ParseDirectiveAscii(IDVal, true);
1063 if (IDVal == ".byte")
1064 return ParseDirectiveValue(1);
1065 if (IDVal == ".short")
1066 return ParseDirectiveValue(2);
1067 if (IDVal == ".value")
1068 return ParseDirectiveValue(2);
1069 if (IDVal == ".2byte")
1070 return ParseDirectiveValue(2);
1071 if (IDVal == ".long")
1072 return ParseDirectiveValue(4);
1073 if (IDVal == ".int")
1074 return ParseDirectiveValue(4);
1075 if (IDVal == ".4byte")
1076 return ParseDirectiveValue(4);
1077 if (IDVal == ".quad")
1078 return ParseDirectiveValue(8);
1079 if (IDVal == ".8byte")
1080 return ParseDirectiveValue(8);
1081 if (IDVal == ".single" || IDVal == ".float")
1082 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1083 if (IDVal == ".double")
1084 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1086 if (IDVal == ".align") {
1087 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1088 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1090 if (IDVal == ".align32") {
1091 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1092 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1094 if (IDVal == ".balign")
1095 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1096 if (IDVal == ".balignw")
1097 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1098 if (IDVal == ".balignl")
1099 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1100 if (IDVal == ".p2align")
1101 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1102 if (IDVal == ".p2alignw")
1103 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1104 if (IDVal == ".p2alignl")
1105 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1107 if (IDVal == ".org")
1108 return ParseDirectiveOrg();
1110 if (IDVal == ".fill")
1111 return ParseDirectiveFill();
1112 if (IDVal == ".space" || IDVal == ".skip")
1113 return ParseDirectiveSpace();
1114 if (IDVal == ".zero")
1115 return ParseDirectiveZero();
1117 // Symbol attribute directives
1119 if (IDVal == ".globl" || IDVal == ".global")
1120 return ParseDirectiveSymbolAttribute(MCSA_Global);
1121 // ELF only? Should it be here?
1122 if (IDVal == ".local")
1123 return ParseDirectiveSymbolAttribute(MCSA_Local);
1124 if (IDVal == ".hidden")
1125 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1126 if (IDVal == ".indirect_symbol")
1127 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1128 if (IDVal == ".internal")
1129 return ParseDirectiveSymbolAttribute(MCSA_Internal);
1130 if (IDVal == ".lazy_reference")
1131 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1132 if (IDVal == ".no_dead_strip")
1133 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1134 if (IDVal == ".symbol_resolver")
1135 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1136 if (IDVal == ".private_extern")
1137 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1138 if (IDVal == ".protected")
1139 return ParseDirectiveSymbolAttribute(MCSA_Protected);
1140 if (IDVal == ".reference")
1141 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1142 if (IDVal == ".weak")
1143 return ParseDirectiveSymbolAttribute(MCSA_Weak);
1144 if (IDVal == ".weak_definition")
1145 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1146 if (IDVal == ".weak_reference")
1147 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1148 if (IDVal == ".weak_def_can_be_hidden")
1149 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1151 if (IDVal == ".comm" || IDVal == ".common")
1152 return ParseDirectiveComm(/*IsLocal=*/false);
1153 if (IDVal == ".lcomm")
1154 return ParseDirectiveComm(/*IsLocal=*/true);
1156 if (IDVal == ".abort")
1157 return ParseDirectiveAbort();
1158 if (IDVal == ".include")
1159 return ParseDirectiveInclude();
1161 if (IDVal == ".code16" || IDVal == ".code32" || IDVal == ".code64")
1162 return TokError(Twine(IDVal) + " not supported yet");
1164 // Look up the handler in the handler table.
1165 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1166 DirectiveMap.lookup(IDVal);
1168 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1170 // Target hook for parsing target specific directives.
1171 if (!getTargetParser().ParseDirective(ID))
1174 bool retval = Warning(IDLoc, "ignoring directive for now");
1175 EatToEndOfStatement();
1179 CheckForValidSection();
1181 // Canonicalize the opcode to lower case.
1182 SmallString<128> Opcode;
1183 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1184 Opcode.push_back(tolower(IDVal[i]));
1186 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1187 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1190 // Dump the parsed representation, if requested.
1191 if (getShowParsedOperands()) {
1192 SmallString<256> Str;
1193 raw_svector_ostream OS(Str);
1194 OS << "parsed instruction: [";
1195 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1198 ParsedOperands[i]->print(OS);
1202 PrintMessage(IDLoc, OS.str(), "note");
1205 // If parsing succeeded, match the instruction.
1207 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1210 // Free any parsed operands.
1211 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1212 delete ParsedOperands[i];
1214 // Don't skip the rest of the line, the instruction parser is responsible for
1219 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1220 const std::vector<StringRef> &Parameters,
1221 const std::vector<std::vector<AsmToken> > &A,
1223 raw_svector_ostream OS(Buf);
1224 unsigned NParameters = Parameters.size();
1225 if (NParameters != 0 && NParameters != A.size())
1226 return Error(L, "Wrong number of arguments");
1228 while (!Body.empty()) {
1229 // Scan for the next substitution.
1230 std::size_t End = Body.size(), Pos = 0;
1231 for (; Pos != End; ++Pos) {
1232 // Check for a substitution or escape.
1234 // This macro has no parameters, look for $0, $1, etc.
1235 if (Body[Pos] != '$' || Pos + 1 == End)
1238 char Next = Body[Pos + 1];
1239 if (Next == '$' || Next == 'n' || isdigit(Next))
1242 // This macro has parameters, look for \foo, \bar, etc.
1243 if (Body[Pos] == '\\' && Pos + 1 != End)
1249 OS << Body.slice(0, Pos);
1251 // Check if we reached the end.
1256 switch (Body[Pos+1]) {
1262 // $n => number of arguments
1267 // $[0-9] => argument
1269 // Missing arguments are ignored.
1270 unsigned Index = Body[Pos+1] - '0';
1271 if (Index >= A.size())
1274 // Otherwise substitute with the token values, with spaces eliminated.
1275 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1276 ie = A[Index].end(); it != ie; ++it)
1277 OS << it->getString();
1283 unsigned I = Pos + 1;
1284 while (isalnum(Body[I]) && I + 1 != End)
1287 const char *Begin = Body.data() + Pos +1;
1288 StringRef Argument(Begin, I - (Pos +1));
1290 for (; Index < NParameters; ++Index)
1291 if (Parameters[Index] == Argument)
1294 // FIXME: We should error at the macro definition.
1295 if (Index == NParameters)
1296 return Error(L, "Parameter not found");
1298 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1299 ie = A[Index].end(); it != ie; ++it)
1300 OS << it->getString();
1302 Pos += 1 + Argument.size();
1304 // Update the scan point.
1305 Body = Body.substr(Pos);
1308 // We include the .endmacro in the buffer as our queue to exit the macro
1310 OS << ".endmacro\n";
1314 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1316 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1320 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1322 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1323 // this, although we should protect against infinite loops.
1324 if (ActiveMacros.size() == 20)
1325 return TokError("macros cannot be nested more than 20 levels deep");
1327 // Parse the macro instantiation arguments.
1328 std::vector<std::vector<AsmToken> > MacroArguments;
1329 MacroArguments.push_back(std::vector<AsmToken>());
1330 unsigned ParenLevel = 0;
1332 if (Lexer.is(AsmToken::Eof))
1333 return TokError("unexpected token in macro instantiation");
1334 if (Lexer.is(AsmToken::EndOfStatement))
1337 // If we aren't inside parentheses and this is a comma, start a new token
1339 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1340 MacroArguments.push_back(std::vector<AsmToken>());
1342 // Adjust the current parentheses level.
1343 if (Lexer.is(AsmToken::LParen))
1345 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1348 // Append the token to the current argument list.
1349 MacroArguments.back().push_back(getTok());
1354 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1355 // to hold the macro body with substitutions.
1356 SmallString<256> Buf;
1357 StringRef Body = M->Body;
1359 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1362 MemoryBuffer *Instantiation =
1363 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1365 // Create the macro instantiation object and add to the current macro
1366 // instantiation stack.
1367 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1370 ActiveMacros.push_back(MI);
1372 // Jump to the macro instantiation and prime the lexer.
1373 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1374 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1380 void AsmParser::HandleMacroExit() {
1381 // Jump to the EndOfStatement we should return to, and consume it.
1382 JumpToLoc(ActiveMacros.back()->ExitLoc);
1385 // Pop the instantiation entry.
1386 delete ActiveMacros.back();
1387 ActiveMacros.pop_back();
1390 static void MarkUsed(const MCExpr *Value) {
1391 switch (Value->getKind()) {
1392 case MCExpr::Binary:
1393 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1394 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1396 case MCExpr::Target:
1397 case MCExpr::Constant:
1399 case MCExpr::SymbolRef: {
1400 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1404 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1409 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1410 // FIXME: Use better location, we should use proper tokens.
1411 SMLoc EqualLoc = Lexer.getLoc();
1413 const MCExpr *Value;
1414 if (ParseExpression(Value))
1419 if (Lexer.isNot(AsmToken::EndOfStatement))
1420 return TokError("unexpected token in assignment");
1422 // Error on assignment to '.'.
1424 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1425 "(use '.space' or '.org').)"));
1428 // Eat the end of statement marker.
1431 // Validate that the LHS is allowed to be a variable (either it has not been
1432 // used as a symbol, or it is an absolute symbol).
1433 MCSymbol *Sym = getContext().LookupSymbol(Name);
1435 // Diagnose assignment to a label.
1437 // FIXME: Diagnostics. Note the location of the definition as a label.
1438 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1439 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1440 ; // Allow redefinitions of undefined symbols only used in directives.
1441 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1442 return Error(EqualLoc, "redefinition of '" + Name + "'");
1443 else if (!Sym->isVariable())
1444 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1445 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1446 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1449 // Don't count these checks as uses.
1450 Sym->setUsed(false);
1452 Sym = getContext().GetOrCreateSymbol(Name);
1454 // FIXME: Handle '.'.
1456 // Do the assignment.
1457 Out.EmitAssignment(Sym, Value);
1462 /// ParseIdentifier:
1465 bool AsmParser::ParseIdentifier(StringRef &Res) {
1466 // The assembler has relaxed rules for accepting identifiers, in particular we
1467 // allow things like '.globl $foo', which would normally be separate
1468 // tokens. At this level, we have already lexed so we cannot (currently)
1469 // handle this as a context dependent token, instead we detect adjacent tokens
1470 // and return the combined identifier.
1471 if (Lexer.is(AsmToken::Dollar)) {
1472 SMLoc DollarLoc = getLexer().getLoc();
1474 // Consume the dollar sign, and check for a following identifier.
1476 if (Lexer.isNot(AsmToken::Identifier))
1479 // We have a '$' followed by an identifier, make sure they are adjacent.
1480 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1483 // Construct the joined identifier and consume the token.
1484 Res = StringRef(DollarLoc.getPointer(),
1485 getTok().getIdentifier().size() + 1);
1490 if (Lexer.isNot(AsmToken::Identifier) &&
1491 Lexer.isNot(AsmToken::String))
1494 Res = getTok().getIdentifier();
1496 Lex(); // Consume the identifier token.
1501 /// ParseDirectiveSet:
1502 /// ::= .equ identifier ',' expression
1503 /// ::= .equiv identifier ',' expression
1504 /// ::= .set identifier ',' expression
1505 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1508 if (ParseIdentifier(Name))
1509 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1511 if (getLexer().isNot(AsmToken::Comma))
1512 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1515 return ParseAssignment(Name, allow_redef);
1518 bool AsmParser::ParseEscapedString(std::string &Data) {
1519 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1522 StringRef Str = getTok().getStringContents();
1523 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1524 if (Str[i] != '\\') {
1529 // Recognize escaped characters. Note that this escape semantics currently
1530 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1533 return TokError("unexpected backslash at end of string");
1535 // Recognize octal sequences.
1536 if ((unsigned) (Str[i] - '0') <= 7) {
1537 // Consume up to three octal characters.
1538 unsigned Value = Str[i] - '0';
1540 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1542 Value = Value * 8 + (Str[i] - '0');
1544 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1546 Value = Value * 8 + (Str[i] - '0');
1551 return TokError("invalid octal escape sequence (out of range)");
1553 Data += (unsigned char) Value;
1557 // Otherwise recognize individual escapes.
1560 // Just reject invalid escape sequences for now.
1561 return TokError("invalid escape sequence (unrecognized character)");
1563 case 'b': Data += '\b'; break;
1564 case 'f': Data += '\f'; break;
1565 case 'n': Data += '\n'; break;
1566 case 'r': Data += '\r'; break;
1567 case 't': Data += '\t'; break;
1568 case '"': Data += '"'; break;
1569 case '\\': Data += '\\'; break;
1576 /// ParseDirectiveAscii:
1577 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1578 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1579 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1580 CheckForValidSection();
1583 if (getLexer().isNot(AsmToken::String))
1584 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1587 if (ParseEscapedString(Data))
1590 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1592 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1596 if (getLexer().is(AsmToken::EndOfStatement))
1599 if (getLexer().isNot(AsmToken::Comma))
1600 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1609 /// ParseDirectiveValue
1610 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1611 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1612 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1613 CheckForValidSection();
1616 const MCExpr *Value;
1617 SMLoc ExprLoc = getLexer().getLoc();
1618 if (ParseExpression(Value))
1621 // Special case constant expressions to match code generator.
1622 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1623 assert(Size <= 8 && "Invalid size");
1624 uint64_t IntValue = MCE->getValue();
1625 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1626 return Error(ExprLoc, "literal value out of range for directive");
1627 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1629 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1631 if (getLexer().is(AsmToken::EndOfStatement))
1634 // FIXME: Improve diagnostic.
1635 if (getLexer().isNot(AsmToken::Comma))
1636 return TokError("unexpected token in directive");
1645 /// ParseDirectiveRealValue
1646 /// ::= (.single | .double) [ expression (, expression)* ]
1647 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1648 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1649 CheckForValidSection();
1652 // We don't truly support arithmetic on floating point expressions, so we
1653 // have to manually parse unary prefixes.
1655 if (getLexer().is(AsmToken::Minus)) {
1658 } else if (getLexer().is(AsmToken::Plus))
1661 if (getLexer().isNot(AsmToken::Integer) &&
1662 getLexer().isNot(AsmToken::Real) &&
1663 getLexer().isNot(AsmToken::Identifier))
1664 return TokError("unexpected token in directive");
1666 // Convert to an APFloat.
1667 APFloat Value(Semantics);
1668 StringRef IDVal = getTok().getString();
1669 if (getLexer().is(AsmToken::Identifier)) {
1670 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1671 Value = APFloat::getInf(Semantics);
1672 else if (!IDVal.compare_lower("nan"))
1673 Value = APFloat::getNaN(Semantics, false, ~0);
1675 return TokError("invalid floating point literal");
1676 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1677 APFloat::opInvalidOp)
1678 return TokError("invalid floating point literal");
1682 // Consume the numeric token.
1685 // Emit the value as an integer.
1686 APInt AsInt = Value.bitcastToAPInt();
1687 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1688 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1690 if (getLexer().is(AsmToken::EndOfStatement))
1693 if (getLexer().isNot(AsmToken::Comma))
1694 return TokError("unexpected token in directive");
1703 /// ParseDirectiveSpace
1704 /// ::= .space expression [ , expression ]
1705 bool AsmParser::ParseDirectiveSpace() {
1706 CheckForValidSection();
1709 if (ParseAbsoluteExpression(NumBytes))
1712 int64_t FillExpr = 0;
1713 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1714 if (getLexer().isNot(AsmToken::Comma))
1715 return TokError("unexpected token in '.space' directive");
1718 if (ParseAbsoluteExpression(FillExpr))
1721 if (getLexer().isNot(AsmToken::EndOfStatement))
1722 return TokError("unexpected token in '.space' directive");
1728 return TokError("invalid number of bytes in '.space' directive");
1730 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1731 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1736 /// ParseDirectiveZero
1737 /// ::= .zero expression
1738 bool AsmParser::ParseDirectiveZero() {
1739 CheckForValidSection();
1742 if (ParseAbsoluteExpression(NumBytes))
1746 if (getLexer().is(AsmToken::Comma)) {
1748 if (ParseAbsoluteExpression(Val))
1752 if (getLexer().isNot(AsmToken::EndOfStatement))
1753 return TokError("unexpected token in '.zero' directive");
1757 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1762 /// ParseDirectiveFill
1763 /// ::= .fill expression , expression , expression
1764 bool AsmParser::ParseDirectiveFill() {
1765 CheckForValidSection();
1768 if (ParseAbsoluteExpression(NumValues))
1771 if (getLexer().isNot(AsmToken::Comma))
1772 return TokError("unexpected token in '.fill' directive");
1776 if (ParseAbsoluteExpression(FillSize))
1779 if (getLexer().isNot(AsmToken::Comma))
1780 return TokError("unexpected token in '.fill' directive");
1784 if (ParseAbsoluteExpression(FillExpr))
1787 if (getLexer().isNot(AsmToken::EndOfStatement))
1788 return TokError("unexpected token in '.fill' directive");
1792 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1793 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1795 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1796 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1801 /// ParseDirectiveOrg
1802 /// ::= .org expression [ , expression ]
1803 bool AsmParser::ParseDirectiveOrg() {
1804 CheckForValidSection();
1806 const MCExpr *Offset;
1807 if (ParseExpression(Offset))
1810 // Parse optional fill expression.
1811 int64_t FillExpr = 0;
1812 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1813 if (getLexer().isNot(AsmToken::Comma))
1814 return TokError("unexpected token in '.org' directive");
1817 if (ParseAbsoluteExpression(FillExpr))
1820 if (getLexer().isNot(AsmToken::EndOfStatement))
1821 return TokError("unexpected token in '.org' directive");
1826 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1827 // has to be relative to the current section.
1828 getStreamer().EmitValueToOffset(Offset, FillExpr);
1833 /// ParseDirectiveAlign
1834 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1835 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1836 CheckForValidSection();
1838 SMLoc AlignmentLoc = getLexer().getLoc();
1840 if (ParseAbsoluteExpression(Alignment))
1844 bool HasFillExpr = false;
1845 int64_t FillExpr = 0;
1846 int64_t MaxBytesToFill = 0;
1847 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1848 if (getLexer().isNot(AsmToken::Comma))
1849 return TokError("unexpected token in directive");
1852 // The fill expression can be omitted while specifying a maximum number of
1853 // alignment bytes, e.g:
1855 if (getLexer().isNot(AsmToken::Comma)) {
1857 if (ParseAbsoluteExpression(FillExpr))
1861 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1862 if (getLexer().isNot(AsmToken::Comma))
1863 return TokError("unexpected token in directive");
1866 MaxBytesLoc = getLexer().getLoc();
1867 if (ParseAbsoluteExpression(MaxBytesToFill))
1870 if (getLexer().isNot(AsmToken::EndOfStatement))
1871 return TokError("unexpected token in directive");
1880 // Compute alignment in bytes.
1882 // FIXME: Diagnose overflow.
1883 if (Alignment >= 32) {
1884 Error(AlignmentLoc, "invalid alignment value");
1888 Alignment = 1ULL << Alignment;
1891 // Diagnose non-sensical max bytes to align.
1892 if (MaxBytesLoc.isValid()) {
1893 if (MaxBytesToFill < 1) {
1894 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1895 "many bytes, ignoring maximum bytes expression");
1899 if (MaxBytesToFill >= Alignment) {
1900 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1906 // Check whether we should use optimal code alignment for this .align
1908 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1909 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1910 ValueSize == 1 && UseCodeAlign) {
1911 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1913 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1914 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1921 /// ParseDirectiveSymbolAttribute
1922 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1923 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1924 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1928 if (ParseIdentifier(Name))
1929 return TokError("expected identifier in directive");
1931 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1933 getStreamer().EmitSymbolAttribute(Sym, Attr);
1935 if (getLexer().is(AsmToken::EndOfStatement))
1938 if (getLexer().isNot(AsmToken::Comma))
1939 return TokError("unexpected token in directive");
1948 /// ParseDirectiveComm
1949 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1950 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1951 CheckForValidSection();
1953 SMLoc IDLoc = getLexer().getLoc();
1955 if (ParseIdentifier(Name))
1956 return TokError("expected identifier in directive");
1958 // Handle the identifier as the key symbol.
1959 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1961 if (getLexer().isNot(AsmToken::Comma))
1962 return TokError("unexpected token in directive");
1966 SMLoc SizeLoc = getLexer().getLoc();
1967 if (ParseAbsoluteExpression(Size))
1970 int64_t Pow2Alignment = 0;
1971 SMLoc Pow2AlignmentLoc;
1972 if (getLexer().is(AsmToken::Comma)) {
1974 Pow2AlignmentLoc = getLexer().getLoc();
1975 if (ParseAbsoluteExpression(Pow2Alignment))
1978 // If this target takes alignments in bytes (not log) validate and convert.
1979 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1980 if (!isPowerOf2_64(Pow2Alignment))
1981 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1982 Pow2Alignment = Log2_64(Pow2Alignment);
1986 if (getLexer().isNot(AsmToken::EndOfStatement))
1987 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1991 // NOTE: a size of zero for a .comm should create a undefined symbol
1992 // but a size of .lcomm creates a bss symbol of size zero.
1994 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1995 "be less than zero");
1997 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1998 // may internally end up wanting an alignment in bytes.
1999 // FIXME: Diagnose overflow.
2000 if (Pow2Alignment < 0)
2001 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2002 "alignment, can't be less than zero");
2004 if (!Sym->isUndefined())
2005 return Error(IDLoc, "invalid symbol redefinition");
2007 // '.lcomm' is equivalent to '.zerofill'.
2008 // Create the Symbol as a common or local common with Size and Pow2Alignment
2010 getStreamer().EmitZerofill(Ctx.getMachOSection(
2011 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2012 0, SectionKind::getBSS()),
2013 Sym, Size, 1 << Pow2Alignment);
2017 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2021 /// ParseDirectiveAbort
2022 /// ::= .abort [... message ...]
2023 bool AsmParser::ParseDirectiveAbort() {
2024 // FIXME: Use loc from directive.
2025 SMLoc Loc = getLexer().getLoc();
2027 StringRef Str = ParseStringToEndOfStatement();
2028 if (getLexer().isNot(AsmToken::EndOfStatement))
2029 return TokError("unexpected token in '.abort' directive");
2034 Error(Loc, ".abort detected. Assembly stopping.");
2036 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2037 // FIXME: Actually abort assembly here.
2042 /// ParseDirectiveInclude
2043 /// ::= .include "filename"
2044 bool AsmParser::ParseDirectiveInclude() {
2045 if (getLexer().isNot(AsmToken::String))
2046 return TokError("expected string in '.include' directive");
2048 std::string Filename = getTok().getString();
2049 SMLoc IncludeLoc = getLexer().getLoc();
2052 if (getLexer().isNot(AsmToken::EndOfStatement))
2053 return TokError("unexpected token in '.include' directive");
2055 // Strip the quotes.
2056 Filename = Filename.substr(1, Filename.size()-2);
2058 // Attempt to switch the lexer to the included file before consuming the end
2059 // of statement to avoid losing it when we switch.
2060 if (EnterIncludeFile(Filename)) {
2061 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2068 /// ParseDirectiveIf
2069 /// ::= .if expression
2070 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2071 TheCondStack.push_back(TheCondState);
2072 TheCondState.TheCond = AsmCond::IfCond;
2073 if(TheCondState.Ignore) {
2074 EatToEndOfStatement();
2078 if (ParseAbsoluteExpression(ExprValue))
2081 if (getLexer().isNot(AsmToken::EndOfStatement))
2082 return TokError("unexpected token in '.if' directive");
2086 TheCondState.CondMet = ExprValue;
2087 TheCondState.Ignore = !TheCondState.CondMet;
2093 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2095 TheCondStack.push_back(TheCondState);
2096 TheCondState.TheCond = AsmCond::IfCond;
2098 if (TheCondState.Ignore) {
2099 EatToEndOfStatement();
2101 if (ParseIdentifier(Name))
2102 return TokError("expected identifier after '.ifdef'");
2106 MCSymbol *Sym = getContext().LookupSymbol(Name);
2109 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2111 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2112 TheCondState.Ignore = !TheCondState.CondMet;
2118 /// ParseDirectiveElseIf
2119 /// ::= .elseif expression
2120 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2121 if (TheCondState.TheCond != AsmCond::IfCond &&
2122 TheCondState.TheCond != AsmCond::ElseIfCond)
2123 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2125 TheCondState.TheCond = AsmCond::ElseIfCond;
2127 bool LastIgnoreState = false;
2128 if (!TheCondStack.empty())
2129 LastIgnoreState = TheCondStack.back().Ignore;
2130 if (LastIgnoreState || TheCondState.CondMet) {
2131 TheCondState.Ignore = true;
2132 EatToEndOfStatement();
2136 if (ParseAbsoluteExpression(ExprValue))
2139 if (getLexer().isNot(AsmToken::EndOfStatement))
2140 return TokError("unexpected token in '.elseif' directive");
2143 TheCondState.CondMet = ExprValue;
2144 TheCondState.Ignore = !TheCondState.CondMet;
2150 /// ParseDirectiveElse
2152 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2153 if (getLexer().isNot(AsmToken::EndOfStatement))
2154 return TokError("unexpected token in '.else' directive");
2158 if (TheCondState.TheCond != AsmCond::IfCond &&
2159 TheCondState.TheCond != AsmCond::ElseIfCond)
2160 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2162 TheCondState.TheCond = AsmCond::ElseCond;
2163 bool LastIgnoreState = false;
2164 if (!TheCondStack.empty())
2165 LastIgnoreState = TheCondStack.back().Ignore;
2166 if (LastIgnoreState || TheCondState.CondMet)
2167 TheCondState.Ignore = true;
2169 TheCondState.Ignore = false;
2174 /// ParseDirectiveEndIf
2176 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2177 if (getLexer().isNot(AsmToken::EndOfStatement))
2178 return TokError("unexpected token in '.endif' directive");
2182 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2183 TheCondStack.empty())
2184 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2186 if (!TheCondStack.empty()) {
2187 TheCondState = TheCondStack.back();
2188 TheCondStack.pop_back();
2194 /// ParseDirectiveFile
2195 /// ::= .file [number] string
2196 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2197 // FIXME: I'm not sure what this is.
2198 int64_t FileNumber = -1;
2199 SMLoc FileNumberLoc = getLexer().getLoc();
2200 if (getLexer().is(AsmToken::Integer)) {
2201 FileNumber = getTok().getIntVal();
2205 return TokError("file number less than one");
2208 if (getLexer().isNot(AsmToken::String))
2209 return TokError("unexpected token in '.file' directive");
2211 StringRef Filename = getTok().getString();
2212 Filename = Filename.substr(1, Filename.size()-2);
2215 if (getLexer().isNot(AsmToken::EndOfStatement))
2216 return TokError("unexpected token in '.file' directive");
2218 if (FileNumber == -1)
2219 getStreamer().EmitFileDirective(Filename);
2221 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2222 Error(FileNumberLoc, "file number already allocated");
2228 /// ParseDirectiveLine
2229 /// ::= .line [number]
2230 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2231 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2232 if (getLexer().isNot(AsmToken::Integer))
2233 return TokError("unexpected token in '.line' directive");
2235 int64_t LineNumber = getTok().getIntVal();
2239 // FIXME: Do something with the .line.
2242 if (getLexer().isNot(AsmToken::EndOfStatement))
2243 return TokError("unexpected token in '.line' directive");
2249 /// ParseDirectiveLoc
2250 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2251 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2252 /// The first number is a file number, must have been previously assigned with
2253 /// a .file directive, the second number is the line number and optionally the
2254 /// third number is a column position (zero if not specified). The remaining
2255 /// optional items are .loc sub-directives.
2256 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2258 if (getLexer().isNot(AsmToken::Integer))
2259 return TokError("unexpected token in '.loc' directive");
2260 int64_t FileNumber = getTok().getIntVal();
2262 return TokError("file number less than one in '.loc' directive");
2263 if (!getContext().isValidDwarfFileNumber(FileNumber))
2264 return TokError("unassigned file number in '.loc' directive");
2267 int64_t LineNumber = 0;
2268 if (getLexer().is(AsmToken::Integer)) {
2269 LineNumber = getTok().getIntVal();
2271 return TokError("line number less than one in '.loc' directive");
2275 int64_t ColumnPos = 0;
2276 if (getLexer().is(AsmToken::Integer)) {
2277 ColumnPos = getTok().getIntVal();
2279 return TokError("column position less than zero in '.loc' directive");
2283 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2285 int64_t Discriminator = 0;
2286 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2288 if (getLexer().is(AsmToken::EndOfStatement))
2292 SMLoc Loc = getTok().getLoc();
2293 if (getParser().ParseIdentifier(Name))
2294 return TokError("unexpected token in '.loc' directive");
2296 if (Name == "basic_block")
2297 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2298 else if (Name == "prologue_end")
2299 Flags |= DWARF2_FLAG_PROLOGUE_END;
2300 else if (Name == "epilogue_begin")
2301 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2302 else if (Name == "is_stmt") {
2303 SMLoc Loc = getTok().getLoc();
2304 const MCExpr *Value;
2305 if (getParser().ParseExpression(Value))
2307 // The expression must be the constant 0 or 1.
2308 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2309 int Value = MCE->getValue();
2311 Flags &= ~DWARF2_FLAG_IS_STMT;
2312 else if (Value == 1)
2313 Flags |= DWARF2_FLAG_IS_STMT;
2315 return Error(Loc, "is_stmt value not 0 or 1");
2318 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2321 else if (Name == "isa") {
2322 SMLoc Loc = getTok().getLoc();
2323 const MCExpr *Value;
2324 if (getParser().ParseExpression(Value))
2326 // The expression must be a constant greater or equal to 0.
2327 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2328 int Value = MCE->getValue();
2330 return Error(Loc, "isa number less than zero");
2334 return Error(Loc, "isa number not a constant value");
2337 else if (Name == "discriminator") {
2338 if (getParser().ParseAbsoluteExpression(Discriminator))
2342 return Error(Loc, "unknown sub-directive in '.loc' directive");
2345 if (getLexer().is(AsmToken::EndOfStatement))
2350 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2351 Isa, Discriminator, StringRef());
2356 /// ParseDirectiveStabs
2357 /// ::= .stabs string, number, number, number
2358 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2359 SMLoc DirectiveLoc) {
2360 return TokError("unsupported directive '" + Directive + "'");
2363 /// ParseDirectiveCFISections
2364 /// ::= .cfi_sections section [, section]
2365 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2366 SMLoc DirectiveLoc) {
2371 if (getParser().ParseIdentifier(Name))
2372 return TokError("Expected an identifier");
2374 if (Name == ".eh_frame")
2376 else if (Name == ".debug_frame")
2379 if (getLexer().is(AsmToken::Comma)) {
2382 if (getParser().ParseIdentifier(Name))
2383 return TokError("Expected an identifier");
2385 if (Name == ".eh_frame")
2387 else if (Name == ".debug_frame")
2391 getStreamer().EmitCFISections(EH, Debug);
2396 /// ParseDirectiveCFIStartProc
2397 /// ::= .cfi_startproc
2398 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2399 SMLoc DirectiveLoc) {
2400 getStreamer().EmitCFIStartProc();
2404 /// ParseDirectiveCFIEndProc
2405 /// ::= .cfi_endproc
2406 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2407 getStreamer().EmitCFIEndProc();
2411 /// ParseRegisterOrRegisterNumber - parse register name or number.
2412 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2413 SMLoc DirectiveLoc) {
2416 if (getLexer().isNot(AsmToken::Integer)) {
2417 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2420 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2422 return getParser().ParseAbsoluteExpression(Register);
2427 /// ParseDirectiveCFIDefCfa
2428 /// ::= .cfi_def_cfa register, offset
2429 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2430 SMLoc DirectiveLoc) {
2431 int64_t Register = 0;
2432 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2435 if (getLexer().isNot(AsmToken::Comma))
2436 return TokError("unexpected token in directive");
2440 if (getParser().ParseAbsoluteExpression(Offset))
2443 getStreamer().EmitCFIDefCfa(Register, Offset);
2447 /// ParseDirectiveCFIDefCfaOffset
2448 /// ::= .cfi_def_cfa_offset offset
2449 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2450 SMLoc DirectiveLoc) {
2452 if (getParser().ParseAbsoluteExpression(Offset))
2455 getStreamer().EmitCFIDefCfaOffset(Offset);
2459 /// ParseDirectiveCFIAdjustCfaOffset
2460 /// ::= .cfi_adjust_cfa_offset adjustment
2461 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2462 SMLoc DirectiveLoc) {
2463 int64_t Adjustment = 0;
2464 if (getParser().ParseAbsoluteExpression(Adjustment))
2467 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2471 /// ParseDirectiveCFIDefCfaRegister
2472 /// ::= .cfi_def_cfa_register register
2473 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2474 SMLoc DirectiveLoc) {
2475 int64_t Register = 0;
2476 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2479 getStreamer().EmitCFIDefCfaRegister(Register);
2483 /// ParseDirectiveCFIOffset
2484 /// ::= .cfi_offset register, offset
2485 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2486 int64_t Register = 0;
2489 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2492 if (getLexer().isNot(AsmToken::Comma))
2493 return TokError("unexpected token in directive");
2496 if (getParser().ParseAbsoluteExpression(Offset))
2499 getStreamer().EmitCFIOffset(Register, Offset);
2503 /// ParseDirectiveCFIRelOffset
2504 /// ::= .cfi_rel_offset register, offset
2505 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2506 SMLoc DirectiveLoc) {
2507 int64_t Register = 0;
2509 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2512 if (getLexer().isNot(AsmToken::Comma))
2513 return TokError("unexpected token in directive");
2517 if (getParser().ParseAbsoluteExpression(Offset))
2520 getStreamer().EmitCFIRelOffset(Register, Offset);
2524 static bool isValidEncoding(int64_t Encoding) {
2525 if (Encoding & ~0xff)
2528 if (Encoding == dwarf::DW_EH_PE_omit)
2531 const unsigned Format = Encoding & 0xf;
2532 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2533 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2534 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2535 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2538 const unsigned Application = Encoding & 0x70;
2539 if (Application != dwarf::DW_EH_PE_absptr &&
2540 Application != dwarf::DW_EH_PE_pcrel)
2546 /// ParseDirectiveCFIPersonalityOrLsda
2547 /// ::= .cfi_personality encoding, [symbol_name]
2548 /// ::= .cfi_lsda encoding, [symbol_name]
2549 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2550 SMLoc DirectiveLoc) {
2551 int64_t Encoding = 0;
2552 if (getParser().ParseAbsoluteExpression(Encoding))
2554 if (Encoding == dwarf::DW_EH_PE_omit)
2557 if (!isValidEncoding(Encoding))
2558 return TokError("unsupported encoding.");
2560 if (getLexer().isNot(AsmToken::Comma))
2561 return TokError("unexpected token in directive");
2565 if (getParser().ParseIdentifier(Name))
2566 return TokError("expected identifier in directive");
2568 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2570 if (IDVal == ".cfi_personality")
2571 getStreamer().EmitCFIPersonality(Sym, Encoding);
2573 assert(IDVal == ".cfi_lsda");
2574 getStreamer().EmitCFILsda(Sym, Encoding);
2579 /// ParseDirectiveCFIRememberState
2580 /// ::= .cfi_remember_state
2581 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2582 SMLoc DirectiveLoc) {
2583 getStreamer().EmitCFIRememberState();
2587 /// ParseDirectiveCFIRestoreState
2588 /// ::= .cfi_remember_state
2589 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2590 SMLoc DirectiveLoc) {
2591 getStreamer().EmitCFIRestoreState();
2595 /// ParseDirectiveCFISameValue
2596 /// ::= .cfi_same_value register
2597 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2598 SMLoc DirectiveLoc) {
2599 int64_t Register = 0;
2601 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2604 getStreamer().EmitCFISameValue(Register);
2609 /// ParseDirectiveMacrosOnOff
2612 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2613 SMLoc DirectiveLoc) {
2614 if (getLexer().isNot(AsmToken::EndOfStatement))
2615 return Error(getLexer().getLoc(),
2616 "unexpected token in '" + Directive + "' directive");
2618 getParser().MacrosEnabled = Directive == ".macros_on";
2623 /// ParseDirectiveMacro
2624 /// ::= .macro name [parameters]
2625 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2626 SMLoc DirectiveLoc) {
2628 if (getParser().ParseIdentifier(Name))
2629 return TokError("expected identifier in directive");
2631 std::vector<StringRef> Parameters;
2632 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2634 StringRef Parameter;
2635 if (getParser().ParseIdentifier(Parameter))
2636 return TokError("expected identifier in directive");
2637 Parameters.push_back(Parameter);
2639 if (getLexer().isNot(AsmToken::Comma))
2645 if (getLexer().isNot(AsmToken::EndOfStatement))
2646 return TokError("unexpected token in '.macro' directive");
2648 // Eat the end of statement.
2651 AsmToken EndToken, StartToken = getTok();
2653 // Lex the macro definition.
2655 // Check whether we have reached the end of the file.
2656 if (getLexer().is(AsmToken::Eof))
2657 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2659 // Otherwise, check whether we have reach the .endmacro.
2660 if (getLexer().is(AsmToken::Identifier) &&
2661 (getTok().getIdentifier() == ".endm" ||
2662 getTok().getIdentifier() == ".endmacro")) {
2663 EndToken = getTok();
2665 if (getLexer().isNot(AsmToken::EndOfStatement))
2666 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2671 // Otherwise, scan til the end of the statement.
2672 getParser().EatToEndOfStatement();
2675 if (getParser().MacroMap.lookup(Name)) {
2676 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2679 const char *BodyStart = StartToken.getLoc().getPointer();
2680 const char *BodyEnd = EndToken.getLoc().getPointer();
2681 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2682 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
2686 /// ParseDirectiveEndMacro
2689 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2690 SMLoc DirectiveLoc) {
2691 if (getLexer().isNot(AsmToken::EndOfStatement))
2692 return TokError("unexpected token in '" + Directive + "' directive");
2694 // If we are inside a macro instantiation, terminate the current
2696 if (!getParser().ActiveMacros.empty()) {
2697 getParser().HandleMacroExit();
2701 // Otherwise, this .endmacro is a stray entry in the file; well formed
2702 // .endmacro directives are handled during the macro definition parsing.
2703 return TokError("unexpected '" + Directive + "' in file, "
2704 "no current macro definition");
2707 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2708 getParser().CheckForValidSection();
2710 const MCExpr *Value;
2712 if (getParser().ParseExpression(Value))
2715 if (getLexer().isNot(AsmToken::EndOfStatement))
2716 return TokError("unexpected token in directive");
2718 if (DirName[1] == 's')
2719 getStreamer().EmitSLEB128Value(Value);
2721 getStreamer().EmitULEB128Value(Value);
2727 /// \brief Create an MCAsmParser instance.
2728 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2729 MCContext &C, MCStreamer &Out,
2730 const MCAsmInfo &MAI) {
2731 return new AsmParser(T, SM, C, Out, MAI);