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/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCParser/AsmCond.h"
24 #include "llvm/MC/MCParser/AsmLexer.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCSectionMachO.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCTargetAsmParser.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/raw_ostream.h"
42 FatalAssemblerWarnings("fatal-assembler-warnings",
43 cl::desc("Consider warnings as error"));
47 /// \brief Helper class for tracking macro definitions.
51 std::vector<StringRef> Parameters;
54 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
55 Name(N), Body(B), Parameters(P) {}
58 /// \brief Helper class for storing information about an active macro
60 struct MacroInstantiation {
61 /// The macro being instantiated.
62 const Macro *TheMacro;
64 /// The macro instantiation with substitutions.
65 MemoryBuffer *Instantiation;
67 /// The location of the instantiation.
68 SMLoc InstantiationLoc;
70 /// The location where parsing should resume upon instantiation completion.
74 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
78 /// \brief The concrete assembly parser instance.
79 class AsmParser : public MCAsmParser {
80 friend class GenericAsmParser;
82 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
83 void operator=(const AsmParser &); // DO NOT IMPLEMENT
90 SourceMgr::DiagHandlerTy SavedDiagHandler;
91 void *SavedDiagContext;
92 MCAsmParserExtension *GenericParser;
93 MCAsmParserExtension *PlatformParser;
95 /// This is the current buffer index we're lexing from as managed by the
100 std::vector<AsmCond> TheCondStack;
102 /// DirectiveMap - This is a table handlers for directives. Each handler is
103 /// invoked after the directive identifier is read and is responsible for
104 /// parsing and validating the rest of the directive. The handler is passed
105 /// in the directive name and the location of the directive keyword.
106 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
108 /// MacroMap - Map of currently defined macros.
109 StringMap<Macro*> MacroMap;
111 /// ActiveMacros - Stack of active macro instantiations.
112 std::vector<MacroInstantiation*> ActiveMacros;
114 /// Boolean tracking whether macro substitution is enabled.
115 unsigned MacrosEnabled : 1;
117 /// Flag tracking whether any errors have been encountered.
118 unsigned HadError : 1;
120 /// The values from the last parsed cpp hash file line comment if any.
121 StringRef CppHashFilename;
122 int64_t CppHashLineNumber;
126 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
127 const MCAsmInfo &MAI);
130 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
132 void AddDirectiveHandler(MCAsmParserExtension *Object,
134 DirectiveHandler Handler) {
135 DirectiveMap[Directive] = std::make_pair(Object, Handler);
139 /// @name MCAsmParser Interface
142 virtual SourceMgr &getSourceManager() { return SrcMgr; }
143 virtual MCAsmLexer &getLexer() { return Lexer; }
144 virtual MCContext &getContext() { return Ctx; }
145 virtual MCStreamer &getStreamer() { return Out; }
147 virtual bool Warning(SMLoc L, const Twine &Msg,
148 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
149 virtual bool Error(SMLoc L, const Twine &Msg,
150 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
152 const AsmToken &Lex();
154 bool ParseExpression(const MCExpr *&Res);
155 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
156 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
157 virtual bool ParseAbsoluteExpression(int64_t &Res);
162 void CheckForValidSection();
164 bool ParseStatement();
165 void EatToEndOfLine();
166 bool ParseCppHashLineFilenameComment(const SMLoc &L);
168 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
169 bool expandMacro(SmallString<256> &Buf, StringRef Body,
170 const std::vector<StringRef> &Parameters,
171 const std::vector<std::vector<AsmToken> > &A,
173 void HandleMacroExit();
175 void PrintMacroInstantiations();
176 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
177 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
178 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
180 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
182 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
183 bool EnterIncludeFile(const std::string &Filename);
185 /// \brief Reset the current lexer position to that given by \arg Loc. The
186 /// current token is not set; clients should ensure Lex() is called
188 void JumpToLoc(SMLoc Loc);
190 void EatToEndOfStatement();
192 /// \brief Parse up to the end of statement and a return the contents from the
193 /// current token until the end of the statement; the current token on exit
194 /// will be either the EndOfStatement or EOF.
195 StringRef ParseStringToEndOfStatement();
197 bool ParseAssignment(StringRef Name, bool allow_redef);
199 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
200 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
201 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
202 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
204 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
205 /// and set \arg Res to the identifier contents.
206 bool ParseIdentifier(StringRef &Res);
208 // Directive Parsing.
210 // ".ascii", ".asciiz", ".string"
211 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
212 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
213 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
214 bool ParseDirectiveFill(); // ".fill"
215 bool ParseDirectiveSpace(); // ".space"
216 bool ParseDirectiveZero(); // ".zero"
217 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
218 bool ParseDirectiveOrg(); // ".org"
219 // ".align{,32}", ".p2align{,w,l}"
220 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
222 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
223 /// accepts a single symbol (which should be a label or an external).
224 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
226 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
228 bool ParseDirectiveAbort(); // ".abort"
229 bool ParseDirectiveInclude(); // ".include"
231 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
232 // ".ifdef" or ".ifndef", depending on expect_defined
233 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
234 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
235 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
236 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
238 /// ParseEscapedString - Parse the current token as a string which may include
239 /// escaped characters and return the string contents.
240 bool ParseEscapedString(std::string &Data);
242 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
243 MCSymbolRefExpr::VariantKind Variant);
246 /// \brief Generic implementations of directive handling, etc. which is shared
247 /// (or the default, at least) for all assembler parser.
248 class GenericAsmParser : public MCAsmParserExtension {
249 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
250 void AddDirectiveHandler(StringRef Directive) {
251 getParser().AddDirectiveHandler(this, Directive,
252 HandleDirective<GenericAsmParser, Handler>);
255 GenericAsmParser() {}
257 AsmParser &getParser() {
258 return (AsmParser&) this->MCAsmParserExtension::getParser();
261 virtual void Initialize(MCAsmParser &Parser) {
262 // Call the base implementation.
263 this->MCAsmParserExtension::Initialize(Parser);
265 // Debugging directives.
266 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
267 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
268 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
269 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
272 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
274 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
276 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
278 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
280 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
281 ".cfi_def_cfa_offset");
282 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
283 ".cfi_adjust_cfa_offset");
284 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
285 ".cfi_def_cfa_register");
286 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
288 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
291 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
293 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
295 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
297 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
299 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
302 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
304 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
306 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
307 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
308 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
310 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
311 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
314 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
316 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
317 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
318 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
319 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
320 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
321 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
322 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
323 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
324 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
325 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
326 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
327 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
328 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
329 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
330 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
331 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
332 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
334 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
335 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
336 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
338 bool ParseDirectiveLEB128(StringRef, SMLoc);
345 extern MCAsmParserExtension *createDarwinAsmParser();
346 extern MCAsmParserExtension *createELFAsmParser();
347 extern MCAsmParserExtension *createCOFFAsmParser();
351 enum { DEFAULT_ADDRSPACE = 0 };
353 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
354 MCStreamer &_Out, const MCAsmInfo &_MAI)
355 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
356 GenericParser(new GenericAsmParser), PlatformParser(0),
357 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0) {
358 // Save the old handler.
359 SavedDiagHandler = SrcMgr.getDiagHandler();
360 SavedDiagContext = SrcMgr.getDiagContext();
361 // Set our own handler which calls the saved handler.
362 SrcMgr.setDiagHandler(DiagHandler, this);
363 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
365 // Initialize the generic parser.
366 GenericParser->Initialize(*this);
368 // Initialize the platform / file format parser.
370 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
372 if (_MAI.hasMicrosoftFastStdCallMangling()) {
373 PlatformParser = createCOFFAsmParser();
374 PlatformParser->Initialize(*this);
375 } else if (_MAI.hasSubsectionsViaSymbols()) {
376 PlatformParser = createDarwinAsmParser();
377 PlatformParser->Initialize(*this);
379 PlatformParser = createELFAsmParser();
380 PlatformParser->Initialize(*this);
384 AsmParser::~AsmParser() {
385 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
387 // Destroy any macros.
388 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
389 ie = MacroMap.end(); it != ie; ++it)
390 delete it->getValue();
392 delete PlatformParser;
393 delete GenericParser;
396 void AsmParser::PrintMacroInstantiations() {
397 // Print the active macro instantiation stack.
398 for (std::vector<MacroInstantiation*>::const_reverse_iterator
399 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
400 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
401 "while in macro instantiation");
404 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
405 if (FatalAssemblerWarnings)
406 return Error(L, Msg, Ranges);
407 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
408 PrintMacroInstantiations();
412 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
414 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
415 PrintMacroInstantiations();
419 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
420 std::string IncludedFile;
421 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
427 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
432 void AsmParser::JumpToLoc(SMLoc Loc) {
433 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
434 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
437 const AsmToken &AsmParser::Lex() {
438 const AsmToken *tok = &Lexer.Lex();
440 if (tok->is(AsmToken::Eof)) {
441 // If this is the end of an included file, pop the parent file off the
443 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
444 if (ParentIncludeLoc != SMLoc()) {
445 JumpToLoc(ParentIncludeLoc);
450 if (tok->is(AsmToken::Error))
451 Error(Lexer.getErrLoc(), Lexer.getErr());
456 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
457 // Create the initial section, if requested.
458 if (!NoInitialTextSection)
465 AsmCond StartingCondState = TheCondState;
467 // If we are generating dwarf for assembly source files save the initial text
468 // section and generate a .file directive.
469 if (getContext().getGenDwarfForAssembly()) {
470 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
471 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
472 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
475 // While we have input, parse each statement.
476 while (Lexer.isNot(AsmToken::Eof)) {
477 if (!ParseStatement()) continue;
479 // We had an error, validate that one was emitted and recover by skipping to
481 assert(HadError && "Parse statement returned an error, but none emitted!");
482 EatToEndOfStatement();
485 if (TheCondState.TheCond != StartingCondState.TheCond ||
486 TheCondState.Ignore != StartingCondState.Ignore)
487 return TokError("unmatched .ifs or .elses");
489 // Check to see there are no empty DwarfFile slots.
490 const std::vector<MCDwarfFile *> &MCDwarfFiles =
491 getContext().getMCDwarfFiles();
492 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
493 if (!MCDwarfFiles[i])
494 TokError("unassigned file number: " + Twine(i) + " for .file directives");
497 // Check to see that all assembler local symbols were actually defined.
498 // Targets that don't do subsections via symbols may not want this, though,
499 // so conservatively exclude them. Only do this if we're finalizing, though,
500 // as otherwise we won't necessarilly have seen everything yet.
501 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
502 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
503 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
506 MCSymbol *Sym = i->getValue();
507 // Variable symbols may not be marked as defined, so check those
508 // explicitly. If we know it's a variable, we have a definition for
509 // the purposes of this check.
510 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
511 // FIXME: We would really like to refer back to where the symbol was
512 // first referenced for a source location. We need to add something
513 // to track that. Currently, we just point to the end of the file.
514 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
515 "assembler local symbol '" + Sym->getName() +
521 // Finalize the output stream if there are no errors and if the client wants
523 if (!HadError && !NoFinalize)
529 void AsmParser::CheckForValidSection() {
530 if (!getStreamer().getCurrentSection()) {
531 TokError("expected section directive before assembly directive");
532 Out.SwitchSection(Ctx.getMachOSection(
534 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
535 0, SectionKind::getText()));
539 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
540 void AsmParser::EatToEndOfStatement() {
541 while (Lexer.isNot(AsmToken::EndOfStatement) &&
542 Lexer.isNot(AsmToken::Eof))
546 if (Lexer.is(AsmToken::EndOfStatement))
550 StringRef AsmParser::ParseStringToEndOfStatement() {
551 const char *Start = getTok().getLoc().getPointer();
553 while (Lexer.isNot(AsmToken::EndOfStatement) &&
554 Lexer.isNot(AsmToken::Eof))
557 const char *End = getTok().getLoc().getPointer();
558 return StringRef(Start, End - Start);
561 /// ParseParenExpr - Parse a paren expression and return it.
562 /// NOTE: This assumes the leading '(' has already been consumed.
564 /// parenexpr ::= expr)
566 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
567 if (ParseExpression(Res)) return true;
568 if (Lexer.isNot(AsmToken::RParen))
569 return TokError("expected ')' in parentheses expression");
570 EndLoc = Lexer.getLoc();
575 /// ParseBracketExpr - Parse a bracket expression and return it.
576 /// NOTE: This assumes the leading '[' has already been consumed.
578 /// bracketexpr ::= expr]
580 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
581 if (ParseExpression(Res)) return true;
582 if (Lexer.isNot(AsmToken::RBrac))
583 return TokError("expected ']' in brackets expression");
584 EndLoc = Lexer.getLoc();
589 /// ParsePrimaryExpr - Parse a primary expression and return it.
590 /// primaryexpr ::= (parenexpr
591 /// primaryexpr ::= symbol
592 /// primaryexpr ::= number
593 /// primaryexpr ::= '.'
594 /// primaryexpr ::= ~,+,- primaryexpr
595 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
596 switch (Lexer.getKind()) {
598 return TokError("unknown token in expression");
599 // If we have an error assume that we've already handled it.
600 case AsmToken::Error:
602 case AsmToken::Exclaim:
603 Lex(); // Eat the operator.
604 if (ParsePrimaryExpr(Res, EndLoc))
606 Res = MCUnaryExpr::CreateLNot(Res, getContext());
608 case AsmToken::Dollar:
609 case AsmToken::String:
610 case AsmToken::Identifier: {
611 EndLoc = Lexer.getLoc();
613 StringRef Identifier;
614 if (ParseIdentifier(Identifier))
617 // This is a symbol reference.
618 std::pair<StringRef, StringRef> Split = Identifier.split('@');
619 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
621 // Lookup the symbol variant if used.
622 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
623 if (Split.first.size() != Identifier.size()) {
624 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
625 if (Variant == MCSymbolRefExpr::VK_Invalid) {
626 Variant = MCSymbolRefExpr::VK_None;
627 return TokError("invalid variant '" + Split.second + "'");
631 // If this is an absolute variable reference, substitute it now to preserve
632 // semantics in the face of reassignment.
633 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
635 return Error(EndLoc, "unexpected modifier on variable reference");
637 Res = Sym->getVariableValue();
641 // Otherwise create a symbol ref.
642 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
645 case AsmToken::Integer: {
646 SMLoc Loc = getTok().getLoc();
647 int64_t IntVal = getTok().getIntVal();
648 Res = MCConstantExpr::Create(IntVal, getContext());
649 EndLoc = Lexer.getLoc();
651 // Look for 'b' or 'f' following an Integer as a directional label
652 if (Lexer.getKind() == AsmToken::Identifier) {
653 StringRef IDVal = getTok().getString();
654 if (IDVal == "f" || IDVal == "b"){
655 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
656 IDVal == "f" ? 1 : 0);
657 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
659 if(IDVal == "b" && Sym->isUndefined())
660 return Error(Loc, "invalid reference to undefined symbol");
661 EndLoc = Lexer.getLoc();
662 Lex(); // Eat identifier.
667 case AsmToken::Real: {
668 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
669 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
670 Res = MCConstantExpr::Create(IntVal, getContext());
674 case AsmToken::Dot: {
675 // This is a '.' reference, which references the current PC. Emit a
676 // temporary label to the streamer and refer to it.
677 MCSymbol *Sym = Ctx.CreateTempSymbol();
679 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
680 EndLoc = Lexer.getLoc();
681 Lex(); // Eat identifier.
684 case AsmToken::LParen:
685 Lex(); // Eat the '('.
686 return ParseParenExpr(Res, EndLoc);
687 case AsmToken::LBrac:
688 if (!PlatformParser->HasBracketExpressions())
689 return TokError("brackets expression not supported on this target");
690 Lex(); // Eat the '['.
691 return ParseBracketExpr(Res, EndLoc);
692 case AsmToken::Minus:
693 Lex(); // Eat the operator.
694 if (ParsePrimaryExpr(Res, EndLoc))
696 Res = MCUnaryExpr::CreateMinus(Res, getContext());
699 Lex(); // Eat the operator.
700 if (ParsePrimaryExpr(Res, EndLoc))
702 Res = MCUnaryExpr::CreatePlus(Res, getContext());
704 case AsmToken::Tilde:
705 Lex(); // Eat the operator.
706 if (ParsePrimaryExpr(Res, EndLoc))
708 Res = MCUnaryExpr::CreateNot(Res, getContext());
713 bool AsmParser::ParseExpression(const MCExpr *&Res) {
715 return ParseExpression(Res, EndLoc);
719 AsmParser::ApplyModifierToExpr(const MCExpr *E,
720 MCSymbolRefExpr::VariantKind Variant) {
721 // Recurse over the given expression, rebuilding it to apply the given variant
722 // if there is exactly one symbol.
723 switch (E->getKind()) {
725 case MCExpr::Constant:
728 case MCExpr::SymbolRef: {
729 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
731 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
732 TokError("invalid variant on expression '" +
733 getTok().getIdentifier() + "' (already modified)");
737 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
740 case MCExpr::Unary: {
741 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
742 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
745 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
748 case MCExpr::Binary: {
749 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
750 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
751 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
756 if (!LHS) LHS = BE->getLHS();
757 if (!RHS) RHS = BE->getRHS();
759 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
763 assert(0 && "Invalid expression kind!");
767 /// ParseExpression - Parse an expression and return it.
769 /// expr ::= expr &&,|| expr -> lowest.
770 /// expr ::= expr |,^,&,! expr
771 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
772 /// expr ::= expr <<,>> expr
773 /// expr ::= expr +,- expr
774 /// expr ::= expr *,/,% expr -> highest.
775 /// expr ::= primaryexpr
777 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
778 // Parse the expression.
780 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
783 // As a special case, we support 'a op b @ modifier' by rewriting the
784 // expression to include the modifier. This is inefficient, but in general we
785 // expect users to use 'a@modifier op b'.
786 if (Lexer.getKind() == AsmToken::At) {
789 if (Lexer.isNot(AsmToken::Identifier))
790 return TokError("unexpected symbol modifier following '@'");
792 MCSymbolRefExpr::VariantKind Variant =
793 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
794 if (Variant == MCSymbolRefExpr::VK_Invalid)
795 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
797 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
799 return TokError("invalid modifier '" + getTok().getIdentifier() +
800 "' (no symbols present)");
808 // Try to constant fold it up front, if possible.
810 if (Res->EvaluateAsAbsolute(Value))
811 Res = MCConstantExpr::Create(Value, getContext());
816 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
818 return ParseParenExpr(Res, EndLoc) ||
819 ParseBinOpRHS(1, Res, EndLoc);
822 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
825 SMLoc StartLoc = Lexer.getLoc();
826 if (ParseExpression(Expr))
829 if (!Expr->EvaluateAsAbsolute(Res))
830 return Error(StartLoc, "expected absolute expression");
835 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
836 MCBinaryExpr::Opcode &Kind) {
839 return 0; // not a binop.
841 // Lowest Precedence: &&, ||
842 case AsmToken::AmpAmp:
843 Kind = MCBinaryExpr::LAnd;
845 case AsmToken::PipePipe:
846 Kind = MCBinaryExpr::LOr;
850 // Low Precedence: |, &, ^
852 // FIXME: gas seems to support '!' as an infix operator?
854 Kind = MCBinaryExpr::Or;
856 case AsmToken::Caret:
857 Kind = MCBinaryExpr::Xor;
860 Kind = MCBinaryExpr::And;
863 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
864 case AsmToken::EqualEqual:
865 Kind = MCBinaryExpr::EQ;
867 case AsmToken::ExclaimEqual:
868 case AsmToken::LessGreater:
869 Kind = MCBinaryExpr::NE;
872 Kind = MCBinaryExpr::LT;
874 case AsmToken::LessEqual:
875 Kind = MCBinaryExpr::LTE;
877 case AsmToken::Greater:
878 Kind = MCBinaryExpr::GT;
880 case AsmToken::GreaterEqual:
881 Kind = MCBinaryExpr::GTE;
884 // Intermediate Precedence: <<, >>
885 case AsmToken::LessLess:
886 Kind = MCBinaryExpr::Shl;
888 case AsmToken::GreaterGreater:
889 Kind = MCBinaryExpr::Shr;
892 // High Intermediate Precedence: +, -
894 Kind = MCBinaryExpr::Add;
896 case AsmToken::Minus:
897 Kind = MCBinaryExpr::Sub;
900 // Highest Precedence: *, /, %
902 Kind = MCBinaryExpr::Mul;
904 case AsmToken::Slash:
905 Kind = MCBinaryExpr::Div;
907 case AsmToken::Percent:
908 Kind = MCBinaryExpr::Mod;
914 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
915 /// Res contains the LHS of the expression on input.
916 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
919 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
920 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
922 // If the next token is lower precedence than we are allowed to eat, return
923 // successfully with what we ate already.
924 if (TokPrec < Precedence)
929 // Eat the next primary expression.
931 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
933 // If BinOp binds less tightly with RHS than the operator after RHS, let
934 // the pending operator take RHS as its LHS.
935 MCBinaryExpr::Opcode Dummy;
936 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
937 if (TokPrec < NextTokPrec) {
938 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
941 // Merge LHS and RHS according to operator.
942 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
950 /// ::= EndOfStatement
951 /// ::= Label* Directive ...Operands... EndOfStatement
952 /// ::= Label* Identifier OperandList* EndOfStatement
953 bool AsmParser::ParseStatement() {
954 if (Lexer.is(AsmToken::EndOfStatement)) {
960 // Statements always start with an identifier or are a full line comment.
961 AsmToken ID = getTok();
962 SMLoc IDLoc = ID.getLoc();
964 int64_t LocalLabelVal = -1;
965 // A full line comment is a '#' as the first token.
966 if (Lexer.is(AsmToken::Hash))
967 return ParseCppHashLineFilenameComment(IDLoc);
969 // Allow an integer followed by a ':' as a directional local label.
970 if (Lexer.is(AsmToken::Integer)) {
971 LocalLabelVal = getTok().getIntVal();
972 if (LocalLabelVal < 0) {
973 if (!TheCondState.Ignore)
974 return TokError("unexpected token at start of statement");
978 IDVal = getTok().getString();
979 Lex(); // Consume the integer token to be used as an identifier token.
980 if (Lexer.getKind() != AsmToken::Colon) {
981 if (!TheCondState.Ignore)
982 return TokError("unexpected token at start of statement");
986 } else if (Lexer.is(AsmToken::Dot)) {
987 // Treat '.' as a valid identifier in this context.
991 } else if (ParseIdentifier(IDVal)) {
992 if (!TheCondState.Ignore)
993 return TokError("unexpected token at start of statement");
998 // Handle conditional assembly here before checking for skipping. We
999 // have to do this so that .endif isn't skipped in a ".if 0" block for
1002 return ParseDirectiveIf(IDLoc);
1003 if (IDVal == ".ifdef")
1004 return ParseDirectiveIfdef(IDLoc, true);
1005 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1006 return ParseDirectiveIfdef(IDLoc, false);
1007 if (IDVal == ".elseif")
1008 return ParseDirectiveElseIf(IDLoc);
1009 if (IDVal == ".else")
1010 return ParseDirectiveElse(IDLoc);
1011 if (IDVal == ".endif")
1012 return ParseDirectiveEndIf(IDLoc);
1014 // If we are in a ".if 0" block, ignore this statement.
1015 if (TheCondState.Ignore) {
1016 EatToEndOfStatement();
1020 // FIXME: Recurse on local labels?
1022 // See what kind of statement we have.
1023 switch (Lexer.getKind()) {
1024 case AsmToken::Colon: {
1025 CheckForValidSection();
1027 // identifier ':' -> Label.
1030 // Diagnose attempt to use '.' as a label.
1032 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1034 // Diagnose attempt to use a variable as a label.
1036 // FIXME: Diagnostics. Note the location of the definition as a label.
1037 // FIXME: This doesn't diagnose assignment to a symbol which has been
1038 // implicitly marked as external.
1040 if (LocalLabelVal == -1)
1041 Sym = getContext().GetOrCreateSymbol(IDVal);
1043 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1044 if (!Sym->isUndefined() || Sym->isVariable())
1045 return Error(IDLoc, "invalid symbol redefinition");
1050 // Consume any end of statement token, if present, to avoid spurious
1051 // AddBlankLine calls().
1052 if (Lexer.is(AsmToken::EndOfStatement)) {
1054 if (Lexer.is(AsmToken::Eof))
1058 return ParseStatement();
1061 case AsmToken::Equal:
1062 // identifier '=' ... -> assignment statement
1065 return ParseAssignment(IDVal, true);
1067 default: // Normal instruction or directive.
1071 // If macros are enabled, check to see if this is a macro instantiation.
1073 if (const Macro *M = MacroMap.lookup(IDVal))
1074 return HandleMacroEntry(IDVal, IDLoc, M);
1076 // Otherwise, we have a normal instruction or directive.
1077 if (IDVal[0] == '.' && IDVal != ".") {
1078 // Assembler features
1079 if (IDVal == ".set" || IDVal == ".equ")
1080 return ParseDirectiveSet(IDVal, true);
1081 if (IDVal == ".equiv")
1082 return ParseDirectiveSet(IDVal, false);
1086 if (IDVal == ".ascii")
1087 return ParseDirectiveAscii(IDVal, false);
1088 if (IDVal == ".asciz" || IDVal == ".string")
1089 return ParseDirectiveAscii(IDVal, true);
1091 if (IDVal == ".byte")
1092 return ParseDirectiveValue(1);
1093 if (IDVal == ".short")
1094 return ParseDirectiveValue(2);
1095 if (IDVal == ".value")
1096 return ParseDirectiveValue(2);
1097 if (IDVal == ".2byte")
1098 return ParseDirectiveValue(2);
1099 if (IDVal == ".long")
1100 return ParseDirectiveValue(4);
1101 if (IDVal == ".int")
1102 return ParseDirectiveValue(4);
1103 if (IDVal == ".4byte")
1104 return ParseDirectiveValue(4);
1105 if (IDVal == ".quad")
1106 return ParseDirectiveValue(8);
1107 if (IDVal == ".8byte")
1108 return ParseDirectiveValue(8);
1109 if (IDVal == ".single" || IDVal == ".float")
1110 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1111 if (IDVal == ".double")
1112 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1114 if (IDVal == ".align") {
1115 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1116 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1118 if (IDVal == ".align32") {
1119 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1120 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1122 if (IDVal == ".balign")
1123 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1124 if (IDVal == ".balignw")
1125 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1126 if (IDVal == ".balignl")
1127 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1128 if (IDVal == ".p2align")
1129 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1130 if (IDVal == ".p2alignw")
1131 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1132 if (IDVal == ".p2alignl")
1133 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1135 if (IDVal == ".org")
1136 return ParseDirectiveOrg();
1138 if (IDVal == ".fill")
1139 return ParseDirectiveFill();
1140 if (IDVal == ".space" || IDVal == ".skip")
1141 return ParseDirectiveSpace();
1142 if (IDVal == ".zero")
1143 return ParseDirectiveZero();
1145 // Symbol attribute directives
1147 if (IDVal == ".globl" || IDVal == ".global")
1148 return ParseDirectiveSymbolAttribute(MCSA_Global);
1149 if (IDVal == ".indirect_symbol")
1150 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1151 if (IDVal == ".lazy_reference")
1152 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1153 if (IDVal == ".no_dead_strip")
1154 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1155 if (IDVal == ".symbol_resolver")
1156 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1157 if (IDVal == ".private_extern")
1158 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1159 if (IDVal == ".reference")
1160 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1161 if (IDVal == ".weak_definition")
1162 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1163 if (IDVal == ".weak_reference")
1164 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1165 if (IDVal == ".weak_def_can_be_hidden")
1166 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1168 if (IDVal == ".comm" || IDVal == ".common")
1169 return ParseDirectiveComm(/*IsLocal=*/false);
1170 if (IDVal == ".lcomm")
1171 return ParseDirectiveComm(/*IsLocal=*/true);
1173 if (IDVal == ".abort")
1174 return ParseDirectiveAbort();
1175 if (IDVal == ".include")
1176 return ParseDirectiveInclude();
1178 if (IDVal == ".code16")
1179 return TokError(Twine(IDVal) + " not supported yet");
1181 // Look up the handler in the handler table.
1182 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1183 DirectiveMap.lookup(IDVal);
1185 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1187 // Target hook for parsing target specific directives.
1188 if (!getTargetParser().ParseDirective(ID))
1191 bool retval = Warning(IDLoc, "ignoring directive for now");
1192 EatToEndOfStatement();
1196 CheckForValidSection();
1198 // Canonicalize the opcode to lower case.
1199 SmallString<128> Opcode;
1200 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1201 Opcode.push_back(tolower(IDVal[i]));
1203 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1204 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1207 // Dump the parsed representation, if requested.
1208 if (getShowParsedOperands()) {
1209 SmallString<256> Str;
1210 raw_svector_ostream OS(Str);
1211 OS << "parsed instruction: [";
1212 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1215 ParsedOperands[i]->print(OS);
1219 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1222 // If we are generating dwarf for assembly source files and the current
1223 // section is the initial text section then generate a .loc directive for
1225 if (!HadError && getContext().getGenDwarfForAssembly() &&
1226 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1227 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1228 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1229 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1230 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1234 // If parsing succeeded, match the instruction.
1236 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1239 // Free any parsed operands.
1240 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1241 delete ParsedOperands[i];
1243 // Don't skip the rest of the line, the instruction parser is responsible for
1248 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1249 /// since they may not be able to be tokenized to get to the end of line token.
1250 void AsmParser::EatToEndOfLine() {
1251 if (!Lexer.is(AsmToken::EndOfStatement))
1252 Lexer.LexUntilEndOfLine();
1257 /// ParseCppHashLineFilenameComment as this:
1258 /// ::= # number "filename"
1259 /// or just as a full line comment if it doesn't have a number and a string.
1260 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1261 Lex(); // Eat the hash token.
1263 if (getLexer().isNot(AsmToken::Integer)) {
1264 // Consume the line since in cases it is not a well-formed line directive,
1265 // as if were simply a full line comment.
1270 int64_t LineNumber = getTok().getIntVal();
1273 if (getLexer().isNot(AsmToken::String)) {
1278 StringRef Filename = getTok().getString();
1279 // Get rid of the enclosing quotes.
1280 Filename = Filename.substr(1, Filename.size()-2);
1282 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1284 CppHashFilename = Filename;
1285 CppHashLineNumber = LineNumber;
1287 // Ignore any trailing characters, they're just comment.
1292 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1293 /// for the Filename and LineNo if any in the diagnostic.
1294 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1295 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1296 raw_ostream &OS = errs();
1298 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1299 const SMLoc &DiagLoc = Diag.getLoc();
1300 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1301 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1303 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1304 // before printing the message.
1305 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1306 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1307 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1308 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1311 // If we have not parsed a cpp hash line filename comment or the source
1312 // manager changed or buffer changed (like in a nested include) then just
1313 // print the normal diagnostic using its Filename and LineNo.
1314 if (!Parser->CppHashLineNumber ||
1315 &DiagSrcMgr != &Parser->SrcMgr ||
1316 DiagBuf != CppHashBuf) {
1317 if (Parser->SavedDiagHandler)
1318 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1324 // Use the CppHashFilename and calculate a line number based on the
1325 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1327 const std::string Filename = Parser->CppHashFilename;
1329 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1330 int CppHashLocLineNo =
1331 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1332 int LineNo = Parser->CppHashLineNumber - 1 +
1333 (DiagLocLineNo - CppHashLocLineNo);
1335 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1336 Filename, LineNo, Diag.getColumnNo(),
1337 Diag.getKind(), Diag.getMessage(),
1338 Diag.getLineContents(), Diag.getRanges());
1340 if (Parser->SavedDiagHandler)
1341 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1343 NewDiag.print(0, OS);
1346 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1347 const std::vector<StringRef> &Parameters,
1348 const std::vector<std::vector<AsmToken> > &A,
1350 raw_svector_ostream OS(Buf);
1351 unsigned NParameters = Parameters.size();
1352 if (NParameters != 0 && NParameters != A.size())
1353 return Error(L, "Wrong number of arguments");
1355 while (!Body.empty()) {
1356 // Scan for the next substitution.
1357 std::size_t End = Body.size(), Pos = 0;
1358 for (; Pos != End; ++Pos) {
1359 // Check for a substitution or escape.
1361 // This macro has no parameters, look for $0, $1, etc.
1362 if (Body[Pos] != '$' || Pos + 1 == End)
1365 char Next = Body[Pos + 1];
1366 if (Next == '$' || Next == 'n' || isdigit(Next))
1369 // This macro has parameters, look for \foo, \bar, etc.
1370 if (Body[Pos] == '\\' && Pos + 1 != End)
1376 OS << Body.slice(0, Pos);
1378 // Check if we reached the end.
1383 switch (Body[Pos+1]) {
1389 // $n => number of arguments
1394 // $[0-9] => argument
1396 // Missing arguments are ignored.
1397 unsigned Index = Body[Pos+1] - '0';
1398 if (Index >= A.size())
1401 // Otherwise substitute with the token values, with spaces eliminated.
1402 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1403 ie = A[Index].end(); it != ie; ++it)
1404 OS << it->getString();
1410 unsigned I = Pos + 1;
1411 while (isalnum(Body[I]) && I + 1 != End)
1414 const char *Begin = Body.data() + Pos +1;
1415 StringRef Argument(Begin, I - (Pos +1));
1417 for (; Index < NParameters; ++Index)
1418 if (Parameters[Index] == Argument)
1421 // FIXME: We should error at the macro definition.
1422 if (Index == NParameters)
1423 return Error(L, "Parameter not found");
1425 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1426 ie = A[Index].end(); it != ie; ++it)
1427 OS << it->getString();
1429 Pos += 1 + Argument.size();
1431 // Update the scan point.
1432 Body = Body.substr(Pos);
1435 // We include the .endmacro in the buffer as our queue to exit the macro
1437 OS << ".endmacro\n";
1441 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1443 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1447 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1449 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1450 // this, although we should protect against infinite loops.
1451 if (ActiveMacros.size() == 20)
1452 return TokError("macros cannot be nested more than 20 levels deep");
1454 // Parse the macro instantiation arguments.
1455 std::vector<std::vector<AsmToken> > MacroArguments;
1456 MacroArguments.push_back(std::vector<AsmToken>());
1457 unsigned ParenLevel = 0;
1459 if (Lexer.is(AsmToken::Eof))
1460 return TokError("unexpected token in macro instantiation");
1461 if (Lexer.is(AsmToken::EndOfStatement))
1464 // If we aren't inside parentheses and this is a comma, start a new token
1466 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1467 MacroArguments.push_back(std::vector<AsmToken>());
1469 // Adjust the current parentheses level.
1470 if (Lexer.is(AsmToken::LParen))
1472 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1475 // Append the token to the current argument list.
1476 MacroArguments.back().push_back(getTok());
1481 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1482 // to hold the macro body with substitutions.
1483 SmallString<256> Buf;
1484 StringRef Body = M->Body;
1486 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1489 MemoryBuffer *Instantiation =
1490 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1492 // Create the macro instantiation object and add to the current macro
1493 // instantiation stack.
1494 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1497 ActiveMacros.push_back(MI);
1499 // Jump to the macro instantiation and prime the lexer.
1500 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1501 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1507 void AsmParser::HandleMacroExit() {
1508 // Jump to the EndOfStatement we should return to, and consume it.
1509 JumpToLoc(ActiveMacros.back()->ExitLoc);
1512 // Pop the instantiation entry.
1513 delete ActiveMacros.back();
1514 ActiveMacros.pop_back();
1517 static void MarkUsed(const MCExpr *Value) {
1518 switch (Value->getKind()) {
1519 case MCExpr::Binary:
1520 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1521 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1523 case MCExpr::Target:
1524 case MCExpr::Constant:
1526 case MCExpr::SymbolRef: {
1527 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1531 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1536 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1537 // FIXME: Use better location, we should use proper tokens.
1538 SMLoc EqualLoc = Lexer.getLoc();
1540 const MCExpr *Value;
1541 if (ParseExpression(Value))
1546 if (Lexer.isNot(AsmToken::EndOfStatement))
1547 return TokError("unexpected token in assignment");
1549 // Error on assignment to '.'.
1551 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1552 "(use '.space' or '.org').)"));
1555 // Eat the end of statement marker.
1558 // Validate that the LHS is allowed to be a variable (either it has not been
1559 // used as a symbol, or it is an absolute symbol).
1560 MCSymbol *Sym = getContext().LookupSymbol(Name);
1562 // Diagnose assignment to a label.
1564 // FIXME: Diagnostics. Note the location of the definition as a label.
1565 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1566 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1567 ; // Allow redefinitions of undefined symbols only used in directives.
1568 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1569 return Error(EqualLoc, "redefinition of '" + Name + "'");
1570 else if (!Sym->isVariable())
1571 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1572 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1573 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1576 // Don't count these checks as uses.
1577 Sym->setUsed(false);
1579 Sym = getContext().GetOrCreateSymbol(Name);
1581 // FIXME: Handle '.'.
1583 // Do the assignment.
1584 Out.EmitAssignment(Sym, Value);
1589 /// ParseIdentifier:
1592 bool AsmParser::ParseIdentifier(StringRef &Res) {
1593 // The assembler has relaxed rules for accepting identifiers, in particular we
1594 // allow things like '.globl $foo', which would normally be separate
1595 // tokens. At this level, we have already lexed so we cannot (currently)
1596 // handle this as a context dependent token, instead we detect adjacent tokens
1597 // and return the combined identifier.
1598 if (Lexer.is(AsmToken::Dollar)) {
1599 SMLoc DollarLoc = getLexer().getLoc();
1601 // Consume the dollar sign, and check for a following identifier.
1603 if (Lexer.isNot(AsmToken::Identifier))
1606 // We have a '$' followed by an identifier, make sure they are adjacent.
1607 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1610 // Construct the joined identifier and consume the token.
1611 Res = StringRef(DollarLoc.getPointer(),
1612 getTok().getIdentifier().size() + 1);
1617 if (Lexer.isNot(AsmToken::Identifier) &&
1618 Lexer.isNot(AsmToken::String))
1621 Res = getTok().getIdentifier();
1623 Lex(); // Consume the identifier token.
1628 /// ParseDirectiveSet:
1629 /// ::= .equ identifier ',' expression
1630 /// ::= .equiv identifier ',' expression
1631 /// ::= .set identifier ',' expression
1632 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1635 if (ParseIdentifier(Name))
1636 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1638 if (getLexer().isNot(AsmToken::Comma))
1639 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1642 return ParseAssignment(Name, allow_redef);
1645 bool AsmParser::ParseEscapedString(std::string &Data) {
1646 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1649 StringRef Str = getTok().getStringContents();
1650 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1651 if (Str[i] != '\\') {
1656 // Recognize escaped characters. Note that this escape semantics currently
1657 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1660 return TokError("unexpected backslash at end of string");
1662 // Recognize octal sequences.
1663 if ((unsigned) (Str[i] - '0') <= 7) {
1664 // Consume up to three octal characters.
1665 unsigned Value = Str[i] - '0';
1667 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1669 Value = Value * 8 + (Str[i] - '0');
1671 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1673 Value = Value * 8 + (Str[i] - '0');
1678 return TokError("invalid octal escape sequence (out of range)");
1680 Data += (unsigned char) Value;
1684 // Otherwise recognize individual escapes.
1687 // Just reject invalid escape sequences for now.
1688 return TokError("invalid escape sequence (unrecognized character)");
1690 case 'b': Data += '\b'; break;
1691 case 'f': Data += '\f'; break;
1692 case 'n': Data += '\n'; break;
1693 case 'r': Data += '\r'; break;
1694 case 't': Data += '\t'; break;
1695 case '"': Data += '"'; break;
1696 case '\\': Data += '\\'; break;
1703 /// ParseDirectiveAscii:
1704 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1705 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1706 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1707 CheckForValidSection();
1710 if (getLexer().isNot(AsmToken::String))
1711 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1714 if (ParseEscapedString(Data))
1717 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1719 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1723 if (getLexer().is(AsmToken::EndOfStatement))
1726 if (getLexer().isNot(AsmToken::Comma))
1727 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1736 /// ParseDirectiveValue
1737 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1738 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1739 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1740 CheckForValidSection();
1743 const MCExpr *Value;
1744 SMLoc ExprLoc = getLexer().getLoc();
1745 if (ParseExpression(Value))
1748 // Special case constant expressions to match code generator.
1749 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1750 assert(Size <= 8 && "Invalid size");
1751 uint64_t IntValue = MCE->getValue();
1752 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1753 return Error(ExprLoc, "literal value out of range for directive");
1754 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1756 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1758 if (getLexer().is(AsmToken::EndOfStatement))
1761 // FIXME: Improve diagnostic.
1762 if (getLexer().isNot(AsmToken::Comma))
1763 return TokError("unexpected token in directive");
1772 /// ParseDirectiveRealValue
1773 /// ::= (.single | .double) [ expression (, expression)* ]
1774 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1775 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1776 CheckForValidSection();
1779 // We don't truly support arithmetic on floating point expressions, so we
1780 // have to manually parse unary prefixes.
1782 if (getLexer().is(AsmToken::Minus)) {
1785 } else if (getLexer().is(AsmToken::Plus))
1788 if (getLexer().isNot(AsmToken::Integer) &&
1789 getLexer().isNot(AsmToken::Real) &&
1790 getLexer().isNot(AsmToken::Identifier))
1791 return TokError("unexpected token in directive");
1793 // Convert to an APFloat.
1794 APFloat Value(Semantics);
1795 StringRef IDVal = getTok().getString();
1796 if (getLexer().is(AsmToken::Identifier)) {
1797 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1798 Value = APFloat::getInf(Semantics);
1799 else if (!IDVal.compare_lower("nan"))
1800 Value = APFloat::getNaN(Semantics, false, ~0);
1802 return TokError("invalid floating point literal");
1803 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1804 APFloat::opInvalidOp)
1805 return TokError("invalid floating point literal");
1809 // Consume the numeric token.
1812 // Emit the value as an integer.
1813 APInt AsInt = Value.bitcastToAPInt();
1814 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1815 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1817 if (getLexer().is(AsmToken::EndOfStatement))
1820 if (getLexer().isNot(AsmToken::Comma))
1821 return TokError("unexpected token in directive");
1830 /// ParseDirectiveSpace
1831 /// ::= .space expression [ , expression ]
1832 bool AsmParser::ParseDirectiveSpace() {
1833 CheckForValidSection();
1836 if (ParseAbsoluteExpression(NumBytes))
1839 int64_t FillExpr = 0;
1840 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1841 if (getLexer().isNot(AsmToken::Comma))
1842 return TokError("unexpected token in '.space' directive");
1845 if (ParseAbsoluteExpression(FillExpr))
1848 if (getLexer().isNot(AsmToken::EndOfStatement))
1849 return TokError("unexpected token in '.space' directive");
1855 return TokError("invalid number of bytes in '.space' directive");
1857 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1858 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1863 /// ParseDirectiveZero
1864 /// ::= .zero expression
1865 bool AsmParser::ParseDirectiveZero() {
1866 CheckForValidSection();
1869 if (ParseAbsoluteExpression(NumBytes))
1873 if (getLexer().is(AsmToken::Comma)) {
1875 if (ParseAbsoluteExpression(Val))
1879 if (getLexer().isNot(AsmToken::EndOfStatement))
1880 return TokError("unexpected token in '.zero' directive");
1884 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1889 /// ParseDirectiveFill
1890 /// ::= .fill expression , expression , expression
1891 bool AsmParser::ParseDirectiveFill() {
1892 CheckForValidSection();
1895 if (ParseAbsoluteExpression(NumValues))
1898 if (getLexer().isNot(AsmToken::Comma))
1899 return TokError("unexpected token in '.fill' directive");
1903 if (ParseAbsoluteExpression(FillSize))
1906 if (getLexer().isNot(AsmToken::Comma))
1907 return TokError("unexpected token in '.fill' directive");
1911 if (ParseAbsoluteExpression(FillExpr))
1914 if (getLexer().isNot(AsmToken::EndOfStatement))
1915 return TokError("unexpected token in '.fill' directive");
1919 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1920 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1922 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1923 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1928 /// ParseDirectiveOrg
1929 /// ::= .org expression [ , expression ]
1930 bool AsmParser::ParseDirectiveOrg() {
1931 CheckForValidSection();
1933 const MCExpr *Offset;
1934 if (ParseExpression(Offset))
1937 // Parse optional fill expression.
1938 int64_t FillExpr = 0;
1939 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1940 if (getLexer().isNot(AsmToken::Comma))
1941 return TokError("unexpected token in '.org' directive");
1944 if (ParseAbsoluteExpression(FillExpr))
1947 if (getLexer().isNot(AsmToken::EndOfStatement))
1948 return TokError("unexpected token in '.org' directive");
1953 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1954 // has to be relative to the current section.
1955 getStreamer().EmitValueToOffset(Offset, FillExpr);
1960 /// ParseDirectiveAlign
1961 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1962 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1963 CheckForValidSection();
1965 SMLoc AlignmentLoc = getLexer().getLoc();
1967 if (ParseAbsoluteExpression(Alignment))
1971 bool HasFillExpr = false;
1972 int64_t FillExpr = 0;
1973 int64_t MaxBytesToFill = 0;
1974 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1975 if (getLexer().isNot(AsmToken::Comma))
1976 return TokError("unexpected token in directive");
1979 // The fill expression can be omitted while specifying a maximum number of
1980 // alignment bytes, e.g:
1982 if (getLexer().isNot(AsmToken::Comma)) {
1984 if (ParseAbsoluteExpression(FillExpr))
1988 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1989 if (getLexer().isNot(AsmToken::Comma))
1990 return TokError("unexpected token in directive");
1993 MaxBytesLoc = getLexer().getLoc();
1994 if (ParseAbsoluteExpression(MaxBytesToFill))
1997 if (getLexer().isNot(AsmToken::EndOfStatement))
1998 return TokError("unexpected token in directive");
2007 // Compute alignment in bytes.
2009 // FIXME: Diagnose overflow.
2010 if (Alignment >= 32) {
2011 Error(AlignmentLoc, "invalid alignment value");
2015 Alignment = 1ULL << Alignment;
2018 // Diagnose non-sensical max bytes to align.
2019 if (MaxBytesLoc.isValid()) {
2020 if (MaxBytesToFill < 1) {
2021 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2022 "many bytes, ignoring maximum bytes expression");
2026 if (MaxBytesToFill >= Alignment) {
2027 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2033 // Check whether we should use optimal code alignment for this .align
2035 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2036 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2037 ValueSize == 1 && UseCodeAlign) {
2038 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2040 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2041 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2048 /// ParseDirectiveSymbolAttribute
2049 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2050 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2051 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2054 SMLoc Loc = getTok().getLoc();
2056 if (ParseIdentifier(Name))
2057 return Error(Loc, "expected identifier in directive");
2059 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2061 // Assembler local symbols don't make any sense here. Complain loudly.
2062 if (Sym->isTemporary())
2063 return Error(Loc, "non-local symbol required in directive");
2065 getStreamer().EmitSymbolAttribute(Sym, Attr);
2067 if (getLexer().is(AsmToken::EndOfStatement))
2070 if (getLexer().isNot(AsmToken::Comma))
2071 return TokError("unexpected token in directive");
2080 /// ParseDirectiveComm
2081 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2082 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2083 CheckForValidSection();
2085 SMLoc IDLoc = getLexer().getLoc();
2087 if (ParseIdentifier(Name))
2088 return TokError("expected identifier in directive");
2090 // Handle the identifier as the key symbol.
2091 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2093 if (getLexer().isNot(AsmToken::Comma))
2094 return TokError("unexpected token in directive");
2098 SMLoc SizeLoc = getLexer().getLoc();
2099 if (ParseAbsoluteExpression(Size))
2102 int64_t Pow2Alignment = 0;
2103 SMLoc Pow2AlignmentLoc;
2104 if (getLexer().is(AsmToken::Comma)) {
2106 Pow2AlignmentLoc = getLexer().getLoc();
2107 if (ParseAbsoluteExpression(Pow2Alignment))
2110 // If this target takes alignments in bytes (not log) validate and convert.
2111 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2112 if (!isPowerOf2_64(Pow2Alignment))
2113 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2114 Pow2Alignment = Log2_64(Pow2Alignment);
2118 if (getLexer().isNot(AsmToken::EndOfStatement))
2119 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2123 // NOTE: a size of zero for a .comm should create a undefined symbol
2124 // but a size of .lcomm creates a bss symbol of size zero.
2126 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2127 "be less than zero");
2129 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2130 // may internally end up wanting an alignment in bytes.
2131 // FIXME: Diagnose overflow.
2132 if (Pow2Alignment < 0)
2133 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2134 "alignment, can't be less than zero");
2136 if (!Sym->isUndefined())
2137 return Error(IDLoc, "invalid symbol redefinition");
2139 // '.lcomm' is equivalent to '.zerofill'.
2140 // Create the Symbol as a common or local common with Size and Pow2Alignment
2142 getStreamer().EmitZerofill(Ctx.getMachOSection(
2143 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2144 0, SectionKind::getBSS()),
2145 Sym, Size, 1 << Pow2Alignment);
2149 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2153 /// ParseDirectiveAbort
2154 /// ::= .abort [... message ...]
2155 bool AsmParser::ParseDirectiveAbort() {
2156 // FIXME: Use loc from directive.
2157 SMLoc Loc = getLexer().getLoc();
2159 StringRef Str = ParseStringToEndOfStatement();
2160 if (getLexer().isNot(AsmToken::EndOfStatement))
2161 return TokError("unexpected token in '.abort' directive");
2166 Error(Loc, ".abort detected. Assembly stopping.");
2168 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2169 // FIXME: Actually abort assembly here.
2174 /// ParseDirectiveInclude
2175 /// ::= .include "filename"
2176 bool AsmParser::ParseDirectiveInclude() {
2177 if (getLexer().isNot(AsmToken::String))
2178 return TokError("expected string in '.include' directive");
2180 std::string Filename = getTok().getString();
2181 SMLoc IncludeLoc = getLexer().getLoc();
2184 if (getLexer().isNot(AsmToken::EndOfStatement))
2185 return TokError("unexpected token in '.include' directive");
2187 // Strip the quotes.
2188 Filename = Filename.substr(1, Filename.size()-2);
2190 // Attempt to switch the lexer to the included file before consuming the end
2191 // of statement to avoid losing it when we switch.
2192 if (EnterIncludeFile(Filename)) {
2193 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2200 /// ParseDirectiveIf
2201 /// ::= .if expression
2202 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2203 TheCondStack.push_back(TheCondState);
2204 TheCondState.TheCond = AsmCond::IfCond;
2205 if(TheCondState.Ignore) {
2206 EatToEndOfStatement();
2210 if (ParseAbsoluteExpression(ExprValue))
2213 if (getLexer().isNot(AsmToken::EndOfStatement))
2214 return TokError("unexpected token in '.if' directive");
2218 TheCondState.CondMet = ExprValue;
2219 TheCondState.Ignore = !TheCondState.CondMet;
2225 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2227 TheCondStack.push_back(TheCondState);
2228 TheCondState.TheCond = AsmCond::IfCond;
2230 if (TheCondState.Ignore) {
2231 EatToEndOfStatement();
2233 if (ParseIdentifier(Name))
2234 return TokError("expected identifier after '.ifdef'");
2238 MCSymbol *Sym = getContext().LookupSymbol(Name);
2241 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2243 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2244 TheCondState.Ignore = !TheCondState.CondMet;
2250 /// ParseDirectiveElseIf
2251 /// ::= .elseif expression
2252 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2253 if (TheCondState.TheCond != AsmCond::IfCond &&
2254 TheCondState.TheCond != AsmCond::ElseIfCond)
2255 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2257 TheCondState.TheCond = AsmCond::ElseIfCond;
2259 bool LastIgnoreState = false;
2260 if (!TheCondStack.empty())
2261 LastIgnoreState = TheCondStack.back().Ignore;
2262 if (LastIgnoreState || TheCondState.CondMet) {
2263 TheCondState.Ignore = true;
2264 EatToEndOfStatement();
2268 if (ParseAbsoluteExpression(ExprValue))
2271 if (getLexer().isNot(AsmToken::EndOfStatement))
2272 return TokError("unexpected token in '.elseif' directive");
2275 TheCondState.CondMet = ExprValue;
2276 TheCondState.Ignore = !TheCondState.CondMet;
2282 /// ParseDirectiveElse
2284 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2285 if (getLexer().isNot(AsmToken::EndOfStatement))
2286 return TokError("unexpected token in '.else' directive");
2290 if (TheCondState.TheCond != AsmCond::IfCond &&
2291 TheCondState.TheCond != AsmCond::ElseIfCond)
2292 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2294 TheCondState.TheCond = AsmCond::ElseCond;
2295 bool LastIgnoreState = false;
2296 if (!TheCondStack.empty())
2297 LastIgnoreState = TheCondStack.back().Ignore;
2298 if (LastIgnoreState || TheCondState.CondMet)
2299 TheCondState.Ignore = true;
2301 TheCondState.Ignore = false;
2306 /// ParseDirectiveEndIf
2308 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2309 if (getLexer().isNot(AsmToken::EndOfStatement))
2310 return TokError("unexpected token in '.endif' directive");
2314 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2315 TheCondStack.empty())
2316 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2318 if (!TheCondStack.empty()) {
2319 TheCondState = TheCondStack.back();
2320 TheCondStack.pop_back();
2326 /// ParseDirectiveFile
2327 /// ::= .file [number] filename
2328 /// ::= .file number directory filename
2329 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2330 // FIXME: I'm not sure what this is.
2331 int64_t FileNumber = -1;
2332 SMLoc FileNumberLoc = getLexer().getLoc();
2333 if (getLexer().is(AsmToken::Integer)) {
2334 FileNumber = getTok().getIntVal();
2338 return TokError("file number less than one");
2341 if (getLexer().isNot(AsmToken::String))
2342 return TokError("unexpected token in '.file' directive");
2344 // Usually the directory and filename together, otherwise just the directory.
2345 StringRef Path = getTok().getString();
2346 Path = Path.substr(1, Path.size()-2);
2349 StringRef Directory;
2351 if (getLexer().is(AsmToken::String)) {
2352 if (FileNumber == -1)
2353 return TokError("explicit path specified, but no file number");
2354 Filename = getTok().getString();
2355 Filename = Filename.substr(1, Filename.size()-2);
2362 if (getLexer().isNot(AsmToken::EndOfStatement))
2363 return TokError("unexpected token in '.file' directive");
2365 if (getContext().getGenDwarfForAssembly() == true)
2366 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2367 "used to generate dwarf debug info for assembly code");
2369 if (FileNumber == -1)
2370 getStreamer().EmitFileDirective(Filename);
2372 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2373 Error(FileNumberLoc, "file number already allocated");
2379 /// ParseDirectiveLine
2380 /// ::= .line [number]
2381 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2382 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2383 if (getLexer().isNot(AsmToken::Integer))
2384 return TokError("unexpected token in '.line' directive");
2386 int64_t LineNumber = getTok().getIntVal();
2390 // FIXME: Do something with the .line.
2393 if (getLexer().isNot(AsmToken::EndOfStatement))
2394 return TokError("unexpected token in '.line' directive");
2400 /// ParseDirectiveLoc
2401 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2402 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2403 /// The first number is a file number, must have been previously assigned with
2404 /// a .file directive, the second number is the line number and optionally the
2405 /// third number is a column position (zero if not specified). The remaining
2406 /// optional items are .loc sub-directives.
2407 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2409 if (getLexer().isNot(AsmToken::Integer))
2410 return TokError("unexpected token in '.loc' directive");
2411 int64_t FileNumber = getTok().getIntVal();
2413 return TokError("file number less than one in '.loc' directive");
2414 if (!getContext().isValidDwarfFileNumber(FileNumber))
2415 return TokError("unassigned file number in '.loc' directive");
2418 int64_t LineNumber = 0;
2419 if (getLexer().is(AsmToken::Integer)) {
2420 LineNumber = getTok().getIntVal();
2422 return TokError("line number less than one in '.loc' directive");
2426 int64_t ColumnPos = 0;
2427 if (getLexer().is(AsmToken::Integer)) {
2428 ColumnPos = getTok().getIntVal();
2430 return TokError("column position less than zero in '.loc' directive");
2434 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2436 int64_t Discriminator = 0;
2437 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2439 if (getLexer().is(AsmToken::EndOfStatement))
2443 SMLoc Loc = getTok().getLoc();
2444 if (getParser().ParseIdentifier(Name))
2445 return TokError("unexpected token in '.loc' directive");
2447 if (Name == "basic_block")
2448 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2449 else if (Name == "prologue_end")
2450 Flags |= DWARF2_FLAG_PROLOGUE_END;
2451 else if (Name == "epilogue_begin")
2452 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2453 else if (Name == "is_stmt") {
2454 SMLoc Loc = getTok().getLoc();
2455 const MCExpr *Value;
2456 if (getParser().ParseExpression(Value))
2458 // The expression must be the constant 0 or 1.
2459 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2460 int Value = MCE->getValue();
2462 Flags &= ~DWARF2_FLAG_IS_STMT;
2463 else if (Value == 1)
2464 Flags |= DWARF2_FLAG_IS_STMT;
2466 return Error(Loc, "is_stmt value not 0 or 1");
2469 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2472 else if (Name == "isa") {
2473 SMLoc Loc = getTok().getLoc();
2474 const MCExpr *Value;
2475 if (getParser().ParseExpression(Value))
2477 // The expression must be a constant greater or equal to 0.
2478 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2479 int Value = MCE->getValue();
2481 return Error(Loc, "isa number less than zero");
2485 return Error(Loc, "isa number not a constant value");
2488 else if (Name == "discriminator") {
2489 if (getParser().ParseAbsoluteExpression(Discriminator))
2493 return Error(Loc, "unknown sub-directive in '.loc' directive");
2496 if (getLexer().is(AsmToken::EndOfStatement))
2501 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2502 Isa, Discriminator, StringRef());
2507 /// ParseDirectiveStabs
2508 /// ::= .stabs string, number, number, number
2509 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2510 SMLoc DirectiveLoc) {
2511 return TokError("unsupported directive '" + Directive + "'");
2514 /// ParseDirectiveCFISections
2515 /// ::= .cfi_sections section [, section]
2516 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2517 SMLoc DirectiveLoc) {
2522 if (getParser().ParseIdentifier(Name))
2523 return TokError("Expected an identifier");
2525 if (Name == ".eh_frame")
2527 else if (Name == ".debug_frame")
2530 if (getLexer().is(AsmToken::Comma)) {
2533 if (getParser().ParseIdentifier(Name))
2534 return TokError("Expected an identifier");
2536 if (Name == ".eh_frame")
2538 else if (Name == ".debug_frame")
2542 getStreamer().EmitCFISections(EH, Debug);
2547 /// ParseDirectiveCFIStartProc
2548 /// ::= .cfi_startproc
2549 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2550 SMLoc DirectiveLoc) {
2551 getStreamer().EmitCFIStartProc();
2555 /// ParseDirectiveCFIEndProc
2556 /// ::= .cfi_endproc
2557 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2558 getStreamer().EmitCFIEndProc();
2562 /// ParseRegisterOrRegisterNumber - parse register name or number.
2563 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2564 SMLoc DirectiveLoc) {
2567 if (getLexer().isNot(AsmToken::Integer)) {
2568 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2571 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2573 return getParser().ParseAbsoluteExpression(Register);
2578 /// ParseDirectiveCFIDefCfa
2579 /// ::= .cfi_def_cfa register, offset
2580 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2581 SMLoc DirectiveLoc) {
2582 int64_t Register = 0;
2583 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2586 if (getLexer().isNot(AsmToken::Comma))
2587 return TokError("unexpected token in directive");
2591 if (getParser().ParseAbsoluteExpression(Offset))
2594 getStreamer().EmitCFIDefCfa(Register, Offset);
2598 /// ParseDirectiveCFIDefCfaOffset
2599 /// ::= .cfi_def_cfa_offset offset
2600 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2601 SMLoc DirectiveLoc) {
2603 if (getParser().ParseAbsoluteExpression(Offset))
2606 getStreamer().EmitCFIDefCfaOffset(Offset);
2610 /// ParseDirectiveCFIAdjustCfaOffset
2611 /// ::= .cfi_adjust_cfa_offset adjustment
2612 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2613 SMLoc DirectiveLoc) {
2614 int64_t Adjustment = 0;
2615 if (getParser().ParseAbsoluteExpression(Adjustment))
2618 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2622 /// ParseDirectiveCFIDefCfaRegister
2623 /// ::= .cfi_def_cfa_register register
2624 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2625 SMLoc DirectiveLoc) {
2626 int64_t Register = 0;
2627 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2630 getStreamer().EmitCFIDefCfaRegister(Register);
2634 /// ParseDirectiveCFIOffset
2635 /// ::= .cfi_offset register, offset
2636 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2637 int64_t Register = 0;
2640 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2643 if (getLexer().isNot(AsmToken::Comma))
2644 return TokError("unexpected token in directive");
2647 if (getParser().ParseAbsoluteExpression(Offset))
2650 getStreamer().EmitCFIOffset(Register, Offset);
2654 /// ParseDirectiveCFIRelOffset
2655 /// ::= .cfi_rel_offset register, offset
2656 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2657 SMLoc DirectiveLoc) {
2658 int64_t Register = 0;
2660 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2663 if (getLexer().isNot(AsmToken::Comma))
2664 return TokError("unexpected token in directive");
2668 if (getParser().ParseAbsoluteExpression(Offset))
2671 getStreamer().EmitCFIRelOffset(Register, Offset);
2675 static bool isValidEncoding(int64_t Encoding) {
2676 if (Encoding & ~0xff)
2679 if (Encoding == dwarf::DW_EH_PE_omit)
2682 const unsigned Format = Encoding & 0xf;
2683 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2684 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2685 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2686 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2689 const unsigned Application = Encoding & 0x70;
2690 if (Application != dwarf::DW_EH_PE_absptr &&
2691 Application != dwarf::DW_EH_PE_pcrel)
2697 /// ParseDirectiveCFIPersonalityOrLsda
2698 /// ::= .cfi_personality encoding, [symbol_name]
2699 /// ::= .cfi_lsda encoding, [symbol_name]
2700 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2701 SMLoc DirectiveLoc) {
2702 int64_t Encoding = 0;
2703 if (getParser().ParseAbsoluteExpression(Encoding))
2705 if (Encoding == dwarf::DW_EH_PE_omit)
2708 if (!isValidEncoding(Encoding))
2709 return TokError("unsupported encoding.");
2711 if (getLexer().isNot(AsmToken::Comma))
2712 return TokError("unexpected token in directive");
2716 if (getParser().ParseIdentifier(Name))
2717 return TokError("expected identifier in directive");
2719 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2721 if (IDVal == ".cfi_personality")
2722 getStreamer().EmitCFIPersonality(Sym, Encoding);
2724 assert(IDVal == ".cfi_lsda");
2725 getStreamer().EmitCFILsda(Sym, Encoding);
2730 /// ParseDirectiveCFIRememberState
2731 /// ::= .cfi_remember_state
2732 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2733 SMLoc DirectiveLoc) {
2734 getStreamer().EmitCFIRememberState();
2738 /// ParseDirectiveCFIRestoreState
2739 /// ::= .cfi_remember_state
2740 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2741 SMLoc DirectiveLoc) {
2742 getStreamer().EmitCFIRestoreState();
2746 /// ParseDirectiveCFISameValue
2747 /// ::= .cfi_same_value register
2748 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2749 SMLoc DirectiveLoc) {
2750 int64_t Register = 0;
2752 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2755 getStreamer().EmitCFISameValue(Register);
2760 /// ParseDirectiveMacrosOnOff
2763 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2764 SMLoc DirectiveLoc) {
2765 if (getLexer().isNot(AsmToken::EndOfStatement))
2766 return Error(getLexer().getLoc(),
2767 "unexpected token in '" + Directive + "' directive");
2769 getParser().MacrosEnabled = Directive == ".macros_on";
2774 /// ParseDirectiveMacro
2775 /// ::= .macro name [parameters]
2776 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2777 SMLoc DirectiveLoc) {
2779 if (getParser().ParseIdentifier(Name))
2780 return TokError("expected identifier in directive");
2782 std::vector<StringRef> Parameters;
2783 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2785 StringRef Parameter;
2786 if (getParser().ParseIdentifier(Parameter))
2787 return TokError("expected identifier in directive");
2788 Parameters.push_back(Parameter);
2790 if (getLexer().isNot(AsmToken::Comma))
2796 if (getLexer().isNot(AsmToken::EndOfStatement))
2797 return TokError("unexpected token in '.macro' directive");
2799 // Eat the end of statement.
2802 AsmToken EndToken, StartToken = getTok();
2804 // Lex the macro definition.
2806 // Check whether we have reached the end of the file.
2807 if (getLexer().is(AsmToken::Eof))
2808 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2810 // Otherwise, check whether we have reach the .endmacro.
2811 if (getLexer().is(AsmToken::Identifier) &&
2812 (getTok().getIdentifier() == ".endm" ||
2813 getTok().getIdentifier() == ".endmacro")) {
2814 EndToken = getTok();
2816 if (getLexer().isNot(AsmToken::EndOfStatement))
2817 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2822 // Otherwise, scan til the end of the statement.
2823 getParser().EatToEndOfStatement();
2826 if (getParser().MacroMap.lookup(Name)) {
2827 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2830 const char *BodyStart = StartToken.getLoc().getPointer();
2831 const char *BodyEnd = EndToken.getLoc().getPointer();
2832 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2833 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
2837 /// ParseDirectiveEndMacro
2840 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2841 SMLoc DirectiveLoc) {
2842 if (getLexer().isNot(AsmToken::EndOfStatement))
2843 return TokError("unexpected token in '" + Directive + "' directive");
2845 // If we are inside a macro instantiation, terminate the current
2847 if (!getParser().ActiveMacros.empty()) {
2848 getParser().HandleMacroExit();
2852 // Otherwise, this .endmacro is a stray entry in the file; well formed
2853 // .endmacro directives are handled during the macro definition parsing.
2854 return TokError("unexpected '" + Directive + "' in file, "
2855 "no current macro definition");
2858 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2859 getParser().CheckForValidSection();
2861 const MCExpr *Value;
2863 if (getParser().ParseExpression(Value))
2866 if (getLexer().isNot(AsmToken::EndOfStatement))
2867 return TokError("unexpected token in directive");
2869 if (DirName[1] == 's')
2870 getStreamer().EmitSLEB128Value(Value);
2872 getStreamer().EmitULEB128Value(Value);
2878 /// \brief Create an MCAsmParser instance.
2879 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
2880 MCContext &C, MCStreamer &Out,
2881 const MCAsmInfo &MAI) {
2882 return new AsmParser(SM, C, Out, MAI);