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 // FIXME: This is not the best place to store this. To handle a (for example)
85 // .cfi_rel_offset before a .cfi_def_cfa_offset we need to know the initial
89 /// This is the current buffer index we're lexing from as managed by the
94 std::vector<AsmCond> TheCondStack;
96 /// DirectiveMap - This is a table handlers for directives. Each handler is
97 /// invoked after the directive identifier is read and is responsible for
98 /// parsing and validating the rest of the directive. The handler is passed
99 /// in the directive name and the location of the directive keyword.
100 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
102 /// MacroMap - Map of currently defined macros.
103 StringMap<Macro*> MacroMap;
105 /// ActiveMacros - Stack of active macro instantiations.
106 std::vector<MacroInstantiation*> ActiveMacros;
108 /// Boolean tracking whether macro substitution is enabled.
109 unsigned MacrosEnabled : 1;
111 /// Flag tracking whether any errors have been encountered.
112 unsigned HadError : 1;
115 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
116 const MCAsmInfo &MAI);
119 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
121 void AddDirectiveHandler(MCAsmParserExtension *Object,
123 DirectiveHandler Handler) {
124 DirectiveMap[Directive] = std::make_pair(Object, Handler);
128 /// @name MCAsmParser Interface
131 virtual SourceMgr &getSourceManager() { return SrcMgr; }
132 virtual MCAsmLexer &getLexer() { return Lexer; }
133 virtual MCContext &getContext() { return Ctx; }
134 virtual MCStreamer &getStreamer() { return Out; }
136 virtual void Warning(SMLoc L, const Twine &Meg);
137 virtual bool Error(SMLoc L, const Twine &Msg);
139 const AsmToken &Lex();
141 bool ParseExpression(const MCExpr *&Res);
142 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
143 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
144 virtual bool ParseAbsoluteExpression(int64_t &Res);
148 int64_t adjustLastOffset(int64_t Adjustment) {
149 LastOffset += Adjustment;
152 int64_t getLastOffset() {
155 void setLastOffset(int64_t Offset) {
160 void CheckForValidSection();
162 bool ParseStatement();
164 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
165 void HandleMacroExit();
167 void PrintMacroInstantiations();
168 void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type) const {
169 SrcMgr.PrintMessage(Loc, Msg, Type);
172 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
173 bool EnterIncludeFile(const std::string &Filename);
175 /// \brief Reset the current lexer position to that given by \arg Loc. The
176 /// current token is not set; clients should ensure Lex() is called
178 void JumpToLoc(SMLoc Loc);
180 void EatToEndOfStatement();
182 /// \brief Parse up to the end of statement and a return the contents from the
183 /// current token until the end of the statement; the current token on exit
184 /// will be either the EndOfStatement or EOF.
185 StringRef ParseStringToEndOfStatement();
187 bool ParseAssignment(StringRef Name, bool allow_redef);
189 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
190 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
191 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
192 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
194 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
195 /// and set \arg Res to the identifier contents.
196 bool ParseIdentifier(StringRef &Res);
198 // Directive Parsing.
200 // ".ascii", ".asciiz", ".string"
201 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
202 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
203 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
204 bool ParseDirectiveFill(); // ".fill"
205 bool ParseDirectiveSpace(); // ".space"
206 bool ParseDirectiveZero(); // ".zero"
207 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
208 bool ParseDirectiveOrg(); // ".org"
209 // ".align{,32}", ".p2align{,w,l}"
210 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
212 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
213 /// accepts a single symbol (which should be a label or an external).
214 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
216 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
218 bool ParseDirectiveAbort(); // ".abort"
219 bool ParseDirectiveInclude(); // ".include"
221 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
222 // ".ifdef" or ".ifndef", depending on expect_defined
223 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
224 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
225 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
226 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
228 /// ParseEscapedString - Parse the current token as a string which may include
229 /// escaped characters and return the string contents.
230 bool ParseEscapedString(std::string &Data);
232 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
233 MCSymbolRefExpr::VariantKind Variant);
236 /// \brief Generic implementations of directive handling, etc. which is shared
237 /// (or the default, at least) for all assembler parser.
238 class GenericAsmParser : public MCAsmParserExtension {
239 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
240 void AddDirectiveHandler(StringRef Directive) {
241 getParser().AddDirectiveHandler(this, Directive,
242 HandleDirective<GenericAsmParser, Handler>);
245 GenericAsmParser() {}
247 AsmParser &getParser() {
248 return (AsmParser&) this->MCAsmParserExtension::getParser();
251 virtual void Initialize(MCAsmParser &Parser) {
252 // Call the base implementation.
253 this->MCAsmParserExtension::Initialize(Parser);
255 // Debugging directives.
256 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
257 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
258 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
259 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
262 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
264 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
266 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
268 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
269 ".cfi_def_cfa_offset");
270 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
271 ".cfi_adjust_cfa_offset");
272 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
273 ".cfi_def_cfa_register");
274 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
276 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
279 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
281 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
283 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
285 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
287 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
290 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
292 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
294 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
295 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
296 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
298 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
299 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
302 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
304 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
305 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
306 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
307 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
308 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
309 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
310 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
311 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
312 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
313 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
314 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
315 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
316 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
317 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
318 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
319 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
321 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
322 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
323 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
325 bool ParseDirectiveLEB128(StringRef, SMLoc);
332 extern MCAsmParserExtension *createDarwinAsmParser();
333 extern MCAsmParserExtension *createELFAsmParser();
334 extern MCAsmParserExtension *createCOFFAsmParser();
338 enum { DEFAULT_ADDRSPACE = 0 };
340 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
341 MCStreamer &_Out, const MCAsmInfo &_MAI)
342 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
343 GenericParser(new GenericAsmParser), PlatformParser(0), LastOffset(0),
344 CurBuffer(0), MacrosEnabled(true) {
345 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
347 // Initialize the generic parser.
348 GenericParser->Initialize(*this);
350 // Initialize the platform / file format parser.
352 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
354 if (_MAI.hasMicrosoftFastStdCallMangling()) {
355 PlatformParser = createCOFFAsmParser();
356 PlatformParser->Initialize(*this);
357 } else if (_MAI.hasSubsectionsViaSymbols()) {
358 PlatformParser = createDarwinAsmParser();
359 PlatformParser->Initialize(*this);
361 PlatformParser = createELFAsmParser();
362 PlatformParser->Initialize(*this);
366 AsmParser::~AsmParser() {
367 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
369 // Destroy any macros.
370 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
371 ie = MacroMap.end(); it != ie; ++it)
372 delete it->getValue();
374 delete PlatformParser;
375 delete GenericParser;
378 void AsmParser::PrintMacroInstantiations() {
379 // Print the active macro instantiation stack.
380 for (std::vector<MacroInstantiation*>::const_reverse_iterator
381 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
382 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
386 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
387 PrintMessage(L, Msg, "warning");
388 PrintMacroInstantiations();
391 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
393 PrintMessage(L, Msg, "error");
394 PrintMacroInstantiations();
398 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
399 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
405 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
410 void AsmParser::JumpToLoc(SMLoc Loc) {
411 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
412 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
415 const AsmToken &AsmParser::Lex() {
416 const AsmToken *tok = &Lexer.Lex();
418 if (tok->is(AsmToken::Eof)) {
419 // If this is the end of an included file, pop the parent file off the
421 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
422 if (ParentIncludeLoc != SMLoc()) {
423 JumpToLoc(ParentIncludeLoc);
428 if (tok->is(AsmToken::Error))
429 Error(Lexer.getErrLoc(), Lexer.getErr());
434 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
435 // Create the initial section, if requested.
436 if (!NoInitialTextSection)
443 AsmCond StartingCondState = TheCondState;
445 // While we have input, parse each statement.
446 while (Lexer.isNot(AsmToken::Eof)) {
447 if (!ParseStatement()) continue;
449 // We had an error, validate that one was emitted and recover by skipping to
451 assert(HadError && "Parse statement returned an error, but none emitted!");
452 EatToEndOfStatement();
455 if (TheCondState.TheCond != StartingCondState.TheCond ||
456 TheCondState.Ignore != StartingCondState.Ignore)
457 return TokError("unmatched .ifs or .elses");
459 // Check to see there are no empty DwarfFile slots.
460 const std::vector<MCDwarfFile *> &MCDwarfFiles =
461 getContext().getMCDwarfFiles();
462 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
463 if (!MCDwarfFiles[i])
464 TokError("unassigned file number: " + Twine(i) + " for .file directives");
467 // Finalize the output stream if there are no errors and if the client wants
469 if (!HadError && !NoFinalize)
475 void AsmParser::CheckForValidSection() {
476 if (!getStreamer().getCurrentSection()) {
477 TokError("expected section directive before assembly directive");
478 Out.SwitchSection(Ctx.getMachOSection(
480 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
481 0, SectionKind::getText()));
485 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
486 void AsmParser::EatToEndOfStatement() {
487 while (Lexer.isNot(AsmToken::EndOfStatement) &&
488 Lexer.isNot(AsmToken::Eof))
492 if (Lexer.is(AsmToken::EndOfStatement))
496 StringRef AsmParser::ParseStringToEndOfStatement() {
497 const char *Start = getTok().getLoc().getPointer();
499 while (Lexer.isNot(AsmToken::EndOfStatement) &&
500 Lexer.isNot(AsmToken::Eof))
503 const char *End = getTok().getLoc().getPointer();
504 return StringRef(Start, End - Start);
507 /// ParseParenExpr - Parse a paren expression and return it.
508 /// NOTE: This assumes the leading '(' has already been consumed.
510 /// parenexpr ::= expr)
512 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
513 if (ParseExpression(Res)) return true;
514 if (Lexer.isNot(AsmToken::RParen))
515 return TokError("expected ')' in parentheses expression");
516 EndLoc = Lexer.getLoc();
521 /// ParseBracketExpr - Parse a bracket expression and return it.
522 /// NOTE: This assumes the leading '[' has already been consumed.
524 /// bracketexpr ::= expr]
526 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
527 if (ParseExpression(Res)) return true;
528 if (Lexer.isNot(AsmToken::RBrac))
529 return TokError("expected ']' in brackets expression");
530 EndLoc = Lexer.getLoc();
535 /// ParsePrimaryExpr - Parse a primary expression and return it.
536 /// primaryexpr ::= (parenexpr
537 /// primaryexpr ::= symbol
538 /// primaryexpr ::= number
539 /// primaryexpr ::= '.'
540 /// primaryexpr ::= ~,+,- primaryexpr
541 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
542 switch (Lexer.getKind()) {
544 return TokError("unknown token in expression");
545 // If we have an error assume that we've already handled it.
546 case AsmToken::Error:
548 case AsmToken::Exclaim:
549 Lex(); // Eat the operator.
550 if (ParsePrimaryExpr(Res, EndLoc))
552 Res = MCUnaryExpr::CreateLNot(Res, getContext());
554 case AsmToken::Dollar:
555 case AsmToken::String:
556 case AsmToken::Identifier: {
557 EndLoc = Lexer.getLoc();
559 StringRef Identifier;
560 if (ParseIdentifier(Identifier))
563 // This is a symbol reference.
564 std::pair<StringRef, StringRef> Split = Identifier.split('@');
565 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
567 // Lookup the symbol variant if used.
568 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
569 if (Split.first.size() != Identifier.size()) {
570 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
571 if (Variant == MCSymbolRefExpr::VK_Invalid) {
572 Variant = MCSymbolRefExpr::VK_None;
573 return TokError("invalid variant '" + Split.second + "'");
577 // If this is an absolute variable reference, substitute it now to preserve
578 // semantics in the face of reassignment.
579 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
581 return Error(EndLoc, "unexpected modifier on variable reference");
583 Res = Sym->getVariableValue();
587 // Otherwise create a symbol ref.
588 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
591 case AsmToken::Integer: {
592 SMLoc Loc = getTok().getLoc();
593 int64_t IntVal = getTok().getIntVal();
594 Res = MCConstantExpr::Create(IntVal, getContext());
595 EndLoc = Lexer.getLoc();
597 // Look for 'b' or 'f' following an Integer as a directional label
598 if (Lexer.getKind() == AsmToken::Identifier) {
599 StringRef IDVal = getTok().getString();
600 if (IDVal == "f" || IDVal == "b"){
601 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
602 IDVal == "f" ? 1 : 0);
603 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
605 if(IDVal == "b" && Sym->isUndefined())
606 return Error(Loc, "invalid reference to undefined symbol");
607 EndLoc = Lexer.getLoc();
608 Lex(); // Eat identifier.
613 case AsmToken::Real: {
614 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
615 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
616 Res = MCConstantExpr::Create(IntVal, getContext());
620 case AsmToken::Dot: {
621 // This is a '.' reference, which references the current PC. Emit a
622 // temporary label to the streamer and refer to it.
623 MCSymbol *Sym = Ctx.CreateTempSymbol();
625 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
626 EndLoc = Lexer.getLoc();
627 Lex(); // Eat identifier.
630 case AsmToken::LParen:
631 Lex(); // Eat the '('.
632 return ParseParenExpr(Res, EndLoc);
633 case AsmToken::LBrac:
634 if (!PlatformParser->HasBracketExpressions())
635 return TokError("brackets expression not supported on this target");
636 Lex(); // Eat the '['.
637 return ParseBracketExpr(Res, EndLoc);
638 case AsmToken::Minus:
639 Lex(); // Eat the operator.
640 if (ParsePrimaryExpr(Res, EndLoc))
642 Res = MCUnaryExpr::CreateMinus(Res, getContext());
645 Lex(); // Eat the operator.
646 if (ParsePrimaryExpr(Res, EndLoc))
648 Res = MCUnaryExpr::CreatePlus(Res, getContext());
650 case AsmToken::Tilde:
651 Lex(); // Eat the operator.
652 if (ParsePrimaryExpr(Res, EndLoc))
654 Res = MCUnaryExpr::CreateNot(Res, getContext());
659 bool AsmParser::ParseExpression(const MCExpr *&Res) {
661 return ParseExpression(Res, EndLoc);
665 AsmParser::ApplyModifierToExpr(const MCExpr *E,
666 MCSymbolRefExpr::VariantKind Variant) {
667 // Recurse over the given expression, rebuilding it to apply the given variant
668 // if there is exactly one symbol.
669 switch (E->getKind()) {
671 case MCExpr::Constant:
674 case MCExpr::SymbolRef: {
675 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
677 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
678 TokError("invalid variant on expression '" +
679 getTok().getIdentifier() + "' (already modified)");
683 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
686 case MCExpr::Unary: {
687 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
688 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
691 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
694 case MCExpr::Binary: {
695 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
696 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
697 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
702 if (!LHS) LHS = BE->getLHS();
703 if (!RHS) RHS = BE->getRHS();
705 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
709 assert(0 && "Invalid expression kind!");
713 /// ParseExpression - Parse an expression and return it.
715 /// expr ::= expr +,- expr -> lowest.
716 /// expr ::= expr |,^,&,! expr -> middle.
717 /// expr ::= expr *,/,%,<<,>> expr -> highest.
718 /// expr ::= primaryexpr
720 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
721 // Parse the expression.
723 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
726 // As a special case, we support 'a op b @ modifier' by rewriting the
727 // expression to include the modifier. This is inefficient, but in general we
728 // expect users to use 'a@modifier op b'.
729 if (Lexer.getKind() == AsmToken::At) {
732 if (Lexer.isNot(AsmToken::Identifier))
733 return TokError("unexpected symbol modifier following '@'");
735 MCSymbolRefExpr::VariantKind Variant =
736 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
737 if (Variant == MCSymbolRefExpr::VK_Invalid)
738 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
740 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
742 return TokError("invalid modifier '" + getTok().getIdentifier() +
743 "' (no symbols present)");
751 // Try to constant fold it up front, if possible.
753 if (Res->EvaluateAsAbsolute(Value))
754 Res = MCConstantExpr::Create(Value, getContext());
759 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
761 return ParseParenExpr(Res, EndLoc) ||
762 ParseBinOpRHS(1, Res, EndLoc);
765 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
768 SMLoc StartLoc = Lexer.getLoc();
769 if (ParseExpression(Expr))
772 if (!Expr->EvaluateAsAbsolute(Res))
773 return Error(StartLoc, "expected absolute expression");
778 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
779 MCBinaryExpr::Opcode &Kind) {
782 return 0; // not a binop.
784 // Lowest Precedence: &&, ||, @
785 case AsmToken::AmpAmp:
786 Kind = MCBinaryExpr::LAnd;
788 case AsmToken::PipePipe:
789 Kind = MCBinaryExpr::LOr;
793 // Low Precedence: |, &, ^
795 // FIXME: gas seems to support '!' as an infix operator?
797 Kind = MCBinaryExpr::Or;
799 case AsmToken::Caret:
800 Kind = MCBinaryExpr::Xor;
803 Kind = MCBinaryExpr::And;
806 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
807 case AsmToken::EqualEqual:
808 Kind = MCBinaryExpr::EQ;
810 case AsmToken::ExclaimEqual:
811 case AsmToken::LessGreater:
812 Kind = MCBinaryExpr::NE;
815 Kind = MCBinaryExpr::LT;
817 case AsmToken::LessEqual:
818 Kind = MCBinaryExpr::LTE;
820 case AsmToken::Greater:
821 Kind = MCBinaryExpr::GT;
823 case AsmToken::GreaterEqual:
824 Kind = MCBinaryExpr::GTE;
827 // High Intermediate Precedence: +, -
829 Kind = MCBinaryExpr::Add;
831 case AsmToken::Minus:
832 Kind = MCBinaryExpr::Sub;
835 // Highest Precedence: *, /, %, <<, >>
837 Kind = MCBinaryExpr::Mul;
839 case AsmToken::Slash:
840 Kind = MCBinaryExpr::Div;
842 case AsmToken::Percent:
843 Kind = MCBinaryExpr::Mod;
845 case AsmToken::LessLess:
846 Kind = MCBinaryExpr::Shl;
848 case AsmToken::GreaterGreater:
849 Kind = MCBinaryExpr::Shr;
855 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
856 /// Res contains the LHS of the expression on input.
857 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
860 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
861 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
863 // If the next token is lower precedence than we are allowed to eat, return
864 // successfully with what we ate already.
865 if (TokPrec < Precedence)
870 // Eat the next primary expression.
872 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
874 // If BinOp binds less tightly with RHS than the operator after RHS, let
875 // the pending operator take RHS as its LHS.
876 MCBinaryExpr::Opcode Dummy;
877 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
878 if (TokPrec < NextTokPrec) {
879 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
882 // Merge LHS and RHS according to operator.
883 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
891 /// ::= EndOfStatement
892 /// ::= Label* Directive ...Operands... EndOfStatement
893 /// ::= Label* Identifier OperandList* EndOfStatement
894 bool AsmParser::ParseStatement() {
895 if (Lexer.is(AsmToken::EndOfStatement)) {
901 // Statements always start with an identifier or are a full line comment.
902 AsmToken ID = getTok();
903 SMLoc IDLoc = ID.getLoc();
905 int64_t LocalLabelVal = -1;
906 // A full line comment is a '#' as the first token.
907 if (Lexer.is(AsmToken::Hash)) {
908 EatToEndOfStatement();
912 // Allow an integer followed by a ':' as a directional local label.
913 if (Lexer.is(AsmToken::Integer)) {
914 LocalLabelVal = getTok().getIntVal();
915 if (LocalLabelVal < 0) {
916 if (!TheCondState.Ignore)
917 return TokError("unexpected token at start of statement");
921 IDVal = getTok().getString();
922 Lex(); // Consume the integer token to be used as an identifier token.
923 if (Lexer.getKind() != AsmToken::Colon) {
924 if (!TheCondState.Ignore)
925 return TokError("unexpected token at start of statement");
929 } else if (Lexer.is(AsmToken::Dot)) {
930 // Treat '.' as a valid identifier in this context.
934 } else if (ParseIdentifier(IDVal)) {
935 if (!TheCondState.Ignore)
936 return TokError("unexpected token at start of statement");
941 // Handle conditional assembly here before checking for skipping. We
942 // have to do this so that .endif isn't skipped in a ".if 0" block for
945 return ParseDirectiveIf(IDLoc);
946 if (IDVal == ".ifdef")
947 return ParseDirectiveIfdef(IDLoc, true);
948 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
949 return ParseDirectiveIfdef(IDLoc, false);
950 if (IDVal == ".elseif")
951 return ParseDirectiveElseIf(IDLoc);
952 if (IDVal == ".else")
953 return ParseDirectiveElse(IDLoc);
954 if (IDVal == ".endif")
955 return ParseDirectiveEndIf(IDLoc);
957 // If we are in a ".if 0" block, ignore this statement.
958 if (TheCondState.Ignore) {
959 EatToEndOfStatement();
963 // FIXME: Recurse on local labels?
965 // See what kind of statement we have.
966 switch (Lexer.getKind()) {
967 case AsmToken::Colon: {
968 CheckForValidSection();
970 // identifier ':' -> Label.
973 // Diagnose attempt to use '.' as a label.
975 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
977 // Diagnose attempt to use a variable as a label.
979 // FIXME: Diagnostics. Note the location of the definition as a label.
980 // FIXME: This doesn't diagnose assignment to a symbol which has been
981 // implicitly marked as external.
983 if (LocalLabelVal == -1)
984 Sym = getContext().GetOrCreateSymbol(IDVal);
986 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
987 if (!Sym->isUndefined() || Sym->isVariable())
988 return Error(IDLoc, "invalid symbol redefinition");
993 // Consume any end of statement token, if present, to avoid spurious
994 // AddBlankLine calls().
995 if (Lexer.is(AsmToken::EndOfStatement)) {
997 if (Lexer.is(AsmToken::Eof))
1001 return ParseStatement();
1004 case AsmToken::Equal:
1005 // identifier '=' ... -> assignment statement
1008 return ParseAssignment(IDVal, true);
1010 default: // Normal instruction or directive.
1014 // If macros are enabled, check to see if this is a macro instantiation.
1016 if (const Macro *M = MacroMap.lookup(IDVal))
1017 return HandleMacroEntry(IDVal, IDLoc, M);
1019 // Otherwise, we have a normal instruction or directive.
1020 if (IDVal[0] == '.' && IDVal != ".") {
1021 // Assembler features
1022 if (IDVal == ".set" || IDVal == ".equ")
1023 return ParseDirectiveSet(IDVal, true);
1024 if (IDVal == ".equiv")
1025 return ParseDirectiveSet(IDVal, false);
1029 if (IDVal == ".ascii")
1030 return ParseDirectiveAscii(IDVal, false);
1031 if (IDVal == ".asciz" || IDVal == ".string")
1032 return ParseDirectiveAscii(IDVal, true);
1034 if (IDVal == ".byte")
1035 return ParseDirectiveValue(1);
1036 if (IDVal == ".short")
1037 return ParseDirectiveValue(2);
1038 if (IDVal == ".value")
1039 return ParseDirectiveValue(2);
1040 if (IDVal == ".2byte")
1041 return ParseDirectiveValue(2);
1042 if (IDVal == ".long")
1043 return ParseDirectiveValue(4);
1044 if (IDVal == ".int")
1045 return ParseDirectiveValue(4);
1046 if (IDVal == ".4byte")
1047 return ParseDirectiveValue(4);
1048 if (IDVal == ".quad")
1049 return ParseDirectiveValue(8);
1050 if (IDVal == ".8byte")
1051 return ParseDirectiveValue(8);
1052 if (IDVal == ".single" || IDVal == ".float")
1053 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1054 if (IDVal == ".double")
1055 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1057 if (IDVal == ".align") {
1058 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1059 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1061 if (IDVal == ".align32") {
1062 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1063 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1065 if (IDVal == ".balign")
1066 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1067 if (IDVal == ".balignw")
1068 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1069 if (IDVal == ".balignl")
1070 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1071 if (IDVal == ".p2align")
1072 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1073 if (IDVal == ".p2alignw")
1074 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1075 if (IDVal == ".p2alignl")
1076 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1078 if (IDVal == ".org")
1079 return ParseDirectiveOrg();
1081 if (IDVal == ".fill")
1082 return ParseDirectiveFill();
1083 if (IDVal == ".space" || IDVal == ".skip")
1084 return ParseDirectiveSpace();
1085 if (IDVal == ".zero")
1086 return ParseDirectiveZero();
1088 // Symbol attribute directives
1090 if (IDVal == ".globl" || IDVal == ".global")
1091 return ParseDirectiveSymbolAttribute(MCSA_Global);
1092 // ELF only? Should it be here?
1093 if (IDVal == ".local")
1094 return ParseDirectiveSymbolAttribute(MCSA_Local);
1095 if (IDVal == ".hidden")
1096 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1097 if (IDVal == ".indirect_symbol")
1098 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1099 if (IDVal == ".internal")
1100 return ParseDirectiveSymbolAttribute(MCSA_Internal);
1101 if (IDVal == ".lazy_reference")
1102 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1103 if (IDVal == ".no_dead_strip")
1104 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1105 if (IDVal == ".symbol_resolver")
1106 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1107 if (IDVal == ".private_extern")
1108 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1109 if (IDVal == ".protected")
1110 return ParseDirectiveSymbolAttribute(MCSA_Protected);
1111 if (IDVal == ".reference")
1112 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1113 if (IDVal == ".weak")
1114 return ParseDirectiveSymbolAttribute(MCSA_Weak);
1115 if (IDVal == ".weak_definition")
1116 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1117 if (IDVal == ".weak_reference")
1118 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1119 if (IDVal == ".weak_def_can_be_hidden")
1120 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1122 if (IDVal == ".comm")
1123 return ParseDirectiveComm(/*IsLocal=*/false);
1124 if (IDVal == ".lcomm")
1125 return ParseDirectiveComm(/*IsLocal=*/true);
1127 if (IDVal == ".abort")
1128 return ParseDirectiveAbort();
1129 if (IDVal == ".include")
1130 return ParseDirectiveInclude();
1132 if (IDVal == ".code16" || IDVal == ".code32" || IDVal == ".code64")
1133 return TokError(Twine(IDVal) + " not supported yet");
1135 // Look up the handler in the handler table.
1136 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1137 DirectiveMap.lookup(IDVal);
1139 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1141 // Target hook for parsing target specific directives.
1142 if (!getTargetParser().ParseDirective(ID))
1145 Warning(IDLoc, "ignoring directive for now");
1146 EatToEndOfStatement();
1150 CheckForValidSection();
1152 // Canonicalize the opcode to lower case.
1153 SmallString<128> Opcode;
1154 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1155 Opcode.push_back(tolower(IDVal[i]));
1157 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1158 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1161 // Dump the parsed representation, if requested.
1162 if (getShowParsedOperands()) {
1163 SmallString<256> Str;
1164 raw_svector_ostream OS(Str);
1165 OS << "parsed instruction: [";
1166 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1169 ParsedOperands[i]->dump(OS);
1173 PrintMessage(IDLoc, OS.str(), "note");
1176 // If parsing succeeded, match the instruction.
1178 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1181 // Free any parsed operands.
1182 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1183 delete ParsedOperands[i];
1185 // Don't skip the rest of the line, the instruction parser is responsible for
1190 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1191 const std::vector<std::vector<AsmToken> > &A)
1192 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1194 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1195 // to hold the macro body with substitutions.
1196 SmallString<256> Buf;
1197 raw_svector_ostream OS(Buf);
1199 StringRef Body = M->Body;
1200 while (!Body.empty()) {
1201 // Scan for the next substitution.
1202 std::size_t End = Body.size(), Pos = 0;
1203 for (; Pos != End; ++Pos) {
1204 // Check for a substitution or escape.
1205 if (Body[Pos] != '$' || Pos + 1 == End)
1208 char Next = Body[Pos + 1];
1209 if (Next == '$' || Next == 'n' || isdigit(Next))
1214 OS << Body.slice(0, Pos);
1216 // Check if we reached the end.
1220 switch (Body[Pos+1]) {
1226 // $n => number of arguments
1231 // $[0-9] => argument
1233 // Missing arguments are ignored.
1234 unsigned Index = Body[Pos+1] - '0';
1235 if (Index >= A.size())
1238 // Otherwise substitute with the token values, with spaces eliminated.
1239 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1240 ie = A[Index].end(); it != ie; ++it)
1241 OS << it->getString();
1246 // Update the scan point.
1247 Body = Body.substr(Pos + 2);
1250 // We include the .endmacro in the buffer as our queue to exit the macro
1252 OS << ".endmacro\n";
1254 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1257 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1259 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1260 // this, although we should protect against infinite loops.
1261 if (ActiveMacros.size() == 20)
1262 return TokError("macros cannot be nested more than 20 levels deep");
1264 // Parse the macro instantiation arguments.
1265 std::vector<std::vector<AsmToken> > MacroArguments;
1266 MacroArguments.push_back(std::vector<AsmToken>());
1267 unsigned ParenLevel = 0;
1269 if (Lexer.is(AsmToken::Eof))
1270 return TokError("unexpected token in macro instantiation");
1271 if (Lexer.is(AsmToken::EndOfStatement))
1274 // If we aren't inside parentheses and this is a comma, start a new token
1276 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1277 MacroArguments.push_back(std::vector<AsmToken>());
1279 // Adjust the current parentheses level.
1280 if (Lexer.is(AsmToken::LParen))
1282 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1285 // Append the token to the current argument list.
1286 MacroArguments.back().push_back(getTok());
1291 // Create the macro instantiation object and add to the current macro
1292 // instantiation stack.
1293 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1296 ActiveMacros.push_back(MI);
1298 // Jump to the macro instantiation and prime the lexer.
1299 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1300 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1306 void AsmParser::HandleMacroExit() {
1307 // Jump to the EndOfStatement we should return to, and consume it.
1308 JumpToLoc(ActiveMacros.back()->ExitLoc);
1311 // Pop the instantiation entry.
1312 delete ActiveMacros.back();
1313 ActiveMacros.pop_back();
1316 static void MarkUsed(const MCExpr *Value) {
1317 switch (Value->getKind()) {
1318 case MCExpr::Binary:
1319 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1320 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1322 case MCExpr::Target:
1323 case MCExpr::Constant:
1325 case MCExpr::SymbolRef: {
1326 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1330 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1335 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1336 // FIXME: Use better location, we should use proper tokens.
1337 SMLoc EqualLoc = Lexer.getLoc();
1339 const MCExpr *Value;
1340 if (ParseExpression(Value))
1345 if (Lexer.isNot(AsmToken::EndOfStatement))
1346 return TokError("unexpected token in assignment");
1348 // Error on assignment to '.'.
1350 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1351 "(use '.space' or '.org').)"));
1354 // Eat the end of statement marker.
1357 // Validate that the LHS is allowed to be a variable (either it has not been
1358 // used as a symbol, or it is an absolute symbol).
1359 MCSymbol *Sym = getContext().LookupSymbol(Name);
1361 // Diagnose assignment to a label.
1363 // FIXME: Diagnostics. Note the location of the definition as a label.
1364 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1365 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1366 ; // Allow redefinitions of undefined symbols only used in directives.
1367 else if (!Sym->isUndefined() && (!Sym->isAbsolute() || !allow_redef))
1368 return Error(EqualLoc, "redefinition of '" + Name + "'");
1369 else if (!Sym->isVariable())
1370 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1371 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1372 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1375 // Don't count these checks as uses.
1376 Sym->setUsed(false);
1378 Sym = getContext().GetOrCreateSymbol(Name);
1380 // FIXME: Handle '.'.
1382 // Do the assignment.
1383 Out.EmitAssignment(Sym, Value);
1388 /// ParseIdentifier:
1391 bool AsmParser::ParseIdentifier(StringRef &Res) {
1392 // The assembler has relaxed rules for accepting identifiers, in particular we
1393 // allow things like '.globl $foo', which would normally be separate
1394 // tokens. At this level, we have already lexed so we cannot (currently)
1395 // handle this as a context dependent token, instead we detect adjacent tokens
1396 // and return the combined identifier.
1397 if (Lexer.is(AsmToken::Dollar)) {
1398 SMLoc DollarLoc = getLexer().getLoc();
1400 // Consume the dollar sign, and check for a following identifier.
1402 if (Lexer.isNot(AsmToken::Identifier))
1405 // We have a '$' followed by an identifier, make sure they are adjacent.
1406 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1409 // Construct the joined identifier and consume the token.
1410 Res = StringRef(DollarLoc.getPointer(),
1411 getTok().getIdentifier().size() + 1);
1416 if (Lexer.isNot(AsmToken::Identifier) &&
1417 Lexer.isNot(AsmToken::String))
1420 Res = getTok().getIdentifier();
1422 Lex(); // Consume the identifier token.
1427 /// ParseDirectiveSet:
1428 /// ::= .equ identifier ',' expression
1429 /// ::= .equiv identifier ',' expression
1430 /// ::= .set identifier ',' expression
1431 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1434 if (ParseIdentifier(Name))
1435 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1437 if (getLexer().isNot(AsmToken::Comma))
1438 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1441 return ParseAssignment(Name, allow_redef);
1444 bool AsmParser::ParseEscapedString(std::string &Data) {
1445 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1448 StringRef Str = getTok().getStringContents();
1449 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1450 if (Str[i] != '\\') {
1455 // Recognize escaped characters. Note that this escape semantics currently
1456 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1459 return TokError("unexpected backslash at end of string");
1461 // Recognize octal sequences.
1462 if ((unsigned) (Str[i] - '0') <= 7) {
1463 // Consume up to three octal characters.
1464 unsigned Value = Str[i] - '0';
1466 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1468 Value = Value * 8 + (Str[i] - '0');
1470 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1472 Value = Value * 8 + (Str[i] - '0');
1477 return TokError("invalid octal escape sequence (out of range)");
1479 Data += (unsigned char) Value;
1483 // Otherwise recognize individual escapes.
1486 // Just reject invalid escape sequences for now.
1487 return TokError("invalid escape sequence (unrecognized character)");
1489 case 'b': Data += '\b'; break;
1490 case 'f': Data += '\f'; break;
1491 case 'n': Data += '\n'; break;
1492 case 'r': Data += '\r'; break;
1493 case 't': Data += '\t'; break;
1494 case '"': Data += '"'; break;
1495 case '\\': Data += '\\'; break;
1502 /// ParseDirectiveAscii:
1503 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1504 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1505 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1506 CheckForValidSection();
1509 if (getLexer().isNot(AsmToken::String))
1510 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1513 if (ParseEscapedString(Data))
1516 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1518 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1522 if (getLexer().is(AsmToken::EndOfStatement))
1525 if (getLexer().isNot(AsmToken::Comma))
1526 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1535 /// ParseDirectiveValue
1536 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1537 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1538 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1539 CheckForValidSection();
1542 const MCExpr *Value;
1543 if (ParseExpression(Value))
1546 // Special case constant expressions to match code generator.
1547 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1548 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1550 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1552 if (getLexer().is(AsmToken::EndOfStatement))
1555 // FIXME: Improve diagnostic.
1556 if (getLexer().isNot(AsmToken::Comma))
1557 return TokError("unexpected token in directive");
1566 /// ParseDirectiveRealValue
1567 /// ::= (.single | .double) [ expression (, expression)* ]
1568 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1569 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1570 CheckForValidSection();
1573 // We don't truly support arithmetic on floating point expressions, so we
1574 // have to manually parse unary prefixes.
1576 if (getLexer().is(AsmToken::Minus)) {
1579 } else if (getLexer().is(AsmToken::Plus))
1582 if (getLexer().isNot(AsmToken::Integer) &&
1583 getLexer().isNot(AsmToken::Real) &&
1584 getLexer().isNot(AsmToken::Identifier))
1585 return TokError("unexpected token in directive");
1587 // Convert to an APFloat.
1588 APFloat Value(Semantics);
1589 StringRef IDVal = getTok().getString();
1590 if (getLexer().is(AsmToken::Identifier)) {
1591 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1592 Value = APFloat::getInf(Semantics);
1593 else if (!IDVal.compare_lower("nan"))
1594 Value = APFloat::getNaN(Semantics, false, ~0);
1596 return TokError("invalid floating point literal");
1597 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1598 APFloat::opInvalidOp)
1599 return TokError("invalid floating point literal");
1603 // Consume the numeric token.
1606 // Emit the value as an integer.
1607 APInt AsInt = Value.bitcastToAPInt();
1608 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1609 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1611 if (getLexer().is(AsmToken::EndOfStatement))
1614 if (getLexer().isNot(AsmToken::Comma))
1615 return TokError("unexpected token in directive");
1624 /// ParseDirectiveSpace
1625 /// ::= .space expression [ , expression ]
1626 bool AsmParser::ParseDirectiveSpace() {
1627 CheckForValidSection();
1630 if (ParseAbsoluteExpression(NumBytes))
1633 int64_t FillExpr = 0;
1634 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1635 if (getLexer().isNot(AsmToken::Comma))
1636 return TokError("unexpected token in '.space' directive");
1639 if (ParseAbsoluteExpression(FillExpr))
1642 if (getLexer().isNot(AsmToken::EndOfStatement))
1643 return TokError("unexpected token in '.space' directive");
1649 return TokError("invalid number of bytes in '.space' directive");
1651 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1652 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1657 /// ParseDirectiveZero
1658 /// ::= .zero expression
1659 bool AsmParser::ParseDirectiveZero() {
1660 CheckForValidSection();
1663 if (ParseAbsoluteExpression(NumBytes))
1667 if (getLexer().is(AsmToken::Comma)) {
1669 if (ParseAbsoluteExpression(Val))
1673 if (getLexer().isNot(AsmToken::EndOfStatement))
1674 return TokError("unexpected token in '.zero' directive");
1678 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1683 /// ParseDirectiveFill
1684 /// ::= .fill expression , expression , expression
1685 bool AsmParser::ParseDirectiveFill() {
1686 CheckForValidSection();
1689 if (ParseAbsoluteExpression(NumValues))
1692 if (getLexer().isNot(AsmToken::Comma))
1693 return TokError("unexpected token in '.fill' directive");
1697 if (ParseAbsoluteExpression(FillSize))
1700 if (getLexer().isNot(AsmToken::Comma))
1701 return TokError("unexpected token in '.fill' directive");
1705 if (ParseAbsoluteExpression(FillExpr))
1708 if (getLexer().isNot(AsmToken::EndOfStatement))
1709 return TokError("unexpected token in '.fill' directive");
1713 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1714 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1716 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1717 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1722 /// ParseDirectiveOrg
1723 /// ::= .org expression [ , expression ]
1724 bool AsmParser::ParseDirectiveOrg() {
1725 CheckForValidSection();
1727 const MCExpr *Offset;
1728 if (ParseExpression(Offset))
1731 // Parse optional fill expression.
1732 int64_t FillExpr = 0;
1733 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1734 if (getLexer().isNot(AsmToken::Comma))
1735 return TokError("unexpected token in '.org' directive");
1738 if (ParseAbsoluteExpression(FillExpr))
1741 if (getLexer().isNot(AsmToken::EndOfStatement))
1742 return TokError("unexpected token in '.org' directive");
1747 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1748 // has to be relative to the current section.
1749 getStreamer().EmitValueToOffset(Offset, FillExpr);
1754 /// ParseDirectiveAlign
1755 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1756 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1757 CheckForValidSection();
1759 SMLoc AlignmentLoc = getLexer().getLoc();
1761 if (ParseAbsoluteExpression(Alignment))
1765 bool HasFillExpr = false;
1766 int64_t FillExpr = 0;
1767 int64_t MaxBytesToFill = 0;
1768 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1769 if (getLexer().isNot(AsmToken::Comma))
1770 return TokError("unexpected token in directive");
1773 // The fill expression can be omitted while specifying a maximum number of
1774 // alignment bytes, e.g:
1776 if (getLexer().isNot(AsmToken::Comma)) {
1778 if (ParseAbsoluteExpression(FillExpr))
1782 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1783 if (getLexer().isNot(AsmToken::Comma))
1784 return TokError("unexpected token in directive");
1787 MaxBytesLoc = getLexer().getLoc();
1788 if (ParseAbsoluteExpression(MaxBytesToFill))
1791 if (getLexer().isNot(AsmToken::EndOfStatement))
1792 return TokError("unexpected token in directive");
1801 // Compute alignment in bytes.
1803 // FIXME: Diagnose overflow.
1804 if (Alignment >= 32) {
1805 Error(AlignmentLoc, "invalid alignment value");
1809 Alignment = 1ULL << Alignment;
1812 // Diagnose non-sensical max bytes to align.
1813 if (MaxBytesLoc.isValid()) {
1814 if (MaxBytesToFill < 1) {
1815 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1816 "many bytes, ignoring maximum bytes expression");
1820 if (MaxBytesToFill >= Alignment) {
1821 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1827 // Check whether we should use optimal code alignment for this .align
1829 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1830 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1831 ValueSize == 1 && UseCodeAlign) {
1832 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1834 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1835 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1842 /// ParseDirectiveSymbolAttribute
1843 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1844 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1845 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1849 if (ParseIdentifier(Name))
1850 return TokError("expected identifier in directive");
1852 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1854 getStreamer().EmitSymbolAttribute(Sym, Attr);
1856 if (getLexer().is(AsmToken::EndOfStatement))
1859 if (getLexer().isNot(AsmToken::Comma))
1860 return TokError("unexpected token in directive");
1869 /// ParseDirectiveComm
1870 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1871 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1872 CheckForValidSection();
1874 SMLoc IDLoc = getLexer().getLoc();
1876 if (ParseIdentifier(Name))
1877 return TokError("expected identifier in directive");
1879 // Handle the identifier as the key symbol.
1880 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1882 if (getLexer().isNot(AsmToken::Comma))
1883 return TokError("unexpected token in directive");
1887 SMLoc SizeLoc = getLexer().getLoc();
1888 if (ParseAbsoluteExpression(Size))
1891 int64_t Pow2Alignment = 0;
1892 SMLoc Pow2AlignmentLoc;
1893 if (getLexer().is(AsmToken::Comma)) {
1895 Pow2AlignmentLoc = getLexer().getLoc();
1896 if (ParseAbsoluteExpression(Pow2Alignment))
1899 // If this target takes alignments in bytes (not log) validate and convert.
1900 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1901 if (!isPowerOf2_64(Pow2Alignment))
1902 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1903 Pow2Alignment = Log2_64(Pow2Alignment);
1907 if (getLexer().isNot(AsmToken::EndOfStatement))
1908 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1912 // NOTE: a size of zero for a .comm should create a undefined symbol
1913 // but a size of .lcomm creates a bss symbol of size zero.
1915 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1916 "be less than zero");
1918 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1919 // may internally end up wanting an alignment in bytes.
1920 // FIXME: Diagnose overflow.
1921 if (Pow2Alignment < 0)
1922 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1923 "alignment, can't be less than zero");
1925 if (!Sym->isUndefined())
1926 return Error(IDLoc, "invalid symbol redefinition");
1928 // '.lcomm' is equivalent to '.zerofill'.
1929 // Create the Symbol as a common or local common with Size and Pow2Alignment
1931 getStreamer().EmitZerofill(Ctx.getMachOSection(
1932 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1933 0, SectionKind::getBSS()),
1934 Sym, Size, 1 << Pow2Alignment);
1938 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1942 /// ParseDirectiveAbort
1943 /// ::= .abort [... message ...]
1944 bool AsmParser::ParseDirectiveAbort() {
1945 // FIXME: Use loc from directive.
1946 SMLoc Loc = getLexer().getLoc();
1948 StringRef Str = ParseStringToEndOfStatement();
1949 if (getLexer().isNot(AsmToken::EndOfStatement))
1950 return TokError("unexpected token in '.abort' directive");
1955 Error(Loc, ".abort detected. Assembly stopping.");
1957 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1958 // FIXME: Actually abort assembly here.
1963 /// ParseDirectiveInclude
1964 /// ::= .include "filename"
1965 bool AsmParser::ParseDirectiveInclude() {
1966 if (getLexer().isNot(AsmToken::String))
1967 return TokError("expected string in '.include' directive");
1969 std::string Filename = getTok().getString();
1970 SMLoc IncludeLoc = getLexer().getLoc();
1973 if (getLexer().isNot(AsmToken::EndOfStatement))
1974 return TokError("unexpected token in '.include' directive");
1976 // Strip the quotes.
1977 Filename = Filename.substr(1, Filename.size()-2);
1979 // Attempt to switch the lexer to the included file before consuming the end
1980 // of statement to avoid losing it when we switch.
1981 if (EnterIncludeFile(Filename)) {
1982 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1989 /// ParseDirectiveIf
1990 /// ::= .if expression
1991 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1992 TheCondStack.push_back(TheCondState);
1993 TheCondState.TheCond = AsmCond::IfCond;
1994 if(TheCondState.Ignore) {
1995 EatToEndOfStatement();
1999 if (ParseAbsoluteExpression(ExprValue))
2002 if (getLexer().isNot(AsmToken::EndOfStatement))
2003 return TokError("unexpected token in '.if' directive");
2007 TheCondState.CondMet = ExprValue;
2008 TheCondState.Ignore = !TheCondState.CondMet;
2014 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2016 TheCondStack.push_back(TheCondState);
2017 TheCondState.TheCond = AsmCond::IfCond;
2019 if (TheCondState.Ignore) {
2020 EatToEndOfStatement();
2022 if (ParseIdentifier(Name))
2023 return TokError("expected identifier after '.ifdef'");
2027 MCSymbol *Sym = getContext().LookupSymbol(Name);
2030 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2032 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2033 TheCondState.Ignore = !TheCondState.CondMet;
2039 /// ParseDirectiveElseIf
2040 /// ::= .elseif expression
2041 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2042 if (TheCondState.TheCond != AsmCond::IfCond &&
2043 TheCondState.TheCond != AsmCond::ElseIfCond)
2044 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2046 TheCondState.TheCond = AsmCond::ElseIfCond;
2048 bool LastIgnoreState = false;
2049 if (!TheCondStack.empty())
2050 LastIgnoreState = TheCondStack.back().Ignore;
2051 if (LastIgnoreState || TheCondState.CondMet) {
2052 TheCondState.Ignore = true;
2053 EatToEndOfStatement();
2057 if (ParseAbsoluteExpression(ExprValue))
2060 if (getLexer().isNot(AsmToken::EndOfStatement))
2061 return TokError("unexpected token in '.elseif' directive");
2064 TheCondState.CondMet = ExprValue;
2065 TheCondState.Ignore = !TheCondState.CondMet;
2071 /// ParseDirectiveElse
2073 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2074 if (getLexer().isNot(AsmToken::EndOfStatement))
2075 return TokError("unexpected token in '.else' directive");
2079 if (TheCondState.TheCond != AsmCond::IfCond &&
2080 TheCondState.TheCond != AsmCond::ElseIfCond)
2081 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2083 TheCondState.TheCond = AsmCond::ElseCond;
2084 bool LastIgnoreState = false;
2085 if (!TheCondStack.empty())
2086 LastIgnoreState = TheCondStack.back().Ignore;
2087 if (LastIgnoreState || TheCondState.CondMet)
2088 TheCondState.Ignore = true;
2090 TheCondState.Ignore = false;
2095 /// ParseDirectiveEndIf
2097 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2098 if (getLexer().isNot(AsmToken::EndOfStatement))
2099 return TokError("unexpected token in '.endif' directive");
2103 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2104 TheCondStack.empty())
2105 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2107 if (!TheCondStack.empty()) {
2108 TheCondState = TheCondStack.back();
2109 TheCondStack.pop_back();
2115 /// ParseDirectiveFile
2116 /// ::= .file [number] string
2117 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2118 // FIXME: I'm not sure what this is.
2119 int64_t FileNumber = -1;
2120 SMLoc FileNumberLoc = getLexer().getLoc();
2121 if (getLexer().is(AsmToken::Integer)) {
2122 FileNumber = getTok().getIntVal();
2126 return TokError("file number less than one");
2129 if (getLexer().isNot(AsmToken::String))
2130 return TokError("unexpected token in '.file' directive");
2132 StringRef Filename = getTok().getString();
2133 Filename = Filename.substr(1, Filename.size()-2);
2136 if (getLexer().isNot(AsmToken::EndOfStatement))
2137 return TokError("unexpected token in '.file' directive");
2139 if (FileNumber == -1)
2140 getStreamer().EmitFileDirective(Filename);
2142 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2143 Error(FileNumberLoc, "file number already allocated");
2149 /// ParseDirectiveLine
2150 /// ::= .line [number]
2151 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2152 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2153 if (getLexer().isNot(AsmToken::Integer))
2154 return TokError("unexpected token in '.line' directive");
2156 int64_t LineNumber = getTok().getIntVal();
2160 // FIXME: Do something with the .line.
2163 if (getLexer().isNot(AsmToken::EndOfStatement))
2164 return TokError("unexpected token in '.line' directive");
2170 /// ParseDirectiveLoc
2171 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2172 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2173 /// The first number is a file number, must have been previously assigned with
2174 /// a .file directive, the second number is the line number and optionally the
2175 /// third number is a column position (zero if not specified). The remaining
2176 /// optional items are .loc sub-directives.
2177 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2179 if (getLexer().isNot(AsmToken::Integer))
2180 return TokError("unexpected token in '.loc' directive");
2181 int64_t FileNumber = getTok().getIntVal();
2183 return TokError("file number less than one in '.loc' directive");
2184 if (!getContext().isValidDwarfFileNumber(FileNumber))
2185 return TokError("unassigned file number in '.loc' directive");
2188 int64_t LineNumber = 0;
2189 if (getLexer().is(AsmToken::Integer)) {
2190 LineNumber = getTok().getIntVal();
2192 return TokError("line number less than one in '.loc' directive");
2196 int64_t ColumnPos = 0;
2197 if (getLexer().is(AsmToken::Integer)) {
2198 ColumnPos = getTok().getIntVal();
2200 return TokError("column position less than zero in '.loc' directive");
2204 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2206 int64_t Discriminator = 0;
2207 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2209 if (getLexer().is(AsmToken::EndOfStatement))
2213 SMLoc Loc = getTok().getLoc();
2214 if (getParser().ParseIdentifier(Name))
2215 return TokError("unexpected token in '.loc' directive");
2217 if (Name == "basic_block")
2218 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2219 else if (Name == "prologue_end")
2220 Flags |= DWARF2_FLAG_PROLOGUE_END;
2221 else if (Name == "epilogue_begin")
2222 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2223 else if (Name == "is_stmt") {
2224 SMLoc Loc = getTok().getLoc();
2225 const MCExpr *Value;
2226 if (getParser().ParseExpression(Value))
2228 // The expression must be the constant 0 or 1.
2229 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2230 int Value = MCE->getValue();
2232 Flags &= ~DWARF2_FLAG_IS_STMT;
2233 else if (Value == 1)
2234 Flags |= DWARF2_FLAG_IS_STMT;
2236 return Error(Loc, "is_stmt value not 0 or 1");
2239 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2242 else if (Name == "isa") {
2243 SMLoc Loc = getTok().getLoc();
2244 const MCExpr *Value;
2245 if (getParser().ParseExpression(Value))
2247 // The expression must be a constant greater or equal to 0.
2248 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2249 int Value = MCE->getValue();
2251 return Error(Loc, "isa number less than zero");
2255 return Error(Loc, "isa number not a constant value");
2258 else if (Name == "discriminator") {
2259 if (getParser().ParseAbsoluteExpression(Discriminator))
2263 return Error(Loc, "unknown sub-directive in '.loc' directive");
2266 if (getLexer().is(AsmToken::EndOfStatement))
2271 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2272 Isa, Discriminator);
2277 /// ParseDirectiveStabs
2278 /// ::= .stabs string, number, number, number
2279 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2280 SMLoc DirectiveLoc) {
2281 return TokError("unsupported directive '" + Directive + "'");
2284 /// ParseDirectiveCFIStartProc
2285 /// ::= .cfi_startproc
2286 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2287 SMLoc DirectiveLoc) {
2288 return getStreamer().EmitCFIStartProc();
2291 /// ParseDirectiveCFIEndProc
2292 /// ::= .cfi_endproc
2293 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2294 return getStreamer().EmitCFIEndProc();
2297 /// ParseRegisterOrRegisterNumber - parse register name or number.
2298 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2299 SMLoc DirectiveLoc) {
2302 if (getLexer().is(AsmToken::Percent)) {
2303 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2306 Register = getContext().getTargetAsmInfo().getDwarfRegNum(RegNo, true);
2308 return getParser().ParseAbsoluteExpression(Register);
2313 /// ParseDirectiveCFIDefCfa
2314 /// ::= .cfi_def_cfa register, offset
2315 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2316 SMLoc DirectiveLoc) {
2317 int64_t Register = 0;
2318 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2321 if (getLexer().isNot(AsmToken::Comma))
2322 return TokError("unexpected token in directive");
2326 if (getParser().ParseAbsoluteExpression(Offset))
2329 return getStreamer().EmitCFIDefCfa(Register, Offset);
2332 /// ParseDirectiveCFIDefCfaOffset
2333 /// ::= .cfi_def_cfa_offset offset
2334 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2335 SMLoc DirectiveLoc) {
2337 if (getParser().ParseAbsoluteExpression(Offset))
2340 getParser().setLastOffset(Offset);
2342 return getStreamer().EmitCFIDefCfaOffset(Offset);
2345 /// ParseDirectiveCFIAdjustCfaOffset
2346 /// ::= .cfi_adjust_cfa_offset adjustment
2347 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2348 SMLoc DirectiveLoc) {
2349 int64_t Adjustment = 0;
2350 if (getParser().ParseAbsoluteExpression(Adjustment))
2353 int64_t Offset = getParser().adjustLastOffset(Adjustment);
2355 return getStreamer().EmitCFIDefCfaOffset(Offset);
2358 /// ParseDirectiveCFIDefCfaRegister
2359 /// ::= .cfi_def_cfa_register register
2360 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2361 SMLoc DirectiveLoc) {
2362 int64_t Register = 0;
2363 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2366 return getStreamer().EmitCFIDefCfaRegister(Register);
2369 /// ParseDirectiveCFIOffset
2370 /// ::= .cfi_offset register, offset
2371 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2372 int64_t Register = 0;
2375 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2378 if (getLexer().isNot(AsmToken::Comma))
2379 return TokError("unexpected token in directive");
2382 if (getParser().ParseAbsoluteExpression(Offset))
2385 return getStreamer().EmitCFIOffset(Register, Offset);
2388 /// ParseDirectiveCFIRelOffset
2389 /// ::= .cfi_rel_offset register, offset
2390 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2391 SMLoc DirectiveLoc) {
2392 int64_t Register = 0;
2394 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2397 if (getLexer().isNot(AsmToken::Comma))
2398 return TokError("unexpected token in directive");
2402 if (getParser().ParseAbsoluteExpression(Offset))
2405 Offset -= getParser().getLastOffset();
2407 return getStreamer().EmitCFIOffset(Register, Offset);
2410 static bool isValidEncoding(int64_t Encoding) {
2411 if (Encoding & ~0xff)
2414 if (Encoding == dwarf::DW_EH_PE_omit)
2417 const unsigned Format = Encoding & 0xf;
2418 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2419 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2420 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2421 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2424 const unsigned Application = Encoding & 0x70;
2425 if (Application != dwarf::DW_EH_PE_absptr &&
2426 Application != dwarf::DW_EH_PE_pcrel)
2432 /// ParseDirectiveCFIPersonalityOrLsda
2433 /// ::= .cfi_personality encoding, [symbol_name]
2434 /// ::= .cfi_lsda encoding, [symbol_name]
2435 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2436 SMLoc DirectiveLoc) {
2437 int64_t Encoding = 0;
2438 if (getParser().ParseAbsoluteExpression(Encoding))
2440 if (Encoding == dwarf::DW_EH_PE_omit)
2443 if (!isValidEncoding(Encoding))
2444 return TokError("unsupported encoding.");
2446 if (getLexer().isNot(AsmToken::Comma))
2447 return TokError("unexpected token in directive");
2451 if (getParser().ParseIdentifier(Name))
2452 return TokError("expected identifier in directive");
2454 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2456 if (IDVal == ".cfi_personality")
2457 return getStreamer().EmitCFIPersonality(Sym, Encoding);
2459 assert(IDVal == ".cfi_lsda");
2460 return getStreamer().EmitCFILsda(Sym, Encoding);
2464 /// ParseDirectiveCFIRememberState
2465 /// ::= .cfi_remember_state
2466 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2467 SMLoc DirectiveLoc) {
2468 return getStreamer().EmitCFIRememberState();
2471 /// ParseDirectiveCFIRestoreState
2472 /// ::= .cfi_remember_state
2473 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2474 SMLoc DirectiveLoc) {
2475 return getStreamer().EmitCFIRestoreState();
2478 /// ParseDirectiveCFISameValue
2479 /// ::= .cfi_same_value register
2480 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2481 SMLoc DirectiveLoc) {
2482 int64_t Register = 0;
2484 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2487 getStreamer().EmitCFISameValue(Register);
2492 /// ParseDirectiveMacrosOnOff
2495 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2496 SMLoc DirectiveLoc) {
2497 if (getLexer().isNot(AsmToken::EndOfStatement))
2498 return Error(getLexer().getLoc(),
2499 "unexpected token in '" + Directive + "' directive");
2501 getParser().MacrosEnabled = Directive == ".macros_on";
2506 /// ParseDirectiveMacro
2508 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2509 SMLoc DirectiveLoc) {
2511 if (getParser().ParseIdentifier(Name))
2512 return TokError("expected identifier in directive");
2514 if (getLexer().isNot(AsmToken::EndOfStatement))
2515 return TokError("unexpected token in '.macro' directive");
2517 // Eat the end of statement.
2520 AsmToken EndToken, StartToken = getTok();
2522 // Lex the macro definition.
2524 // Check whether we have reached the end of the file.
2525 if (getLexer().is(AsmToken::Eof))
2526 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2528 // Otherwise, check whether we have reach the .endmacro.
2529 if (getLexer().is(AsmToken::Identifier) &&
2530 (getTok().getIdentifier() == ".endm" ||
2531 getTok().getIdentifier() == ".endmacro")) {
2532 EndToken = getTok();
2534 if (getLexer().isNot(AsmToken::EndOfStatement))
2535 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2540 // Otherwise, scan til the end of the statement.
2541 getParser().EatToEndOfStatement();
2544 if (getParser().MacroMap.lookup(Name)) {
2545 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2548 const char *BodyStart = StartToken.getLoc().getPointer();
2549 const char *BodyEnd = EndToken.getLoc().getPointer();
2550 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2551 getParser().MacroMap[Name] = new Macro(Name, Body);
2555 /// ParseDirectiveEndMacro
2558 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2559 SMLoc DirectiveLoc) {
2560 if (getLexer().isNot(AsmToken::EndOfStatement))
2561 return TokError("unexpected token in '" + Directive + "' directive");
2563 // If we are inside a macro instantiation, terminate the current
2565 if (!getParser().ActiveMacros.empty()) {
2566 getParser().HandleMacroExit();
2570 // Otherwise, this .endmacro is a stray entry in the file; well formed
2571 // .endmacro directives are handled during the macro definition parsing.
2572 return TokError("unexpected '" + Directive + "' in file, "
2573 "no current macro definition");
2576 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2577 getParser().CheckForValidSection();
2579 const MCExpr *Value;
2581 if (getParser().ParseExpression(Value))
2584 if (getLexer().isNot(AsmToken::EndOfStatement))
2585 return TokError("unexpected token in directive");
2587 if (DirName[1] == 's')
2588 getStreamer().EmitSLEB128Value(Value);
2590 getStreamer().EmitULEB128Value(Value);
2596 /// \brief Create an MCAsmParser instance.
2597 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2598 MCContext &C, MCStreamer &Out,
2599 const MCAsmInfo &MAI) {
2600 return new AsmParser(T, SM, C, Out, MAI);