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/CommandLine.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetAsmInfo.h"
35 #include "llvm/Target/TargetAsmParser.h"
41 FatalAssemblerWarnings("fatal-assembler-warnings",
42 cl::desc("Consider warnings as error"));
46 /// \brief Helper class for tracking macro definitions.
50 std::vector<StringRef> Parameters;
53 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
54 Name(N), Body(B), Parameters(P) {}
57 /// \brief Helper class for storing information about an active macro
59 struct MacroInstantiation {
60 /// The macro being instantiated.
61 const Macro *TheMacro;
63 /// The macro instantiation with substitutions.
64 MemoryBuffer *Instantiation;
66 /// The location of the instantiation.
67 SMLoc InstantiationLoc;
69 /// The location where parsing should resume upon instantiation completion.
73 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
77 /// \brief The concrete assembly parser instance.
78 class AsmParser : public MCAsmParser {
79 friend class GenericAsmParser;
81 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
82 void operator=(const AsmParser &); // DO NOT IMPLEMENT
88 MCAsmParserExtension *GenericParser;
89 MCAsmParserExtension *PlatformParser;
91 /// This is the current buffer index we're lexing from as managed by the
96 std::vector<AsmCond> TheCondStack;
98 /// DirectiveMap - This is a table handlers for directives. Each handler is
99 /// invoked after the directive identifier is read and is responsible for
100 /// parsing and validating the rest of the directive. The handler is passed
101 /// in the directive name and the location of the directive keyword.
102 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
104 /// MacroMap - Map of currently defined macros.
105 StringMap<Macro*> MacroMap;
107 /// ActiveMacros - Stack of active macro instantiations.
108 std::vector<MacroInstantiation*> ActiveMacros;
110 /// Boolean tracking whether macro substitution is enabled.
111 unsigned MacrosEnabled : 1;
113 /// Flag tracking whether any errors have been encountered.
114 unsigned HadError : 1;
117 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
118 const MCAsmInfo &MAI);
121 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
123 void AddDirectiveHandler(MCAsmParserExtension *Object,
125 DirectiveHandler Handler) {
126 DirectiveMap[Directive] = std::make_pair(Object, Handler);
130 /// @name MCAsmParser Interface
133 virtual SourceMgr &getSourceManager() { return SrcMgr; }
134 virtual MCAsmLexer &getLexer() { return Lexer; }
135 virtual MCContext &getContext() { return Ctx; }
136 virtual MCStreamer &getStreamer() { return Out; }
138 virtual bool Warning(SMLoc L, const Twine &Meg);
139 virtual bool Error(SMLoc L, const Twine &Msg);
141 const AsmToken &Lex();
143 bool ParseExpression(const MCExpr *&Res);
144 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
145 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
146 virtual bool ParseAbsoluteExpression(int64_t &Res);
151 void CheckForValidSection();
153 bool ParseStatement();
155 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
156 bool expandMacro(SmallString<256> &Buf, StringRef Body,
157 const std::vector<StringRef> &Parameters,
158 const std::vector<std::vector<AsmToken> > &A,
160 void HandleMacroExit();
162 void PrintMacroInstantiations();
163 void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type) const {
164 SrcMgr.PrintMessage(Loc, Msg, Type);
167 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
168 bool EnterIncludeFile(const std::string &Filename);
170 /// \brief Reset the current lexer position to that given by \arg Loc. The
171 /// current token is not set; clients should ensure Lex() is called
173 void JumpToLoc(SMLoc Loc);
175 void EatToEndOfStatement();
177 /// \brief Parse up to the end of statement and a return the contents from the
178 /// current token until the end of the statement; the current token on exit
179 /// will be either the EndOfStatement or EOF.
180 StringRef ParseStringToEndOfStatement();
182 bool ParseAssignment(StringRef Name, bool allow_redef);
184 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
185 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
186 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
187 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
189 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
190 /// and set \arg Res to the identifier contents.
191 bool ParseIdentifier(StringRef &Res);
193 // Directive Parsing.
195 // ".ascii", ".asciiz", ".string"
196 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
197 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
198 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
199 bool ParseDirectiveFill(); // ".fill"
200 bool ParseDirectiveSpace(); // ".space"
201 bool ParseDirectiveZero(); // ".zero"
202 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
203 bool ParseDirectiveOrg(); // ".org"
204 // ".align{,32}", ".p2align{,w,l}"
205 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
207 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
208 /// accepts a single symbol (which should be a label or an external).
209 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
211 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
213 bool ParseDirectiveAbort(); // ".abort"
214 bool ParseDirectiveInclude(); // ".include"
216 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
217 // ".ifdef" or ".ifndef", depending on expect_defined
218 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
219 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
220 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
221 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
223 /// ParseEscapedString - Parse the current token as a string which may include
224 /// escaped characters and return the string contents.
225 bool ParseEscapedString(std::string &Data);
227 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
228 MCSymbolRefExpr::VariantKind Variant);
231 /// \brief Generic implementations of directive handling, etc. which is shared
232 /// (or the default, at least) for all assembler parser.
233 class GenericAsmParser : public MCAsmParserExtension {
234 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
235 void AddDirectiveHandler(StringRef Directive) {
236 getParser().AddDirectiveHandler(this, Directive,
237 HandleDirective<GenericAsmParser, Handler>);
240 GenericAsmParser() {}
242 AsmParser &getParser() {
243 return (AsmParser&) this->MCAsmParserExtension::getParser();
246 virtual void Initialize(MCAsmParser &Parser) {
247 // Call the base implementation.
248 this->MCAsmParserExtension::Initialize(Parser);
250 // Debugging directives.
251 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
252 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
253 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
254 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
257 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
259 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
261 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
263 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
265 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
266 ".cfi_def_cfa_offset");
267 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
268 ".cfi_adjust_cfa_offset");
269 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
270 ".cfi_def_cfa_register");
271 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
273 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
276 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
278 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
280 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
282 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
284 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
287 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
289 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
291 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
292 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
293 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
295 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
296 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
299 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
301 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
302 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
303 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
304 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
305 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
306 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
307 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
308 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
309 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
310 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
311 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
312 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
313 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
314 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
315 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
316 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
317 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
319 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
320 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
321 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
323 bool ParseDirectiveLEB128(StringRef, SMLoc);
330 extern MCAsmParserExtension *createDarwinAsmParser();
331 extern MCAsmParserExtension *createELFAsmParser();
332 extern MCAsmParserExtension *createCOFFAsmParser();
336 enum { DEFAULT_ADDRSPACE = 0 };
338 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
339 MCStreamer &_Out, const MCAsmInfo &_MAI)
340 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
341 GenericParser(new GenericAsmParser), PlatformParser(0),
342 CurBuffer(0), MacrosEnabled(true) {
343 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
345 // Initialize the generic parser.
346 GenericParser->Initialize(*this);
348 // Initialize the platform / file format parser.
350 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
352 if (_MAI.hasMicrosoftFastStdCallMangling()) {
353 PlatformParser = createCOFFAsmParser();
354 PlatformParser->Initialize(*this);
355 } else if (_MAI.hasSubsectionsViaSymbols()) {
356 PlatformParser = createDarwinAsmParser();
357 PlatformParser->Initialize(*this);
359 PlatformParser = createELFAsmParser();
360 PlatformParser->Initialize(*this);
364 AsmParser::~AsmParser() {
365 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
367 // Destroy any macros.
368 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
369 ie = MacroMap.end(); it != ie; ++it)
370 delete it->getValue();
372 delete PlatformParser;
373 delete GenericParser;
376 void AsmParser::PrintMacroInstantiations() {
377 // Print the active macro instantiation stack.
378 for (std::vector<MacroInstantiation*>::const_reverse_iterator
379 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
380 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
384 bool AsmParser::Warning(SMLoc L, const Twine &Msg) {
385 if (FatalAssemblerWarnings)
386 return Error(L, Msg);
387 PrintMessage(L, Msg, "warning");
388 PrintMacroInstantiations();
392 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
394 PrintMessage(L, Msg, "error");
395 PrintMacroInstantiations();
399 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
400 std::string IncludedFile;
401 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
407 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
412 void AsmParser::JumpToLoc(SMLoc Loc) {
413 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
414 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
417 const AsmToken &AsmParser::Lex() {
418 const AsmToken *tok = &Lexer.Lex();
420 if (tok->is(AsmToken::Eof)) {
421 // If this is the end of an included file, pop the parent file off the
423 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
424 if (ParentIncludeLoc != SMLoc()) {
425 JumpToLoc(ParentIncludeLoc);
430 if (tok->is(AsmToken::Error))
431 Error(Lexer.getErrLoc(), Lexer.getErr());
436 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
437 // Create the initial section, if requested.
438 if (!NoInitialTextSection)
445 AsmCond StartingCondState = TheCondState;
447 // While we have input, parse each statement.
448 while (Lexer.isNot(AsmToken::Eof)) {
449 if (!ParseStatement()) continue;
451 // We had an error, validate that one was emitted and recover by skipping to
453 assert(HadError && "Parse statement returned an error, but none emitted!");
454 EatToEndOfStatement();
457 if (TheCondState.TheCond != StartingCondState.TheCond ||
458 TheCondState.Ignore != StartingCondState.Ignore)
459 return TokError("unmatched .ifs or .elses");
461 // Check to see there are no empty DwarfFile slots.
462 const std::vector<MCDwarfFile *> &MCDwarfFiles =
463 getContext().getMCDwarfFiles();
464 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
465 if (!MCDwarfFiles[i])
466 TokError("unassigned file number: " + Twine(i) + " for .file directives");
469 // Finalize the output stream if there are no errors and if the client wants
471 if (!HadError && !NoFinalize)
477 void AsmParser::CheckForValidSection() {
478 if (!getStreamer().getCurrentSection()) {
479 TokError("expected section directive before assembly directive");
480 Out.SwitchSection(Ctx.getMachOSection(
482 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
483 0, SectionKind::getText()));
487 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
488 void AsmParser::EatToEndOfStatement() {
489 while (Lexer.isNot(AsmToken::EndOfStatement) &&
490 Lexer.isNot(AsmToken::Eof))
494 if (Lexer.is(AsmToken::EndOfStatement))
498 StringRef AsmParser::ParseStringToEndOfStatement() {
499 const char *Start = getTok().getLoc().getPointer();
501 while (Lexer.isNot(AsmToken::EndOfStatement) &&
502 Lexer.isNot(AsmToken::Eof))
505 const char *End = getTok().getLoc().getPointer();
506 return StringRef(Start, End - Start);
509 /// ParseParenExpr - Parse a paren expression and return it.
510 /// NOTE: This assumes the leading '(' has already been consumed.
512 /// parenexpr ::= expr)
514 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
515 if (ParseExpression(Res)) return true;
516 if (Lexer.isNot(AsmToken::RParen))
517 return TokError("expected ')' in parentheses expression");
518 EndLoc = Lexer.getLoc();
523 /// ParseBracketExpr - Parse a bracket expression and return it.
524 /// NOTE: This assumes the leading '[' has already been consumed.
526 /// bracketexpr ::= expr]
528 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
529 if (ParseExpression(Res)) return true;
530 if (Lexer.isNot(AsmToken::RBrac))
531 return TokError("expected ']' in brackets expression");
532 EndLoc = Lexer.getLoc();
537 /// ParsePrimaryExpr - Parse a primary expression and return it.
538 /// primaryexpr ::= (parenexpr
539 /// primaryexpr ::= symbol
540 /// primaryexpr ::= number
541 /// primaryexpr ::= '.'
542 /// primaryexpr ::= ~,+,- primaryexpr
543 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
544 switch (Lexer.getKind()) {
546 return TokError("unknown token in expression");
547 // If we have an error assume that we've already handled it.
548 case AsmToken::Error:
550 case AsmToken::Exclaim:
551 Lex(); // Eat the operator.
552 if (ParsePrimaryExpr(Res, EndLoc))
554 Res = MCUnaryExpr::CreateLNot(Res, getContext());
556 case AsmToken::Dollar:
557 case AsmToken::String:
558 case AsmToken::Identifier: {
559 EndLoc = Lexer.getLoc();
561 StringRef Identifier;
562 if (ParseIdentifier(Identifier))
565 // This is a symbol reference.
566 std::pair<StringRef, StringRef> Split = Identifier.split('@');
567 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
569 // Lookup the symbol variant if used.
570 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
571 if (Split.first.size() != Identifier.size()) {
572 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
573 if (Variant == MCSymbolRefExpr::VK_Invalid) {
574 Variant = MCSymbolRefExpr::VK_None;
575 return TokError("invalid variant '" + Split.second + "'");
579 // If this is an absolute variable reference, substitute it now to preserve
580 // semantics in the face of reassignment.
581 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
583 return Error(EndLoc, "unexpected modifier on variable reference");
585 Res = Sym->getVariableValue();
589 // Otherwise create a symbol ref.
590 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
593 case AsmToken::Integer: {
594 SMLoc Loc = getTok().getLoc();
595 int64_t IntVal = getTok().getIntVal();
596 Res = MCConstantExpr::Create(IntVal, getContext());
597 EndLoc = Lexer.getLoc();
599 // Look for 'b' or 'f' following an Integer as a directional label
600 if (Lexer.getKind() == AsmToken::Identifier) {
601 StringRef IDVal = getTok().getString();
602 if (IDVal == "f" || IDVal == "b"){
603 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
604 IDVal == "f" ? 1 : 0);
605 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
607 if(IDVal == "b" && Sym->isUndefined())
608 return Error(Loc, "invalid reference to undefined symbol");
609 EndLoc = Lexer.getLoc();
610 Lex(); // Eat identifier.
615 case AsmToken::Real: {
616 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
617 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
618 Res = MCConstantExpr::Create(IntVal, getContext());
622 case AsmToken::Dot: {
623 // This is a '.' reference, which references the current PC. Emit a
624 // temporary label to the streamer and refer to it.
625 MCSymbol *Sym = Ctx.CreateTempSymbol();
627 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
628 EndLoc = Lexer.getLoc();
629 Lex(); // Eat identifier.
632 case AsmToken::LParen:
633 Lex(); // Eat the '('.
634 return ParseParenExpr(Res, EndLoc);
635 case AsmToken::LBrac:
636 if (!PlatformParser->HasBracketExpressions())
637 return TokError("brackets expression not supported on this target");
638 Lex(); // Eat the '['.
639 return ParseBracketExpr(Res, EndLoc);
640 case AsmToken::Minus:
641 Lex(); // Eat the operator.
642 if (ParsePrimaryExpr(Res, EndLoc))
644 Res = MCUnaryExpr::CreateMinus(Res, getContext());
647 Lex(); // Eat the operator.
648 if (ParsePrimaryExpr(Res, EndLoc))
650 Res = MCUnaryExpr::CreatePlus(Res, getContext());
652 case AsmToken::Tilde:
653 Lex(); // Eat the operator.
654 if (ParsePrimaryExpr(Res, EndLoc))
656 Res = MCUnaryExpr::CreateNot(Res, getContext());
661 bool AsmParser::ParseExpression(const MCExpr *&Res) {
663 return ParseExpression(Res, EndLoc);
667 AsmParser::ApplyModifierToExpr(const MCExpr *E,
668 MCSymbolRefExpr::VariantKind Variant) {
669 // Recurse over the given expression, rebuilding it to apply the given variant
670 // if there is exactly one symbol.
671 switch (E->getKind()) {
673 case MCExpr::Constant:
676 case MCExpr::SymbolRef: {
677 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
679 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
680 TokError("invalid variant on expression '" +
681 getTok().getIdentifier() + "' (already modified)");
685 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
688 case MCExpr::Unary: {
689 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
690 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
693 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
696 case MCExpr::Binary: {
697 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
698 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
699 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
704 if (!LHS) LHS = BE->getLHS();
705 if (!RHS) RHS = BE->getRHS();
707 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
711 assert(0 && "Invalid expression kind!");
715 /// ParseExpression - Parse an expression and return it.
717 /// expr ::= expr +,- expr -> lowest.
718 /// expr ::= expr |,^,&,! expr -> middle.
719 /// expr ::= expr *,/,%,<<,>> expr -> highest.
720 /// expr ::= primaryexpr
722 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
723 // Parse the expression.
725 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
728 // As a special case, we support 'a op b @ modifier' by rewriting the
729 // expression to include the modifier. This is inefficient, but in general we
730 // expect users to use 'a@modifier op b'.
731 if (Lexer.getKind() == AsmToken::At) {
734 if (Lexer.isNot(AsmToken::Identifier))
735 return TokError("unexpected symbol modifier following '@'");
737 MCSymbolRefExpr::VariantKind Variant =
738 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
739 if (Variant == MCSymbolRefExpr::VK_Invalid)
740 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
742 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
744 return TokError("invalid modifier '" + getTok().getIdentifier() +
745 "' (no symbols present)");
753 // Try to constant fold it up front, if possible.
755 if (Res->EvaluateAsAbsolute(Value))
756 Res = MCConstantExpr::Create(Value, getContext());
761 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
763 return ParseParenExpr(Res, EndLoc) ||
764 ParseBinOpRHS(1, Res, EndLoc);
767 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
770 SMLoc StartLoc = Lexer.getLoc();
771 if (ParseExpression(Expr))
774 if (!Expr->EvaluateAsAbsolute(Res))
775 return Error(StartLoc, "expected absolute expression");
780 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
781 MCBinaryExpr::Opcode &Kind) {
784 return 0; // not a binop.
786 // Lowest Precedence: &&, ||, @
787 case AsmToken::AmpAmp:
788 Kind = MCBinaryExpr::LAnd;
790 case AsmToken::PipePipe:
791 Kind = MCBinaryExpr::LOr;
795 // Low Precedence: |, &, ^
797 // FIXME: gas seems to support '!' as an infix operator?
799 Kind = MCBinaryExpr::Or;
801 case AsmToken::Caret:
802 Kind = MCBinaryExpr::Xor;
805 Kind = MCBinaryExpr::And;
808 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
809 case AsmToken::EqualEqual:
810 Kind = MCBinaryExpr::EQ;
812 case AsmToken::ExclaimEqual:
813 case AsmToken::LessGreater:
814 Kind = MCBinaryExpr::NE;
817 Kind = MCBinaryExpr::LT;
819 case AsmToken::LessEqual:
820 Kind = MCBinaryExpr::LTE;
822 case AsmToken::Greater:
823 Kind = MCBinaryExpr::GT;
825 case AsmToken::GreaterEqual:
826 Kind = MCBinaryExpr::GTE;
829 // High Intermediate Precedence: +, -
831 Kind = MCBinaryExpr::Add;
833 case AsmToken::Minus:
834 Kind = MCBinaryExpr::Sub;
837 // Highest Precedence: *, /, %, <<, >>
839 Kind = MCBinaryExpr::Mul;
841 case AsmToken::Slash:
842 Kind = MCBinaryExpr::Div;
844 case AsmToken::Percent:
845 Kind = MCBinaryExpr::Mod;
847 case AsmToken::LessLess:
848 Kind = MCBinaryExpr::Shl;
850 case AsmToken::GreaterGreater:
851 Kind = MCBinaryExpr::Shr;
857 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
858 /// Res contains the LHS of the expression on input.
859 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
862 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
863 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
865 // If the next token is lower precedence than we are allowed to eat, return
866 // successfully with what we ate already.
867 if (TokPrec < Precedence)
872 // Eat the next primary expression.
874 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
876 // If BinOp binds less tightly with RHS than the operator after RHS, let
877 // the pending operator take RHS as its LHS.
878 MCBinaryExpr::Opcode Dummy;
879 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
880 if (TokPrec < NextTokPrec) {
881 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
884 // Merge LHS and RHS according to operator.
885 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
893 /// ::= EndOfStatement
894 /// ::= Label* Directive ...Operands... EndOfStatement
895 /// ::= Label* Identifier OperandList* EndOfStatement
896 bool AsmParser::ParseStatement() {
897 if (Lexer.is(AsmToken::EndOfStatement)) {
903 // Statements always start with an identifier or are a full line comment.
904 AsmToken ID = getTok();
905 SMLoc IDLoc = ID.getLoc();
907 int64_t LocalLabelVal = -1;
908 // A full line comment is a '#' as the first token.
909 if (Lexer.is(AsmToken::Hash)) {
910 EatToEndOfStatement();
914 // Allow an integer followed by a ':' as a directional local label.
915 if (Lexer.is(AsmToken::Integer)) {
916 LocalLabelVal = getTok().getIntVal();
917 if (LocalLabelVal < 0) {
918 if (!TheCondState.Ignore)
919 return TokError("unexpected token at start of statement");
923 IDVal = getTok().getString();
924 Lex(); // Consume the integer token to be used as an identifier token.
925 if (Lexer.getKind() != AsmToken::Colon) {
926 if (!TheCondState.Ignore)
927 return TokError("unexpected token at start of statement");
931 } else if (Lexer.is(AsmToken::Dot)) {
932 // Treat '.' as a valid identifier in this context.
936 } else if (ParseIdentifier(IDVal)) {
937 if (!TheCondState.Ignore)
938 return TokError("unexpected token at start of statement");
943 // Handle conditional assembly here before checking for skipping. We
944 // have to do this so that .endif isn't skipped in a ".if 0" block for
947 return ParseDirectiveIf(IDLoc);
948 if (IDVal == ".ifdef")
949 return ParseDirectiveIfdef(IDLoc, true);
950 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
951 return ParseDirectiveIfdef(IDLoc, false);
952 if (IDVal == ".elseif")
953 return ParseDirectiveElseIf(IDLoc);
954 if (IDVal == ".else")
955 return ParseDirectiveElse(IDLoc);
956 if (IDVal == ".endif")
957 return ParseDirectiveEndIf(IDLoc);
959 // If we are in a ".if 0" block, ignore this statement.
960 if (TheCondState.Ignore) {
961 EatToEndOfStatement();
965 // FIXME: Recurse on local labels?
967 // See what kind of statement we have.
968 switch (Lexer.getKind()) {
969 case AsmToken::Colon: {
970 CheckForValidSection();
972 // identifier ':' -> Label.
975 // Diagnose attempt to use '.' as a label.
977 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
979 // Diagnose attempt to use a variable as a label.
981 // FIXME: Diagnostics. Note the location of the definition as a label.
982 // FIXME: This doesn't diagnose assignment to a symbol which has been
983 // implicitly marked as external.
985 if (LocalLabelVal == -1)
986 Sym = getContext().GetOrCreateSymbol(IDVal);
988 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
989 if (!Sym->isUndefined() || Sym->isVariable())
990 return Error(IDLoc, "invalid symbol redefinition");
995 // Consume any end of statement token, if present, to avoid spurious
996 // AddBlankLine calls().
997 if (Lexer.is(AsmToken::EndOfStatement)) {
999 if (Lexer.is(AsmToken::Eof))
1003 return ParseStatement();
1006 case AsmToken::Equal:
1007 // identifier '=' ... -> assignment statement
1010 return ParseAssignment(IDVal, true);
1012 default: // Normal instruction or directive.
1016 // If macros are enabled, check to see if this is a macro instantiation.
1018 if (const Macro *M = MacroMap.lookup(IDVal))
1019 return HandleMacroEntry(IDVal, IDLoc, M);
1021 // Otherwise, we have a normal instruction or directive.
1022 if (IDVal[0] == '.' && IDVal != ".") {
1023 // Assembler features
1024 if (IDVal == ".set" || IDVal == ".equ")
1025 return ParseDirectiveSet(IDVal, true);
1026 if (IDVal == ".equiv")
1027 return ParseDirectiveSet(IDVal, false);
1031 if (IDVal == ".ascii")
1032 return ParseDirectiveAscii(IDVal, false);
1033 if (IDVal == ".asciz" || IDVal == ".string")
1034 return ParseDirectiveAscii(IDVal, true);
1036 if (IDVal == ".byte")
1037 return ParseDirectiveValue(1);
1038 if (IDVal == ".short")
1039 return ParseDirectiveValue(2);
1040 if (IDVal == ".value")
1041 return ParseDirectiveValue(2);
1042 if (IDVal == ".2byte")
1043 return ParseDirectiveValue(2);
1044 if (IDVal == ".long")
1045 return ParseDirectiveValue(4);
1046 if (IDVal == ".int")
1047 return ParseDirectiveValue(4);
1048 if (IDVal == ".4byte")
1049 return ParseDirectiveValue(4);
1050 if (IDVal == ".quad")
1051 return ParseDirectiveValue(8);
1052 if (IDVal == ".8byte")
1053 return ParseDirectiveValue(8);
1054 if (IDVal == ".single" || IDVal == ".float")
1055 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1056 if (IDVal == ".double")
1057 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1059 if (IDVal == ".align") {
1060 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1061 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1063 if (IDVal == ".align32") {
1064 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1065 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1067 if (IDVal == ".balign")
1068 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1069 if (IDVal == ".balignw")
1070 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1071 if (IDVal == ".balignl")
1072 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1073 if (IDVal == ".p2align")
1074 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1075 if (IDVal == ".p2alignw")
1076 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1077 if (IDVal == ".p2alignl")
1078 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1080 if (IDVal == ".org")
1081 return ParseDirectiveOrg();
1083 if (IDVal == ".fill")
1084 return ParseDirectiveFill();
1085 if (IDVal == ".space" || IDVal == ".skip")
1086 return ParseDirectiveSpace();
1087 if (IDVal == ".zero")
1088 return ParseDirectiveZero();
1090 // Symbol attribute directives
1092 if (IDVal == ".globl" || IDVal == ".global")
1093 return ParseDirectiveSymbolAttribute(MCSA_Global);
1094 // ELF only? Should it be here?
1095 if (IDVal == ".local")
1096 return ParseDirectiveSymbolAttribute(MCSA_Local);
1097 if (IDVal == ".hidden")
1098 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1099 if (IDVal == ".indirect_symbol")
1100 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1101 if (IDVal == ".internal")
1102 return ParseDirectiveSymbolAttribute(MCSA_Internal);
1103 if (IDVal == ".lazy_reference")
1104 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1105 if (IDVal == ".no_dead_strip")
1106 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1107 if (IDVal == ".symbol_resolver")
1108 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1109 if (IDVal == ".private_extern")
1110 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1111 if (IDVal == ".protected")
1112 return ParseDirectiveSymbolAttribute(MCSA_Protected);
1113 if (IDVal == ".reference")
1114 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1115 if (IDVal == ".weak")
1116 return ParseDirectiveSymbolAttribute(MCSA_Weak);
1117 if (IDVal == ".weak_definition")
1118 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1119 if (IDVal == ".weak_reference")
1120 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1121 if (IDVal == ".weak_def_can_be_hidden")
1122 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1124 if (IDVal == ".comm")
1125 return ParseDirectiveComm(/*IsLocal=*/false);
1126 if (IDVal == ".lcomm")
1127 return ParseDirectiveComm(/*IsLocal=*/true);
1129 if (IDVal == ".abort")
1130 return ParseDirectiveAbort();
1131 if (IDVal == ".include")
1132 return ParseDirectiveInclude();
1134 if (IDVal == ".code16" || IDVal == ".code32" || IDVal == ".code64")
1135 return TokError(Twine(IDVal) + " not supported yet");
1137 // Look up the handler in the handler table.
1138 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1139 DirectiveMap.lookup(IDVal);
1141 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1143 // Target hook for parsing target specific directives.
1144 if (!getTargetParser().ParseDirective(ID))
1147 bool retval = Warning(IDLoc, "ignoring directive for now");
1148 EatToEndOfStatement();
1152 CheckForValidSection();
1154 // Canonicalize the opcode to lower case.
1155 SmallString<128> Opcode;
1156 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1157 Opcode.push_back(tolower(IDVal[i]));
1159 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1160 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1163 // Dump the parsed representation, if requested.
1164 if (getShowParsedOperands()) {
1165 SmallString<256> Str;
1166 raw_svector_ostream OS(Str);
1167 OS << "parsed instruction: [";
1168 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1171 ParsedOperands[i]->dump(OS);
1175 PrintMessage(IDLoc, OS.str(), "note");
1178 // If parsing succeeded, match the instruction.
1180 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1183 // Free any parsed operands.
1184 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1185 delete ParsedOperands[i];
1187 // Don't skip the rest of the line, the instruction parser is responsible for
1192 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1193 const std::vector<StringRef> &Parameters,
1194 const std::vector<std::vector<AsmToken> > &A,
1196 raw_svector_ostream OS(Buf);
1197 unsigned NParameters = Parameters.size();
1198 if (NParameters != 0 && NParameters != A.size())
1199 return Error(L, "Wrong number of arguments");
1201 while (!Body.empty()) {
1202 // Scan for the next substitution.
1203 std::size_t End = Body.size(), Pos = 0;
1204 for (; Pos != End; ++Pos) {
1205 // Check for a substitution or escape.
1207 // This macro has no parameters, look for $0, $1, etc.
1208 if (Body[Pos] != '$' || Pos + 1 == End)
1211 char Next = Body[Pos + 1];
1212 if (Next == '$' || Next == 'n' || isdigit(Next))
1215 // This macro has parameters, look for \foo, \bar, etc.
1216 if (Body[Pos] == '\\' && Pos + 1 != End)
1222 OS << Body.slice(0, Pos);
1224 // Check if we reached the end.
1229 switch (Body[Pos+1]) {
1235 // $n => number of arguments
1240 // $[0-9] => argument
1242 // Missing arguments are ignored.
1243 unsigned Index = Body[Pos+1] - '0';
1244 if (Index >= A.size())
1247 // Otherwise substitute with the token values, with spaces eliminated.
1248 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1249 ie = A[Index].end(); it != ie; ++it)
1250 OS << it->getString();
1256 unsigned I = Pos + 1;
1257 while (isalnum(Body[I]) && I + 1 != End)
1260 const char *Begin = Body.data() + Pos +1;
1261 StringRef Argument(Begin, I - (Pos +1));
1263 for (; Index < NParameters; ++Index)
1264 if (Parameters[Index] == Argument)
1267 // FIXME: We should error at the macro definition.
1268 if (Index == NParameters)
1269 return Error(L, "Parameter not found");
1271 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1272 ie = A[Index].end(); it != ie; ++it)
1273 OS << it->getString();
1275 Pos += 1 + Argument.size();
1277 // Update the scan point.
1278 Body = Body.substr(Pos);
1281 // We include the .endmacro in the buffer as our queue to exit the macro
1283 OS << ".endmacro\n";
1287 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1289 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1293 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1295 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1296 // this, although we should protect against infinite loops.
1297 if (ActiveMacros.size() == 20)
1298 return TokError("macros cannot be nested more than 20 levels deep");
1300 // Parse the macro instantiation arguments.
1301 std::vector<std::vector<AsmToken> > MacroArguments;
1302 MacroArguments.push_back(std::vector<AsmToken>());
1303 unsigned ParenLevel = 0;
1305 if (Lexer.is(AsmToken::Eof))
1306 return TokError("unexpected token in macro instantiation");
1307 if (Lexer.is(AsmToken::EndOfStatement))
1310 // If we aren't inside parentheses and this is a comma, start a new token
1312 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1313 MacroArguments.push_back(std::vector<AsmToken>());
1315 // Adjust the current parentheses level.
1316 if (Lexer.is(AsmToken::LParen))
1318 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1321 // Append the token to the current argument list.
1322 MacroArguments.back().push_back(getTok());
1327 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1328 // to hold the macro body with substitutions.
1329 SmallString<256> Buf;
1330 StringRef Body = M->Body;
1332 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1335 MemoryBuffer *Instantiation =
1336 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1338 // Create the macro instantiation object and add to the current macro
1339 // instantiation stack.
1340 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1343 ActiveMacros.push_back(MI);
1345 // Jump to the macro instantiation and prime the lexer.
1346 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1347 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1353 void AsmParser::HandleMacroExit() {
1354 // Jump to the EndOfStatement we should return to, and consume it.
1355 JumpToLoc(ActiveMacros.back()->ExitLoc);
1358 // Pop the instantiation entry.
1359 delete ActiveMacros.back();
1360 ActiveMacros.pop_back();
1363 static void MarkUsed(const MCExpr *Value) {
1364 switch (Value->getKind()) {
1365 case MCExpr::Binary:
1366 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1367 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1369 case MCExpr::Target:
1370 case MCExpr::Constant:
1372 case MCExpr::SymbolRef: {
1373 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1377 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1382 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1383 // FIXME: Use better location, we should use proper tokens.
1384 SMLoc EqualLoc = Lexer.getLoc();
1386 const MCExpr *Value;
1387 if (ParseExpression(Value))
1392 if (Lexer.isNot(AsmToken::EndOfStatement))
1393 return TokError("unexpected token in assignment");
1395 // Error on assignment to '.'.
1397 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1398 "(use '.space' or '.org').)"));
1401 // Eat the end of statement marker.
1404 // Validate that the LHS is allowed to be a variable (either it has not been
1405 // used as a symbol, or it is an absolute symbol).
1406 MCSymbol *Sym = getContext().LookupSymbol(Name);
1408 // Diagnose assignment to a label.
1410 // FIXME: Diagnostics. Note the location of the definition as a label.
1411 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1412 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1413 ; // Allow redefinitions of undefined symbols only used in directives.
1414 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1415 return Error(EqualLoc, "redefinition of '" + Name + "'");
1416 else if (!Sym->isVariable())
1417 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1418 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1419 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1422 // Don't count these checks as uses.
1423 Sym->setUsed(false);
1425 Sym = getContext().GetOrCreateSymbol(Name);
1427 // FIXME: Handle '.'.
1429 // Do the assignment.
1430 Out.EmitAssignment(Sym, Value);
1435 /// ParseIdentifier:
1438 bool AsmParser::ParseIdentifier(StringRef &Res) {
1439 // The assembler has relaxed rules for accepting identifiers, in particular we
1440 // allow things like '.globl $foo', which would normally be separate
1441 // tokens. At this level, we have already lexed so we cannot (currently)
1442 // handle this as a context dependent token, instead we detect adjacent tokens
1443 // and return the combined identifier.
1444 if (Lexer.is(AsmToken::Dollar)) {
1445 SMLoc DollarLoc = getLexer().getLoc();
1447 // Consume the dollar sign, and check for a following identifier.
1449 if (Lexer.isNot(AsmToken::Identifier))
1452 // We have a '$' followed by an identifier, make sure they are adjacent.
1453 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1456 // Construct the joined identifier and consume the token.
1457 Res = StringRef(DollarLoc.getPointer(),
1458 getTok().getIdentifier().size() + 1);
1463 if (Lexer.isNot(AsmToken::Identifier) &&
1464 Lexer.isNot(AsmToken::String))
1467 Res = getTok().getIdentifier();
1469 Lex(); // Consume the identifier token.
1474 /// ParseDirectiveSet:
1475 /// ::= .equ identifier ',' expression
1476 /// ::= .equiv identifier ',' expression
1477 /// ::= .set identifier ',' expression
1478 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1481 if (ParseIdentifier(Name))
1482 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1484 if (getLexer().isNot(AsmToken::Comma))
1485 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1488 return ParseAssignment(Name, allow_redef);
1491 bool AsmParser::ParseEscapedString(std::string &Data) {
1492 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1495 StringRef Str = getTok().getStringContents();
1496 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1497 if (Str[i] != '\\') {
1502 // Recognize escaped characters. Note that this escape semantics currently
1503 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1506 return TokError("unexpected backslash at end of string");
1508 // Recognize octal sequences.
1509 if ((unsigned) (Str[i] - '0') <= 7) {
1510 // Consume up to three octal characters.
1511 unsigned Value = Str[i] - '0';
1513 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1515 Value = Value * 8 + (Str[i] - '0');
1517 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1519 Value = Value * 8 + (Str[i] - '0');
1524 return TokError("invalid octal escape sequence (out of range)");
1526 Data += (unsigned char) Value;
1530 // Otherwise recognize individual escapes.
1533 // Just reject invalid escape sequences for now.
1534 return TokError("invalid escape sequence (unrecognized character)");
1536 case 'b': Data += '\b'; break;
1537 case 'f': Data += '\f'; break;
1538 case 'n': Data += '\n'; break;
1539 case 'r': Data += '\r'; break;
1540 case 't': Data += '\t'; break;
1541 case '"': Data += '"'; break;
1542 case '\\': Data += '\\'; break;
1549 /// ParseDirectiveAscii:
1550 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1551 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1552 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1553 CheckForValidSection();
1556 if (getLexer().isNot(AsmToken::String))
1557 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1560 if (ParseEscapedString(Data))
1563 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1565 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1569 if (getLexer().is(AsmToken::EndOfStatement))
1572 if (getLexer().isNot(AsmToken::Comma))
1573 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1582 /// ParseDirectiveValue
1583 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1584 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1585 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1586 CheckForValidSection();
1589 const MCExpr *Value;
1590 if (ParseExpression(Value))
1593 // Special case constant expressions to match code generator.
1594 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1595 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1597 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1599 if (getLexer().is(AsmToken::EndOfStatement))
1602 // FIXME: Improve diagnostic.
1603 if (getLexer().isNot(AsmToken::Comma))
1604 return TokError("unexpected token in directive");
1613 /// ParseDirectiveRealValue
1614 /// ::= (.single | .double) [ expression (, expression)* ]
1615 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1616 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1617 CheckForValidSection();
1620 // We don't truly support arithmetic on floating point expressions, so we
1621 // have to manually parse unary prefixes.
1623 if (getLexer().is(AsmToken::Minus)) {
1626 } else if (getLexer().is(AsmToken::Plus))
1629 if (getLexer().isNot(AsmToken::Integer) &&
1630 getLexer().isNot(AsmToken::Real) &&
1631 getLexer().isNot(AsmToken::Identifier))
1632 return TokError("unexpected token in directive");
1634 // Convert to an APFloat.
1635 APFloat Value(Semantics);
1636 StringRef IDVal = getTok().getString();
1637 if (getLexer().is(AsmToken::Identifier)) {
1638 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1639 Value = APFloat::getInf(Semantics);
1640 else if (!IDVal.compare_lower("nan"))
1641 Value = APFloat::getNaN(Semantics, false, ~0);
1643 return TokError("invalid floating point literal");
1644 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1645 APFloat::opInvalidOp)
1646 return TokError("invalid floating point literal");
1650 // Consume the numeric token.
1653 // Emit the value as an integer.
1654 APInt AsInt = Value.bitcastToAPInt();
1655 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1656 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1658 if (getLexer().is(AsmToken::EndOfStatement))
1661 if (getLexer().isNot(AsmToken::Comma))
1662 return TokError("unexpected token in directive");
1671 /// ParseDirectiveSpace
1672 /// ::= .space expression [ , expression ]
1673 bool AsmParser::ParseDirectiveSpace() {
1674 CheckForValidSection();
1677 if (ParseAbsoluteExpression(NumBytes))
1680 int64_t FillExpr = 0;
1681 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1682 if (getLexer().isNot(AsmToken::Comma))
1683 return TokError("unexpected token in '.space' directive");
1686 if (ParseAbsoluteExpression(FillExpr))
1689 if (getLexer().isNot(AsmToken::EndOfStatement))
1690 return TokError("unexpected token in '.space' directive");
1696 return TokError("invalid number of bytes in '.space' directive");
1698 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1699 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1704 /// ParseDirectiveZero
1705 /// ::= .zero expression
1706 bool AsmParser::ParseDirectiveZero() {
1707 CheckForValidSection();
1710 if (ParseAbsoluteExpression(NumBytes))
1714 if (getLexer().is(AsmToken::Comma)) {
1716 if (ParseAbsoluteExpression(Val))
1720 if (getLexer().isNot(AsmToken::EndOfStatement))
1721 return TokError("unexpected token in '.zero' directive");
1725 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1730 /// ParseDirectiveFill
1731 /// ::= .fill expression , expression , expression
1732 bool AsmParser::ParseDirectiveFill() {
1733 CheckForValidSection();
1736 if (ParseAbsoluteExpression(NumValues))
1739 if (getLexer().isNot(AsmToken::Comma))
1740 return TokError("unexpected token in '.fill' directive");
1744 if (ParseAbsoluteExpression(FillSize))
1747 if (getLexer().isNot(AsmToken::Comma))
1748 return TokError("unexpected token in '.fill' directive");
1752 if (ParseAbsoluteExpression(FillExpr))
1755 if (getLexer().isNot(AsmToken::EndOfStatement))
1756 return TokError("unexpected token in '.fill' directive");
1760 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1761 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1763 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1764 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1769 /// ParseDirectiveOrg
1770 /// ::= .org expression [ , expression ]
1771 bool AsmParser::ParseDirectiveOrg() {
1772 CheckForValidSection();
1774 const MCExpr *Offset;
1775 if (ParseExpression(Offset))
1778 // Parse optional fill expression.
1779 int64_t FillExpr = 0;
1780 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1781 if (getLexer().isNot(AsmToken::Comma))
1782 return TokError("unexpected token in '.org' directive");
1785 if (ParseAbsoluteExpression(FillExpr))
1788 if (getLexer().isNot(AsmToken::EndOfStatement))
1789 return TokError("unexpected token in '.org' directive");
1794 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1795 // has to be relative to the current section.
1796 getStreamer().EmitValueToOffset(Offset, FillExpr);
1801 /// ParseDirectiveAlign
1802 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1803 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1804 CheckForValidSection();
1806 SMLoc AlignmentLoc = getLexer().getLoc();
1808 if (ParseAbsoluteExpression(Alignment))
1812 bool HasFillExpr = false;
1813 int64_t FillExpr = 0;
1814 int64_t MaxBytesToFill = 0;
1815 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1816 if (getLexer().isNot(AsmToken::Comma))
1817 return TokError("unexpected token in directive");
1820 // The fill expression can be omitted while specifying a maximum number of
1821 // alignment bytes, e.g:
1823 if (getLexer().isNot(AsmToken::Comma)) {
1825 if (ParseAbsoluteExpression(FillExpr))
1829 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1830 if (getLexer().isNot(AsmToken::Comma))
1831 return TokError("unexpected token in directive");
1834 MaxBytesLoc = getLexer().getLoc();
1835 if (ParseAbsoluteExpression(MaxBytesToFill))
1838 if (getLexer().isNot(AsmToken::EndOfStatement))
1839 return TokError("unexpected token in directive");
1848 // Compute alignment in bytes.
1850 // FIXME: Diagnose overflow.
1851 if (Alignment >= 32) {
1852 Error(AlignmentLoc, "invalid alignment value");
1856 Alignment = 1ULL << Alignment;
1859 // Diagnose non-sensical max bytes to align.
1860 if (MaxBytesLoc.isValid()) {
1861 if (MaxBytesToFill < 1) {
1862 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1863 "many bytes, ignoring maximum bytes expression");
1867 if (MaxBytesToFill >= Alignment) {
1868 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1874 // Check whether we should use optimal code alignment for this .align
1876 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1877 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1878 ValueSize == 1 && UseCodeAlign) {
1879 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1881 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1882 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1889 /// ParseDirectiveSymbolAttribute
1890 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1891 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1892 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1896 if (ParseIdentifier(Name))
1897 return TokError("expected identifier in directive");
1899 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1901 getStreamer().EmitSymbolAttribute(Sym, Attr);
1903 if (getLexer().is(AsmToken::EndOfStatement))
1906 if (getLexer().isNot(AsmToken::Comma))
1907 return TokError("unexpected token in directive");
1916 /// ParseDirectiveComm
1917 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1918 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1919 CheckForValidSection();
1921 SMLoc IDLoc = getLexer().getLoc();
1923 if (ParseIdentifier(Name))
1924 return TokError("expected identifier in directive");
1926 // Handle the identifier as the key symbol.
1927 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1929 if (getLexer().isNot(AsmToken::Comma))
1930 return TokError("unexpected token in directive");
1934 SMLoc SizeLoc = getLexer().getLoc();
1935 if (ParseAbsoluteExpression(Size))
1938 int64_t Pow2Alignment = 0;
1939 SMLoc Pow2AlignmentLoc;
1940 if (getLexer().is(AsmToken::Comma)) {
1942 Pow2AlignmentLoc = getLexer().getLoc();
1943 if (ParseAbsoluteExpression(Pow2Alignment))
1946 // If this target takes alignments in bytes (not log) validate and convert.
1947 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1948 if (!isPowerOf2_64(Pow2Alignment))
1949 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1950 Pow2Alignment = Log2_64(Pow2Alignment);
1954 if (getLexer().isNot(AsmToken::EndOfStatement))
1955 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1959 // NOTE: a size of zero for a .comm should create a undefined symbol
1960 // but a size of .lcomm creates a bss symbol of size zero.
1962 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1963 "be less than zero");
1965 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1966 // may internally end up wanting an alignment in bytes.
1967 // FIXME: Diagnose overflow.
1968 if (Pow2Alignment < 0)
1969 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1970 "alignment, can't be less than zero");
1972 if (!Sym->isUndefined())
1973 return Error(IDLoc, "invalid symbol redefinition");
1975 // '.lcomm' is equivalent to '.zerofill'.
1976 // Create the Symbol as a common or local common with Size and Pow2Alignment
1978 getStreamer().EmitZerofill(Ctx.getMachOSection(
1979 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1980 0, SectionKind::getBSS()),
1981 Sym, Size, 1 << Pow2Alignment);
1985 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1989 /// ParseDirectiveAbort
1990 /// ::= .abort [... message ...]
1991 bool AsmParser::ParseDirectiveAbort() {
1992 // FIXME: Use loc from directive.
1993 SMLoc Loc = getLexer().getLoc();
1995 StringRef Str = ParseStringToEndOfStatement();
1996 if (getLexer().isNot(AsmToken::EndOfStatement))
1997 return TokError("unexpected token in '.abort' directive");
2002 Error(Loc, ".abort detected. Assembly stopping.");
2004 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2005 // FIXME: Actually abort assembly here.
2010 /// ParseDirectiveInclude
2011 /// ::= .include "filename"
2012 bool AsmParser::ParseDirectiveInclude() {
2013 if (getLexer().isNot(AsmToken::String))
2014 return TokError("expected string in '.include' directive");
2016 std::string Filename = getTok().getString();
2017 SMLoc IncludeLoc = getLexer().getLoc();
2020 if (getLexer().isNot(AsmToken::EndOfStatement))
2021 return TokError("unexpected token in '.include' directive");
2023 // Strip the quotes.
2024 Filename = Filename.substr(1, Filename.size()-2);
2026 // Attempt to switch the lexer to the included file before consuming the end
2027 // of statement to avoid losing it when we switch.
2028 if (EnterIncludeFile(Filename)) {
2029 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2036 /// ParseDirectiveIf
2037 /// ::= .if expression
2038 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2039 TheCondStack.push_back(TheCondState);
2040 TheCondState.TheCond = AsmCond::IfCond;
2041 if(TheCondState.Ignore) {
2042 EatToEndOfStatement();
2046 if (ParseAbsoluteExpression(ExprValue))
2049 if (getLexer().isNot(AsmToken::EndOfStatement))
2050 return TokError("unexpected token in '.if' directive");
2054 TheCondState.CondMet = ExprValue;
2055 TheCondState.Ignore = !TheCondState.CondMet;
2061 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2063 TheCondStack.push_back(TheCondState);
2064 TheCondState.TheCond = AsmCond::IfCond;
2066 if (TheCondState.Ignore) {
2067 EatToEndOfStatement();
2069 if (ParseIdentifier(Name))
2070 return TokError("expected identifier after '.ifdef'");
2074 MCSymbol *Sym = getContext().LookupSymbol(Name);
2077 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2079 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2080 TheCondState.Ignore = !TheCondState.CondMet;
2086 /// ParseDirectiveElseIf
2087 /// ::= .elseif expression
2088 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2089 if (TheCondState.TheCond != AsmCond::IfCond &&
2090 TheCondState.TheCond != AsmCond::ElseIfCond)
2091 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2093 TheCondState.TheCond = AsmCond::ElseIfCond;
2095 bool LastIgnoreState = false;
2096 if (!TheCondStack.empty())
2097 LastIgnoreState = TheCondStack.back().Ignore;
2098 if (LastIgnoreState || TheCondState.CondMet) {
2099 TheCondState.Ignore = true;
2100 EatToEndOfStatement();
2104 if (ParseAbsoluteExpression(ExprValue))
2107 if (getLexer().isNot(AsmToken::EndOfStatement))
2108 return TokError("unexpected token in '.elseif' directive");
2111 TheCondState.CondMet = ExprValue;
2112 TheCondState.Ignore = !TheCondState.CondMet;
2118 /// ParseDirectiveElse
2120 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2121 if (getLexer().isNot(AsmToken::EndOfStatement))
2122 return TokError("unexpected token in '.else' directive");
2126 if (TheCondState.TheCond != AsmCond::IfCond &&
2127 TheCondState.TheCond != AsmCond::ElseIfCond)
2128 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2130 TheCondState.TheCond = AsmCond::ElseCond;
2131 bool LastIgnoreState = false;
2132 if (!TheCondStack.empty())
2133 LastIgnoreState = TheCondStack.back().Ignore;
2134 if (LastIgnoreState || TheCondState.CondMet)
2135 TheCondState.Ignore = true;
2137 TheCondState.Ignore = false;
2142 /// ParseDirectiveEndIf
2144 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2145 if (getLexer().isNot(AsmToken::EndOfStatement))
2146 return TokError("unexpected token in '.endif' directive");
2150 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2151 TheCondStack.empty())
2152 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2154 if (!TheCondStack.empty()) {
2155 TheCondState = TheCondStack.back();
2156 TheCondStack.pop_back();
2162 /// ParseDirectiveFile
2163 /// ::= .file [number] string
2164 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2165 // FIXME: I'm not sure what this is.
2166 int64_t FileNumber = -1;
2167 SMLoc FileNumberLoc = getLexer().getLoc();
2168 if (getLexer().is(AsmToken::Integer)) {
2169 FileNumber = getTok().getIntVal();
2173 return TokError("file number less than one");
2176 if (getLexer().isNot(AsmToken::String))
2177 return TokError("unexpected token in '.file' directive");
2179 StringRef Filename = getTok().getString();
2180 Filename = Filename.substr(1, Filename.size()-2);
2183 if (getLexer().isNot(AsmToken::EndOfStatement))
2184 return TokError("unexpected token in '.file' directive");
2186 if (FileNumber == -1)
2187 getStreamer().EmitFileDirective(Filename);
2189 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2190 Error(FileNumberLoc, "file number already allocated");
2196 /// ParseDirectiveLine
2197 /// ::= .line [number]
2198 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2199 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2200 if (getLexer().isNot(AsmToken::Integer))
2201 return TokError("unexpected token in '.line' directive");
2203 int64_t LineNumber = getTok().getIntVal();
2207 // FIXME: Do something with the .line.
2210 if (getLexer().isNot(AsmToken::EndOfStatement))
2211 return TokError("unexpected token in '.line' directive");
2217 /// ParseDirectiveLoc
2218 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2219 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2220 /// The first number is a file number, must have been previously assigned with
2221 /// a .file directive, the second number is the line number and optionally the
2222 /// third number is a column position (zero if not specified). The remaining
2223 /// optional items are .loc sub-directives.
2224 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2226 if (getLexer().isNot(AsmToken::Integer))
2227 return TokError("unexpected token in '.loc' directive");
2228 int64_t FileNumber = getTok().getIntVal();
2230 return TokError("file number less than one in '.loc' directive");
2231 if (!getContext().isValidDwarfFileNumber(FileNumber))
2232 return TokError("unassigned file number in '.loc' directive");
2235 int64_t LineNumber = 0;
2236 if (getLexer().is(AsmToken::Integer)) {
2237 LineNumber = getTok().getIntVal();
2239 return TokError("line number less than one in '.loc' directive");
2243 int64_t ColumnPos = 0;
2244 if (getLexer().is(AsmToken::Integer)) {
2245 ColumnPos = getTok().getIntVal();
2247 return TokError("column position less than zero in '.loc' directive");
2251 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2253 int64_t Discriminator = 0;
2254 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2256 if (getLexer().is(AsmToken::EndOfStatement))
2260 SMLoc Loc = getTok().getLoc();
2261 if (getParser().ParseIdentifier(Name))
2262 return TokError("unexpected token in '.loc' directive");
2264 if (Name == "basic_block")
2265 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2266 else if (Name == "prologue_end")
2267 Flags |= DWARF2_FLAG_PROLOGUE_END;
2268 else if (Name == "epilogue_begin")
2269 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2270 else if (Name == "is_stmt") {
2271 SMLoc Loc = getTok().getLoc();
2272 const MCExpr *Value;
2273 if (getParser().ParseExpression(Value))
2275 // The expression must be the constant 0 or 1.
2276 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2277 int Value = MCE->getValue();
2279 Flags &= ~DWARF2_FLAG_IS_STMT;
2280 else if (Value == 1)
2281 Flags |= DWARF2_FLAG_IS_STMT;
2283 return Error(Loc, "is_stmt value not 0 or 1");
2286 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2289 else if (Name == "isa") {
2290 SMLoc Loc = getTok().getLoc();
2291 const MCExpr *Value;
2292 if (getParser().ParseExpression(Value))
2294 // The expression must be a constant greater or equal to 0.
2295 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2296 int Value = MCE->getValue();
2298 return Error(Loc, "isa number less than zero");
2302 return Error(Loc, "isa number not a constant value");
2305 else if (Name == "discriminator") {
2306 if (getParser().ParseAbsoluteExpression(Discriminator))
2310 return Error(Loc, "unknown sub-directive in '.loc' directive");
2313 if (getLexer().is(AsmToken::EndOfStatement))
2318 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2319 Isa, Discriminator, StringRef());
2324 /// ParseDirectiveStabs
2325 /// ::= .stabs string, number, number, number
2326 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2327 SMLoc DirectiveLoc) {
2328 return TokError("unsupported directive '" + Directive + "'");
2331 /// ParseDirectiveCFISections
2332 /// ::= .cfi_sections section [, section]
2333 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2334 SMLoc DirectiveLoc) {
2339 if (getParser().ParseIdentifier(Name))
2340 return TokError("Expected an identifier");
2342 if (Name == ".eh_frame")
2344 else if (Name == ".debug_frame")
2347 if (getLexer().is(AsmToken::Comma)) {
2350 if (getParser().ParseIdentifier(Name))
2351 return TokError("Expected an identifier");
2353 if (Name == ".eh_frame")
2355 else if (Name == ".debug_frame")
2359 getStreamer().EmitCFISections(EH, Debug);
2364 /// ParseDirectiveCFIStartProc
2365 /// ::= .cfi_startproc
2366 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2367 SMLoc DirectiveLoc) {
2368 getStreamer().EmitCFIStartProc();
2372 /// ParseDirectiveCFIEndProc
2373 /// ::= .cfi_endproc
2374 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2375 getStreamer().EmitCFIEndProc();
2379 /// ParseRegisterOrRegisterNumber - parse register name or number.
2380 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2381 SMLoc DirectiveLoc) {
2384 if (getLexer().isNot(AsmToken::Integer)) {
2385 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2388 Register = getContext().getTargetAsmInfo().getDwarfRegNum(RegNo, true);
2390 return getParser().ParseAbsoluteExpression(Register);
2395 /// ParseDirectiveCFIDefCfa
2396 /// ::= .cfi_def_cfa register, offset
2397 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2398 SMLoc DirectiveLoc) {
2399 int64_t Register = 0;
2400 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2403 if (getLexer().isNot(AsmToken::Comma))
2404 return TokError("unexpected token in directive");
2408 if (getParser().ParseAbsoluteExpression(Offset))
2411 getStreamer().EmitCFIDefCfa(Register, Offset);
2415 /// ParseDirectiveCFIDefCfaOffset
2416 /// ::= .cfi_def_cfa_offset offset
2417 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2418 SMLoc DirectiveLoc) {
2420 if (getParser().ParseAbsoluteExpression(Offset))
2423 getStreamer().EmitCFIDefCfaOffset(Offset);
2427 /// ParseDirectiveCFIAdjustCfaOffset
2428 /// ::= .cfi_adjust_cfa_offset adjustment
2429 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2430 SMLoc DirectiveLoc) {
2431 int64_t Adjustment = 0;
2432 if (getParser().ParseAbsoluteExpression(Adjustment))
2435 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2439 /// ParseDirectiveCFIDefCfaRegister
2440 /// ::= .cfi_def_cfa_register register
2441 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2442 SMLoc DirectiveLoc) {
2443 int64_t Register = 0;
2444 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2447 getStreamer().EmitCFIDefCfaRegister(Register);
2451 /// ParseDirectiveCFIOffset
2452 /// ::= .cfi_offset register, offset
2453 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2454 int64_t Register = 0;
2457 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2460 if (getLexer().isNot(AsmToken::Comma))
2461 return TokError("unexpected token in directive");
2464 if (getParser().ParseAbsoluteExpression(Offset))
2467 getStreamer().EmitCFIOffset(Register, Offset);
2471 /// ParseDirectiveCFIRelOffset
2472 /// ::= .cfi_rel_offset register, offset
2473 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2474 SMLoc DirectiveLoc) {
2475 int64_t Register = 0;
2477 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2480 if (getLexer().isNot(AsmToken::Comma))
2481 return TokError("unexpected token in directive");
2485 if (getParser().ParseAbsoluteExpression(Offset))
2488 getStreamer().EmitCFIRelOffset(Register, Offset);
2492 static bool isValidEncoding(int64_t Encoding) {
2493 if (Encoding & ~0xff)
2496 if (Encoding == dwarf::DW_EH_PE_omit)
2499 const unsigned Format = Encoding & 0xf;
2500 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2501 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2502 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2503 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2506 const unsigned Application = Encoding & 0x70;
2507 if (Application != dwarf::DW_EH_PE_absptr &&
2508 Application != dwarf::DW_EH_PE_pcrel)
2514 /// ParseDirectiveCFIPersonalityOrLsda
2515 /// ::= .cfi_personality encoding, [symbol_name]
2516 /// ::= .cfi_lsda encoding, [symbol_name]
2517 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2518 SMLoc DirectiveLoc) {
2519 int64_t Encoding = 0;
2520 if (getParser().ParseAbsoluteExpression(Encoding))
2522 if (Encoding == dwarf::DW_EH_PE_omit)
2525 if (!isValidEncoding(Encoding))
2526 return TokError("unsupported encoding.");
2528 if (getLexer().isNot(AsmToken::Comma))
2529 return TokError("unexpected token in directive");
2533 if (getParser().ParseIdentifier(Name))
2534 return TokError("expected identifier in directive");
2536 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2538 if (IDVal == ".cfi_personality")
2539 getStreamer().EmitCFIPersonality(Sym, Encoding);
2541 assert(IDVal == ".cfi_lsda");
2542 getStreamer().EmitCFILsda(Sym, Encoding);
2547 /// ParseDirectiveCFIRememberState
2548 /// ::= .cfi_remember_state
2549 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2550 SMLoc DirectiveLoc) {
2551 getStreamer().EmitCFIRememberState();
2555 /// ParseDirectiveCFIRestoreState
2556 /// ::= .cfi_remember_state
2557 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2558 SMLoc DirectiveLoc) {
2559 getStreamer().EmitCFIRestoreState();
2563 /// ParseDirectiveCFISameValue
2564 /// ::= .cfi_same_value register
2565 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2566 SMLoc DirectiveLoc) {
2567 int64_t Register = 0;
2569 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2572 getStreamer().EmitCFISameValue(Register);
2577 /// ParseDirectiveMacrosOnOff
2580 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2581 SMLoc DirectiveLoc) {
2582 if (getLexer().isNot(AsmToken::EndOfStatement))
2583 return Error(getLexer().getLoc(),
2584 "unexpected token in '" + Directive + "' directive");
2586 getParser().MacrosEnabled = Directive == ".macros_on";
2591 /// ParseDirectiveMacro
2592 /// ::= .macro name [parameters]
2593 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2594 SMLoc DirectiveLoc) {
2596 if (getParser().ParseIdentifier(Name))
2597 return TokError("expected identifier in directive");
2599 std::vector<StringRef> Parameters;
2600 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2602 StringRef Parameter;
2603 if (getParser().ParseIdentifier(Parameter))
2604 return TokError("expected identifier in directive");
2605 Parameters.push_back(Parameter);
2607 if (getLexer().isNot(AsmToken::Comma))
2613 if (getLexer().isNot(AsmToken::EndOfStatement))
2614 return TokError("unexpected token in '.macro' directive");
2616 // Eat the end of statement.
2619 AsmToken EndToken, StartToken = getTok();
2621 // Lex the macro definition.
2623 // Check whether we have reached the end of the file.
2624 if (getLexer().is(AsmToken::Eof))
2625 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2627 // Otherwise, check whether we have reach the .endmacro.
2628 if (getLexer().is(AsmToken::Identifier) &&
2629 (getTok().getIdentifier() == ".endm" ||
2630 getTok().getIdentifier() == ".endmacro")) {
2631 EndToken = getTok();
2633 if (getLexer().isNot(AsmToken::EndOfStatement))
2634 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2639 // Otherwise, scan til the end of the statement.
2640 getParser().EatToEndOfStatement();
2643 if (getParser().MacroMap.lookup(Name)) {
2644 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2647 const char *BodyStart = StartToken.getLoc().getPointer();
2648 const char *BodyEnd = EndToken.getLoc().getPointer();
2649 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2650 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
2654 /// ParseDirectiveEndMacro
2657 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2658 SMLoc DirectiveLoc) {
2659 if (getLexer().isNot(AsmToken::EndOfStatement))
2660 return TokError("unexpected token in '" + Directive + "' directive");
2662 // If we are inside a macro instantiation, terminate the current
2664 if (!getParser().ActiveMacros.empty()) {
2665 getParser().HandleMacroExit();
2669 // Otherwise, this .endmacro is a stray entry in the file; well formed
2670 // .endmacro directives are handled during the macro definition parsing.
2671 return TokError("unexpected '" + Directive + "' in file, "
2672 "no current macro definition");
2675 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2676 getParser().CheckForValidSection();
2678 const MCExpr *Value;
2680 if (getParser().ParseExpression(Value))
2683 if (getLexer().isNot(AsmToken::EndOfStatement))
2684 return TokError("unexpected token in directive");
2686 if (DirName[1] == 's')
2687 getStreamer().EmitSLEB128Value(Value);
2689 getStreamer().EmitULEB128Value(Value);
2695 /// \brief Create an MCAsmParser instance.
2696 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2697 MCContext &C, MCStreamer &Out,
2698 const MCAsmInfo &MAI) {
2699 return new AsmParser(T, SM, C, Out, MAI);