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/Twine.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCDwarf.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCParser/AsmCond.h"
23 #include "llvm/MC/MCParser/AsmLexer.h"
24 #include "llvm/MC/MCParser/MCAsmParser.h"
25 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
26 #include "llvm/MC/MCRegisterInfo.h"
27 #include "llvm/MC/MCSectionMachO.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/MC/MCTargetAsmParser.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/ErrorHandling.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.
48 typedef std::vector<AsmToken> MacroArgument;
53 std::vector<StringRef> Parameters;
56 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
57 Name(N), Body(B), Parameters(P) {}
60 /// \brief Helper class for storing information about an active macro
62 struct MacroInstantiation {
63 /// The macro being instantiated.
64 const Macro *TheMacro;
66 /// The macro instantiation with substitutions.
67 MemoryBuffer *Instantiation;
69 /// The location of the instantiation.
70 SMLoc InstantiationLoc;
72 /// The location where parsing should resume upon instantiation completion.
76 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
80 /// \brief The concrete assembly parser instance.
81 class AsmParser : public MCAsmParser {
82 friend class GenericAsmParser;
84 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
85 void operator=(const AsmParser &); // DO NOT IMPLEMENT
92 SourceMgr::DiagHandlerTy SavedDiagHandler;
93 void *SavedDiagContext;
94 MCAsmParserExtension *GenericParser;
95 MCAsmParserExtension *PlatformParser;
97 /// This is the current buffer index we're lexing from as managed by the
101 AsmCond TheCondState;
102 std::vector<AsmCond> TheCondStack;
104 /// DirectiveMap - This is a table handlers for directives. Each handler is
105 /// invoked after the directive identifier is read and is responsible for
106 /// parsing and validating the rest of the directive. The handler is passed
107 /// in the directive name and the location of the directive keyword.
108 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
110 /// MacroMap - Map of currently defined macros.
111 StringMap<Macro*> MacroMap;
113 /// ActiveMacros - Stack of active macro instantiations.
114 std::vector<MacroInstantiation*> ActiveMacros;
116 /// Boolean tracking whether macro substitution is enabled.
117 unsigned MacrosEnabled : 1;
119 /// Flag tracking whether any errors have been encountered.
120 unsigned HadError : 1;
122 /// The values from the last parsed cpp hash file line comment if any.
123 StringRef CppHashFilename;
124 int64_t CppHashLineNumber;
127 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
128 unsigned AssemblerDialect;
131 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
132 const MCAsmInfo &MAI);
135 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
137 void AddDirectiveHandler(MCAsmParserExtension *Object,
139 DirectiveHandler Handler) {
140 DirectiveMap[Directive] = std::make_pair(Object, Handler);
144 /// @name MCAsmParser Interface
147 virtual SourceMgr &getSourceManager() { return SrcMgr; }
148 virtual MCAsmLexer &getLexer() { return Lexer; }
149 virtual MCContext &getContext() { return Ctx; }
150 virtual MCStreamer &getStreamer() { return Out; }
151 virtual unsigned getAssemblerDialect() {
152 if (AssemblerDialect == ~0U)
153 return MAI.getAssemblerDialect();
155 return AssemblerDialect;
157 virtual void setAssemblerDialect(unsigned i) {
158 AssemblerDialect = i;
161 virtual bool Warning(SMLoc L, const Twine &Msg,
162 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
163 virtual bool Error(SMLoc L, const Twine &Msg,
164 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
166 const AsmToken &Lex();
168 bool ParseExpression(const MCExpr *&Res);
169 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
170 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
171 virtual bool ParseAbsoluteExpression(int64_t &Res);
176 void CheckForValidSection();
178 bool ParseStatement();
179 void EatToEndOfLine();
180 bool ParseCppHashLineFilenameComment(const SMLoc &L);
182 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
183 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
184 const std::vector<StringRef> &Parameters,
185 const std::vector<MacroArgument> &A,
187 void HandleMacroExit();
189 void PrintMacroInstantiations();
190 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
191 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
192 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
194 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
196 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
197 bool EnterIncludeFile(const std::string &Filename);
198 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
199 /// This returns true on failure.
200 bool ProcessIncbinFile(const std::string &Filename);
202 /// \brief Reset the current lexer position to that given by \arg Loc. The
203 /// current token is not set; clients should ensure Lex() is called
205 void JumpToLoc(SMLoc Loc);
207 void EatToEndOfStatement();
209 bool ParseMacroArgument(MacroArgument &MA);
210 bool ParseMacroArguments(const Macro *M, std::vector<MacroArgument> &A);
212 /// \brief Parse up to the end of statement and a return the contents from the
213 /// current token until the end of the statement; the current token on exit
214 /// will be either the EndOfStatement or EOF.
215 StringRef ParseStringToEndOfStatement();
217 /// \brief Parse until the end of a statement or a comma is encountered,
218 /// return the contents from the current token up to the end or comma.
219 StringRef ParseStringToComma();
221 bool ParseAssignment(StringRef Name, bool allow_redef);
223 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
224 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
225 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
226 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
228 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
229 /// and set \arg Res to the identifier contents.
230 bool ParseIdentifier(StringRef &Res);
232 // Directive Parsing.
234 // ".ascii", ".asciiz", ".string"
235 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
236 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
237 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
238 bool ParseDirectiveFill(); // ".fill"
239 bool ParseDirectiveSpace(); // ".space"
240 bool ParseDirectiveZero(); // ".zero"
241 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
242 bool ParseDirectiveOrg(); // ".org"
243 // ".align{,32}", ".p2align{,w,l}"
244 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
246 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
247 /// accepts a single symbol (which should be a label or an external).
248 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
250 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
252 bool ParseDirectiveAbort(); // ".abort"
253 bool ParseDirectiveInclude(); // ".include"
254 bool ParseDirectiveIncbin(); // ".incbin"
256 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
257 // ".ifb" or ".ifnb", depending on ExpectBlank.
258 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
259 // ".ifc" or ".ifnc", depending on ExpectEqual.
260 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
261 // ".ifdef" or ".ifndef", depending on expect_defined
262 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
263 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
264 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
265 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
267 /// ParseEscapedString - Parse the current token as a string which may include
268 /// escaped characters and return the string contents.
269 bool ParseEscapedString(std::string &Data);
271 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
272 MCSymbolRefExpr::VariantKind Variant);
274 // Macro-like directives
275 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
276 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
277 raw_svector_ostream &OS);
278 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
279 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
280 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
281 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
284 /// \brief Generic implementations of directive handling, etc. which is shared
285 /// (or the default, at least) for all assembler parser.
286 class GenericAsmParser : public MCAsmParserExtension {
287 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
288 void AddDirectiveHandler(StringRef Directive) {
289 getParser().AddDirectiveHandler(this, Directive,
290 HandleDirective<GenericAsmParser, Handler>);
293 GenericAsmParser() {}
295 AsmParser &getParser() {
296 return (AsmParser&) this->MCAsmParserExtension::getParser();
299 virtual void Initialize(MCAsmParser &Parser) {
300 // Call the base implementation.
301 this->MCAsmParserExtension::Initialize(Parser);
303 // Debugging directives.
304 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
305 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
306 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
307 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
310 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
312 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
314 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
316 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
318 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
319 ".cfi_def_cfa_offset");
320 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
321 ".cfi_adjust_cfa_offset");
322 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
323 ".cfi_def_cfa_register");
324 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
326 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
329 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
331 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
333 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
335 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
337 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
339 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
341 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
343 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
346 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
348 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
350 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
351 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
352 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
353 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
355 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
356 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
359 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
361 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
362 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
363 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
364 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
365 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
366 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
367 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
368 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
369 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
370 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
371 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
372 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
373 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
374 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
375 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
376 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
377 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
378 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
379 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
380 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
382 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
383 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
384 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
385 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
387 bool ParseDirectiveLEB128(StringRef, SMLoc);
394 extern MCAsmParserExtension *createDarwinAsmParser();
395 extern MCAsmParserExtension *createELFAsmParser();
396 extern MCAsmParserExtension *createCOFFAsmParser();
400 enum { DEFAULT_ADDRSPACE = 0 };
402 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
403 MCStreamer &_Out, const MCAsmInfo &_MAI)
404 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
405 GenericParser(new GenericAsmParser), PlatformParser(0),
406 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
407 AssemblerDialect(~0U) {
408 // Save the old handler.
409 SavedDiagHandler = SrcMgr.getDiagHandler();
410 SavedDiagContext = SrcMgr.getDiagContext();
411 // Set our own handler which calls the saved handler.
412 SrcMgr.setDiagHandler(DiagHandler, this);
413 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
415 // Initialize the generic parser.
416 GenericParser->Initialize(*this);
418 // Initialize the platform / file format parser.
420 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
422 if (_MAI.hasMicrosoftFastStdCallMangling()) {
423 PlatformParser = createCOFFAsmParser();
424 PlatformParser->Initialize(*this);
425 } else if (_MAI.hasSubsectionsViaSymbols()) {
426 PlatformParser = createDarwinAsmParser();
427 PlatformParser->Initialize(*this);
429 PlatformParser = createELFAsmParser();
430 PlatformParser->Initialize(*this);
434 AsmParser::~AsmParser() {
435 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
437 // Destroy any macros.
438 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
439 ie = MacroMap.end(); it != ie; ++it)
440 delete it->getValue();
442 delete PlatformParser;
443 delete GenericParser;
446 void AsmParser::PrintMacroInstantiations() {
447 // Print the active macro instantiation stack.
448 for (std::vector<MacroInstantiation*>::const_reverse_iterator
449 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
450 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
451 "while in macro instantiation");
454 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
455 if (FatalAssemblerWarnings)
456 return Error(L, Msg, Ranges);
457 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
458 PrintMacroInstantiations();
462 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
464 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
465 PrintMacroInstantiations();
469 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
470 std::string IncludedFile;
471 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
477 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
482 /// Process the specified .incbin file by seaching for it in the include paths
483 /// then just emitting the byte contents of the file to the streamer. This
484 /// returns true on failure.
485 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
486 std::string IncludedFile;
487 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
491 // Pick up the bytes from the file and emit them.
492 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
497 void AsmParser::JumpToLoc(SMLoc Loc) {
498 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
499 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
502 const AsmToken &AsmParser::Lex() {
503 const AsmToken *tok = &Lexer.Lex();
505 if (tok->is(AsmToken::Eof)) {
506 // If this is the end of an included file, pop the parent file off the
508 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
509 if (ParentIncludeLoc != SMLoc()) {
510 JumpToLoc(ParentIncludeLoc);
515 if (tok->is(AsmToken::Error))
516 Error(Lexer.getErrLoc(), Lexer.getErr());
521 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
522 // Create the initial section, if requested.
523 if (!NoInitialTextSection)
530 AsmCond StartingCondState = TheCondState;
532 // If we are generating dwarf for assembly source files save the initial text
533 // section and generate a .file directive.
534 if (getContext().getGenDwarfForAssembly()) {
535 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
536 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
537 getStreamer().EmitLabel(SectionStartSym);
538 getContext().setGenDwarfSectionStartSym(SectionStartSym);
539 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
540 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
543 // While we have input, parse each statement.
544 while (Lexer.isNot(AsmToken::Eof)) {
545 if (!ParseStatement()) continue;
547 // We had an error, validate that one was emitted and recover by skipping to
549 assert(HadError && "Parse statement returned an error, but none emitted!");
550 EatToEndOfStatement();
553 if (TheCondState.TheCond != StartingCondState.TheCond ||
554 TheCondState.Ignore != StartingCondState.Ignore)
555 return TokError("unmatched .ifs or .elses");
557 // Check to see there are no empty DwarfFile slots.
558 const std::vector<MCDwarfFile *> &MCDwarfFiles =
559 getContext().getMCDwarfFiles();
560 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
561 if (!MCDwarfFiles[i])
562 TokError("unassigned file number: " + Twine(i) + " for .file directives");
565 // Check to see that all assembler local symbols were actually defined.
566 // Targets that don't do subsections via symbols may not want this, though,
567 // so conservatively exclude them. Only do this if we're finalizing, though,
568 // as otherwise we won't necessarilly have seen everything yet.
569 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
570 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
571 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
574 MCSymbol *Sym = i->getValue();
575 // Variable symbols may not be marked as defined, so check those
576 // explicitly. If we know it's a variable, we have a definition for
577 // the purposes of this check.
578 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
579 // FIXME: We would really like to refer back to where the symbol was
580 // first referenced for a source location. We need to add something
581 // to track that. Currently, we just point to the end of the file.
582 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
583 "assembler local symbol '" + Sym->getName() +
589 // Finalize the output stream if there are no errors and if the client wants
591 if (!HadError && !NoFinalize)
597 void AsmParser::CheckForValidSection() {
598 if (!getStreamer().getCurrentSection()) {
599 TokError("expected section directive before assembly directive");
600 Out.SwitchSection(Ctx.getMachOSection(
602 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
603 0, SectionKind::getText()));
607 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
608 void AsmParser::EatToEndOfStatement() {
609 while (Lexer.isNot(AsmToken::EndOfStatement) &&
610 Lexer.isNot(AsmToken::Eof))
614 if (Lexer.is(AsmToken::EndOfStatement))
618 StringRef AsmParser::ParseStringToEndOfStatement() {
619 const char *Start = getTok().getLoc().getPointer();
621 while (Lexer.isNot(AsmToken::EndOfStatement) &&
622 Lexer.isNot(AsmToken::Eof))
625 const char *End = getTok().getLoc().getPointer();
626 return StringRef(Start, End - Start);
629 StringRef AsmParser::ParseStringToComma() {
630 const char *Start = getTok().getLoc().getPointer();
632 while (Lexer.isNot(AsmToken::EndOfStatement) &&
633 Lexer.isNot(AsmToken::Comma) &&
634 Lexer.isNot(AsmToken::Eof))
637 const char *End = getTok().getLoc().getPointer();
638 return StringRef(Start, End - Start);
641 /// ParseParenExpr - Parse a paren expression and return it.
642 /// NOTE: This assumes the leading '(' has already been consumed.
644 /// parenexpr ::= expr)
646 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
647 if (ParseExpression(Res)) return true;
648 if (Lexer.isNot(AsmToken::RParen))
649 return TokError("expected ')' in parentheses expression");
650 EndLoc = Lexer.getLoc();
655 /// ParseBracketExpr - Parse a bracket expression and return it.
656 /// NOTE: This assumes the leading '[' has already been consumed.
658 /// bracketexpr ::= expr]
660 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
661 if (ParseExpression(Res)) return true;
662 if (Lexer.isNot(AsmToken::RBrac))
663 return TokError("expected ']' in brackets expression");
664 EndLoc = Lexer.getLoc();
669 /// ParsePrimaryExpr - Parse a primary expression and return it.
670 /// primaryexpr ::= (parenexpr
671 /// primaryexpr ::= symbol
672 /// primaryexpr ::= number
673 /// primaryexpr ::= '.'
674 /// primaryexpr ::= ~,+,- primaryexpr
675 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
676 switch (Lexer.getKind()) {
678 return TokError("unknown token in expression");
679 // If we have an error assume that we've already handled it.
680 case AsmToken::Error:
682 case AsmToken::Exclaim:
683 Lex(); // Eat the operator.
684 if (ParsePrimaryExpr(Res, EndLoc))
686 Res = MCUnaryExpr::CreateLNot(Res, getContext());
688 case AsmToken::Dollar:
689 case AsmToken::String:
690 case AsmToken::Identifier: {
691 EndLoc = Lexer.getLoc();
693 StringRef Identifier;
694 if (ParseIdentifier(Identifier))
697 // This is a symbol reference.
698 std::pair<StringRef, StringRef> Split = Identifier.split('@');
699 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
701 // Lookup the symbol variant if used.
702 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
703 if (Split.first.size() != Identifier.size()) {
704 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
705 if (Variant == MCSymbolRefExpr::VK_Invalid) {
706 Variant = MCSymbolRefExpr::VK_None;
707 return TokError("invalid variant '" + Split.second + "'");
711 // If this is an absolute variable reference, substitute it now to preserve
712 // semantics in the face of reassignment.
713 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
715 return Error(EndLoc, "unexpected modifier on variable reference");
717 Res = Sym->getVariableValue();
721 // Otherwise create a symbol ref.
722 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
725 case AsmToken::Integer: {
726 SMLoc Loc = getTok().getLoc();
727 int64_t IntVal = getTok().getIntVal();
728 Res = MCConstantExpr::Create(IntVal, getContext());
729 EndLoc = Lexer.getLoc();
731 // Look for 'b' or 'f' following an Integer as a directional label
732 if (Lexer.getKind() == AsmToken::Identifier) {
733 StringRef IDVal = getTok().getString();
734 if (IDVal == "f" || IDVal == "b"){
735 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
736 IDVal == "f" ? 1 : 0);
737 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
739 if (IDVal == "b" && Sym->isUndefined())
740 return Error(Loc, "invalid reference to undefined symbol");
741 EndLoc = Lexer.getLoc();
742 Lex(); // Eat identifier.
747 case AsmToken::Real: {
748 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
749 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
750 Res = MCConstantExpr::Create(IntVal, getContext());
754 case AsmToken::Dot: {
755 // This is a '.' reference, which references the current PC. Emit a
756 // temporary label to the streamer and refer to it.
757 MCSymbol *Sym = Ctx.CreateTempSymbol();
759 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
760 EndLoc = Lexer.getLoc();
761 Lex(); // Eat identifier.
764 case AsmToken::LParen:
765 Lex(); // Eat the '('.
766 return ParseParenExpr(Res, EndLoc);
767 case AsmToken::LBrac:
768 if (!PlatformParser->HasBracketExpressions())
769 return TokError("brackets expression not supported on this target");
770 Lex(); // Eat the '['.
771 return ParseBracketExpr(Res, EndLoc);
772 case AsmToken::Minus:
773 Lex(); // Eat the operator.
774 if (ParsePrimaryExpr(Res, EndLoc))
776 Res = MCUnaryExpr::CreateMinus(Res, getContext());
779 Lex(); // Eat the operator.
780 if (ParsePrimaryExpr(Res, EndLoc))
782 Res = MCUnaryExpr::CreatePlus(Res, getContext());
784 case AsmToken::Tilde:
785 Lex(); // Eat the operator.
786 if (ParsePrimaryExpr(Res, EndLoc))
788 Res = MCUnaryExpr::CreateNot(Res, getContext());
793 bool AsmParser::ParseExpression(const MCExpr *&Res) {
795 return ParseExpression(Res, EndLoc);
799 AsmParser::ApplyModifierToExpr(const MCExpr *E,
800 MCSymbolRefExpr::VariantKind Variant) {
801 // Recurse over the given expression, rebuilding it to apply the given variant
802 // if there is exactly one symbol.
803 switch (E->getKind()) {
805 case MCExpr::Constant:
808 case MCExpr::SymbolRef: {
809 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
811 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
812 TokError("invalid variant on expression '" +
813 getTok().getIdentifier() + "' (already modified)");
817 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
820 case MCExpr::Unary: {
821 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
822 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
825 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
828 case MCExpr::Binary: {
829 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
830 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
831 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
836 if (!LHS) LHS = BE->getLHS();
837 if (!RHS) RHS = BE->getRHS();
839 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
843 llvm_unreachable("Invalid expression kind!");
846 /// ParseExpression - Parse an expression and return it.
848 /// expr ::= expr &&,|| expr -> lowest.
849 /// expr ::= expr |,^,&,! expr
850 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
851 /// expr ::= expr <<,>> expr
852 /// expr ::= expr +,- expr
853 /// expr ::= expr *,/,% expr -> highest.
854 /// expr ::= primaryexpr
856 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
857 // Parse the expression.
859 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
862 // As a special case, we support 'a op b @ modifier' by rewriting the
863 // expression to include the modifier. This is inefficient, but in general we
864 // expect users to use 'a@modifier op b'.
865 if (Lexer.getKind() == AsmToken::At) {
868 if (Lexer.isNot(AsmToken::Identifier))
869 return TokError("unexpected symbol modifier following '@'");
871 MCSymbolRefExpr::VariantKind Variant =
872 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
873 if (Variant == MCSymbolRefExpr::VK_Invalid)
874 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
876 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
878 return TokError("invalid modifier '" + getTok().getIdentifier() +
879 "' (no symbols present)");
886 // Try to constant fold it up front, if possible.
888 if (Res->EvaluateAsAbsolute(Value))
889 Res = MCConstantExpr::Create(Value, getContext());
894 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
896 return ParseParenExpr(Res, EndLoc) ||
897 ParseBinOpRHS(1, Res, EndLoc);
900 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
903 SMLoc StartLoc = Lexer.getLoc();
904 if (ParseExpression(Expr))
907 if (!Expr->EvaluateAsAbsolute(Res))
908 return Error(StartLoc, "expected absolute expression");
913 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
914 MCBinaryExpr::Opcode &Kind) {
917 return 0; // not a binop.
919 // Lowest Precedence: &&, ||
920 case AsmToken::AmpAmp:
921 Kind = MCBinaryExpr::LAnd;
923 case AsmToken::PipePipe:
924 Kind = MCBinaryExpr::LOr;
928 // Low Precedence: |, &, ^
930 // FIXME: gas seems to support '!' as an infix operator?
932 Kind = MCBinaryExpr::Or;
934 case AsmToken::Caret:
935 Kind = MCBinaryExpr::Xor;
938 Kind = MCBinaryExpr::And;
941 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
942 case AsmToken::EqualEqual:
943 Kind = MCBinaryExpr::EQ;
945 case AsmToken::ExclaimEqual:
946 case AsmToken::LessGreater:
947 Kind = MCBinaryExpr::NE;
950 Kind = MCBinaryExpr::LT;
952 case AsmToken::LessEqual:
953 Kind = MCBinaryExpr::LTE;
955 case AsmToken::Greater:
956 Kind = MCBinaryExpr::GT;
958 case AsmToken::GreaterEqual:
959 Kind = MCBinaryExpr::GTE;
962 // Intermediate Precedence: <<, >>
963 case AsmToken::LessLess:
964 Kind = MCBinaryExpr::Shl;
966 case AsmToken::GreaterGreater:
967 Kind = MCBinaryExpr::Shr;
970 // High Intermediate Precedence: +, -
972 Kind = MCBinaryExpr::Add;
974 case AsmToken::Minus:
975 Kind = MCBinaryExpr::Sub;
978 // Highest Precedence: *, /, %
980 Kind = MCBinaryExpr::Mul;
982 case AsmToken::Slash:
983 Kind = MCBinaryExpr::Div;
985 case AsmToken::Percent:
986 Kind = MCBinaryExpr::Mod;
992 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
993 /// Res contains the LHS of the expression on input.
994 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
997 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
998 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1000 // If the next token is lower precedence than we are allowed to eat, return
1001 // successfully with what we ate already.
1002 if (TokPrec < Precedence)
1007 // Eat the next primary expression.
1009 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1011 // If BinOp binds less tightly with RHS than the operator after RHS, let
1012 // the pending operator take RHS as its LHS.
1013 MCBinaryExpr::Opcode Dummy;
1014 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1015 if (TokPrec < NextTokPrec) {
1016 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1019 // Merge LHS and RHS according to operator.
1020 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1028 /// ::= EndOfStatement
1029 /// ::= Label* Directive ...Operands... EndOfStatement
1030 /// ::= Label* Identifier OperandList* EndOfStatement
1031 bool AsmParser::ParseStatement() {
1032 if (Lexer.is(AsmToken::EndOfStatement)) {
1038 // Statements always start with an identifier or are a full line comment.
1039 AsmToken ID = getTok();
1040 SMLoc IDLoc = ID.getLoc();
1042 int64_t LocalLabelVal = -1;
1043 // A full line comment is a '#' as the first token.
1044 if (Lexer.is(AsmToken::Hash))
1045 return ParseCppHashLineFilenameComment(IDLoc);
1047 // Allow an integer followed by a ':' as a directional local label.
1048 if (Lexer.is(AsmToken::Integer)) {
1049 LocalLabelVal = getTok().getIntVal();
1050 if (LocalLabelVal < 0) {
1051 if (!TheCondState.Ignore)
1052 return TokError("unexpected token at start of statement");
1056 IDVal = getTok().getString();
1057 Lex(); // Consume the integer token to be used as an identifier token.
1058 if (Lexer.getKind() != AsmToken::Colon) {
1059 if (!TheCondState.Ignore)
1060 return TokError("unexpected token at start of statement");
1064 } else if (Lexer.is(AsmToken::Dot)) {
1065 // Treat '.' as a valid identifier in this context.
1069 } else if (ParseIdentifier(IDVal)) {
1070 if (!TheCondState.Ignore)
1071 return TokError("unexpected token at start of statement");
1076 // Handle conditional assembly here before checking for skipping. We
1077 // have to do this so that .endif isn't skipped in a ".if 0" block for
1080 return ParseDirectiveIf(IDLoc);
1081 if (IDVal == ".ifb")
1082 return ParseDirectiveIfb(IDLoc, true);
1083 if (IDVal == ".ifnb")
1084 return ParseDirectiveIfb(IDLoc, false);
1085 if (IDVal == ".ifc")
1086 return ParseDirectiveIfc(IDLoc, true);
1087 if (IDVal == ".ifnc")
1088 return ParseDirectiveIfc(IDLoc, false);
1089 if (IDVal == ".ifdef")
1090 return ParseDirectiveIfdef(IDLoc, true);
1091 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1092 return ParseDirectiveIfdef(IDLoc, false);
1093 if (IDVal == ".elseif")
1094 return ParseDirectiveElseIf(IDLoc);
1095 if (IDVal == ".else")
1096 return ParseDirectiveElse(IDLoc);
1097 if (IDVal == ".endif")
1098 return ParseDirectiveEndIf(IDLoc);
1100 // If we are in a ".if 0" block, ignore this statement.
1101 if (TheCondState.Ignore) {
1102 EatToEndOfStatement();
1106 // FIXME: Recurse on local labels?
1108 // See what kind of statement we have.
1109 switch (Lexer.getKind()) {
1110 case AsmToken::Colon: {
1111 CheckForValidSection();
1113 // identifier ':' -> Label.
1116 // Diagnose attempt to use '.' as a label.
1118 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1120 // Diagnose attempt to use a variable as a label.
1122 // FIXME: Diagnostics. Note the location of the definition as a label.
1123 // FIXME: This doesn't diagnose assignment to a symbol which has been
1124 // implicitly marked as external.
1126 if (LocalLabelVal == -1)
1127 Sym = getContext().GetOrCreateSymbol(IDVal);
1129 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1130 if (!Sym->isUndefined() || Sym->isVariable())
1131 return Error(IDLoc, "invalid symbol redefinition");
1136 // If we are generating dwarf for assembly source files then gather the
1137 // info to make a dwarf label entry for this label if needed.
1138 if (getContext().getGenDwarfForAssembly())
1139 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1142 // Consume any end of statement token, if present, to avoid spurious
1143 // AddBlankLine calls().
1144 if (Lexer.is(AsmToken::EndOfStatement)) {
1146 if (Lexer.is(AsmToken::Eof))
1150 return ParseStatement();
1153 case AsmToken::Equal:
1154 // identifier '=' ... -> assignment statement
1157 return ParseAssignment(IDVal, true);
1159 default: // Normal instruction or directive.
1163 // If macros are enabled, check to see if this is a macro instantiation.
1165 if (const Macro *M = MacroMap.lookup(IDVal))
1166 return HandleMacroEntry(IDVal, IDLoc, M);
1168 // Otherwise, we have a normal instruction or directive.
1169 if (IDVal[0] == '.' && IDVal != ".") {
1171 // Target hook for parsing target specific directives.
1172 if (!getTargetParser().ParseDirective(ID))
1175 // Assembler features
1176 if (IDVal == ".set" || IDVal == ".equ")
1177 return ParseDirectiveSet(IDVal, true);
1178 if (IDVal == ".equiv")
1179 return ParseDirectiveSet(IDVal, false);
1183 if (IDVal == ".ascii")
1184 return ParseDirectiveAscii(IDVal, false);
1185 if (IDVal == ".asciz" || IDVal == ".string")
1186 return ParseDirectiveAscii(IDVal, true);
1188 if (IDVal == ".byte")
1189 return ParseDirectiveValue(1);
1190 if (IDVal == ".short")
1191 return ParseDirectiveValue(2);
1192 if (IDVal == ".value")
1193 return ParseDirectiveValue(2);
1194 if (IDVal == ".2byte")
1195 return ParseDirectiveValue(2);
1196 if (IDVal == ".long")
1197 return ParseDirectiveValue(4);
1198 if (IDVal == ".int")
1199 return ParseDirectiveValue(4);
1200 if (IDVal == ".4byte")
1201 return ParseDirectiveValue(4);
1202 if (IDVal == ".quad")
1203 return ParseDirectiveValue(8);
1204 if (IDVal == ".8byte")
1205 return ParseDirectiveValue(8);
1206 if (IDVal == ".single" || IDVal == ".float")
1207 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1208 if (IDVal == ".double")
1209 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1211 if (IDVal == ".align") {
1212 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1213 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1215 if (IDVal == ".align32") {
1216 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1217 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1219 if (IDVal == ".balign")
1220 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1221 if (IDVal == ".balignw")
1222 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1223 if (IDVal == ".balignl")
1224 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1225 if (IDVal == ".p2align")
1226 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1227 if (IDVal == ".p2alignw")
1228 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1229 if (IDVal == ".p2alignl")
1230 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1232 if (IDVal == ".org")
1233 return ParseDirectiveOrg();
1235 if (IDVal == ".fill")
1236 return ParseDirectiveFill();
1237 if (IDVal == ".space" || IDVal == ".skip")
1238 return ParseDirectiveSpace();
1239 if (IDVal == ".zero")
1240 return ParseDirectiveZero();
1242 // Symbol attribute directives
1244 if (IDVal == ".extern") {
1245 EatToEndOfStatement(); // .extern is the default, ignore it.
1248 if (IDVal == ".globl" || IDVal == ".global")
1249 return ParseDirectiveSymbolAttribute(MCSA_Global);
1250 if (IDVal == ".indirect_symbol")
1251 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1252 if (IDVal == ".lazy_reference")
1253 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1254 if (IDVal == ".no_dead_strip")
1255 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1256 if (IDVal == ".symbol_resolver")
1257 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1258 if (IDVal == ".private_extern")
1259 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1260 if (IDVal == ".reference")
1261 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1262 if (IDVal == ".weak_definition")
1263 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1264 if (IDVal == ".weak_reference")
1265 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1266 if (IDVal == ".weak_def_can_be_hidden")
1267 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1269 if (IDVal == ".comm" || IDVal == ".common")
1270 return ParseDirectiveComm(/*IsLocal=*/false);
1271 if (IDVal == ".lcomm")
1272 return ParseDirectiveComm(/*IsLocal=*/true);
1274 if (IDVal == ".abort")
1275 return ParseDirectiveAbort();
1276 if (IDVal == ".include")
1277 return ParseDirectiveInclude();
1278 if (IDVal == ".incbin")
1279 return ParseDirectiveIncbin();
1281 if (IDVal == ".code16" || IDVal == ".code16gcc")
1282 return TokError(Twine(IDVal) + " not supported yet");
1284 // Macro-like directives
1285 if (IDVal == ".rept")
1286 return ParseDirectiveRept(IDLoc);
1287 if (IDVal == ".irp")
1288 return ParseDirectiveIrp(IDLoc);
1289 if (IDVal == ".irpc")
1290 return ParseDirectiveIrpc(IDLoc);
1291 if (IDVal == ".endr")
1292 return ParseDirectiveEndr(IDLoc);
1294 // Look up the handler in the handler table.
1295 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1296 DirectiveMap.lookup(IDVal);
1298 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1301 return Error(IDLoc, "unknown directive");
1304 CheckForValidSection();
1306 // Canonicalize the opcode to lower case.
1307 SmallString<128> Opcode;
1308 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1309 Opcode.push_back(tolower(IDVal[i]));
1311 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1312 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1315 // Dump the parsed representation, if requested.
1316 if (getShowParsedOperands()) {
1317 SmallString<256> Str;
1318 raw_svector_ostream OS(Str);
1319 OS << "parsed instruction: [";
1320 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1323 ParsedOperands[i]->print(OS);
1327 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1330 // If we are generating dwarf for assembly source files and the current
1331 // section is the initial text section then generate a .loc directive for
1333 if (!HadError && getContext().getGenDwarfForAssembly() &&
1334 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1335 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1336 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1337 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1338 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1342 // If parsing succeeded, match the instruction.
1344 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1347 // Free any parsed operands.
1348 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1349 delete ParsedOperands[i];
1351 // Don't skip the rest of the line, the instruction parser is responsible for
1356 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1357 /// since they may not be able to be tokenized to get to the end of line token.
1358 void AsmParser::EatToEndOfLine() {
1359 if (!Lexer.is(AsmToken::EndOfStatement))
1360 Lexer.LexUntilEndOfLine();
1365 /// ParseCppHashLineFilenameComment as this:
1366 /// ::= # number "filename"
1367 /// or just as a full line comment if it doesn't have a number and a string.
1368 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1369 Lex(); // Eat the hash token.
1371 if (getLexer().isNot(AsmToken::Integer)) {
1372 // Consume the line since in cases it is not a well-formed line directive,
1373 // as if were simply a full line comment.
1378 int64_t LineNumber = getTok().getIntVal();
1381 if (getLexer().isNot(AsmToken::String)) {
1386 StringRef Filename = getTok().getString();
1387 // Get rid of the enclosing quotes.
1388 Filename = Filename.substr(1, Filename.size()-2);
1390 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1392 CppHashFilename = Filename;
1393 CppHashLineNumber = LineNumber;
1395 // Ignore any trailing characters, they're just comment.
1400 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1401 /// for the Filename and LineNo if any in the diagnostic.
1402 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1403 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1404 raw_ostream &OS = errs();
1406 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1407 const SMLoc &DiagLoc = Diag.getLoc();
1408 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1409 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1411 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1412 // before printing the message.
1413 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1414 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1415 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1416 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1419 // If we have not parsed a cpp hash line filename comment or the source
1420 // manager changed or buffer changed (like in a nested include) then just
1421 // print the normal diagnostic using its Filename and LineNo.
1422 if (!Parser->CppHashLineNumber ||
1423 &DiagSrcMgr != &Parser->SrcMgr ||
1424 DiagBuf != CppHashBuf) {
1425 if (Parser->SavedDiagHandler)
1426 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1432 // Use the CppHashFilename and calculate a line number based on the
1433 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1435 const std::string Filename = Parser->CppHashFilename;
1437 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1438 int CppHashLocLineNo =
1439 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1440 int LineNo = Parser->CppHashLineNumber - 1 +
1441 (DiagLocLineNo - CppHashLocLineNo);
1443 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1444 Filename, LineNo, Diag.getColumnNo(),
1445 Diag.getKind(), Diag.getMessage(),
1446 Diag.getLineContents(), Diag.getRanges());
1448 if (Parser->SavedDiagHandler)
1449 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1451 NewDiag.print(0, OS);
1454 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1455 const std::vector<StringRef> &Parameters,
1456 const std::vector<MacroArgument> &A,
1458 unsigned NParameters = Parameters.size();
1459 if (NParameters != 0 && NParameters != A.size())
1460 return Error(L, "Wrong number of arguments");
1462 while (!Body.empty()) {
1463 // Scan for the next substitution.
1464 std::size_t End = Body.size(), Pos = 0;
1465 for (; Pos != End; ++Pos) {
1466 // Check for a substitution or escape.
1468 // This macro has no parameters, look for $0, $1, etc.
1469 if (Body[Pos] != '$' || Pos + 1 == End)
1472 char Next = Body[Pos + 1];
1473 if (Next == '$' || Next == 'n' || isdigit(Next))
1476 // This macro has parameters, look for \foo, \bar, etc.
1477 if (Body[Pos] == '\\' && Pos + 1 != End)
1483 OS << Body.slice(0, Pos);
1485 // Check if we reached the end.
1490 switch (Body[Pos+1]) {
1496 // $n => number of arguments
1501 // $[0-9] => argument
1503 // Missing arguments are ignored.
1504 unsigned Index = Body[Pos+1] - '0';
1505 if (Index >= A.size())
1508 // Otherwise substitute with the token values, with spaces eliminated.
1509 for (MacroArgument::const_iterator it = A[Index].begin(),
1510 ie = A[Index].end(); it != ie; ++it)
1511 OS << it->getString();
1517 unsigned I = Pos + 1;
1518 while (isalnum(Body[I]) && I + 1 != End)
1521 const char *Begin = Body.data() + Pos +1;
1522 StringRef Argument(Begin, I - (Pos +1));
1524 for (; Index < NParameters; ++Index)
1525 if (Parameters[Index] == Argument)
1528 // FIXME: We should error at the macro definition.
1529 if (Index == NParameters)
1530 return Error(L, "Parameter not found");
1532 for (MacroArgument::const_iterator it = A[Index].begin(),
1533 ie = A[Index].end(); it != ie; ++it)
1534 OS << it->getString();
1536 Pos += 1 + Argument.size();
1538 // Update the scan point.
1539 Body = Body.substr(Pos);
1545 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1547 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1551 /// ParseMacroArgument - Extract AsmTokens for a macro argument.
1552 /// This is used for both default macro parameter values and the
1553 /// arguments in macro invocations
1554 bool AsmParser::ParseMacroArgument(MacroArgument &MA) {
1555 unsigned ParenLevel = 0;
1560 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1561 return TokError("unexpected token in macro instantiation");
1563 // HandleMacroEntry relies on not advancing the lexer here
1564 // to be able to fill in the remaining default parameter values
1565 if (Lexer.is(AsmToken::EndOfStatement))
1567 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1570 // Adjust the current parentheses level.
1571 if (Lexer.is(AsmToken::LParen))
1573 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1576 // Append the token to the current argument list.
1577 MA.push_back(getTok());
1580 if (ParenLevel != 0)
1581 return TokError("unbalanced parenthesises in macro argument");
1585 // Parse the macro instantiation arguments.
1586 bool AsmParser::ParseMacroArguments(const Macro *M,
1587 std::vector<MacroArgument> &A) {
1588 const unsigned NParameters = M ? M->Parameters.size() : 0;
1590 // Parse two kinds of macro invocations:
1591 // - macros defined without any parameters accept an arbitrary number of them
1592 // - macros defined with parameters accept at most that many of them
1593 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1597 if (ParseMacroArgument(MA))
1602 if (Lexer.is(AsmToken::EndOfStatement))
1605 if (Lexer.is(AsmToken::Comma))
1608 return TokError("Too many arguments");
1611 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1613 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1614 // this, although we should protect against infinite loops.
1615 if (ActiveMacros.size() == 20)
1616 return TokError("macros cannot be nested more than 20 levels deep");
1618 std::vector<MacroArgument> MacroArguments;
1619 if (ParseMacroArguments(M, MacroArguments))
1622 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1623 // to hold the macro body with substitutions.
1624 SmallString<256> Buf;
1625 StringRef Body = M->Body;
1626 raw_svector_ostream OS(Buf);
1628 if (expandMacro(OS, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1631 // We include the .endmacro in the buffer as our queue to exit the macro
1633 OS << ".endmacro\n";
1635 MemoryBuffer *Instantiation =
1636 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1638 // Create the macro instantiation object and add to the current macro
1639 // instantiation stack.
1640 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1643 ActiveMacros.push_back(MI);
1645 // Jump to the macro instantiation and prime the lexer.
1646 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1647 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1653 void AsmParser::HandleMacroExit() {
1654 // Jump to the EndOfStatement we should return to, and consume it.
1655 JumpToLoc(ActiveMacros.back()->ExitLoc);
1658 // Pop the instantiation entry.
1659 delete ActiveMacros.back();
1660 ActiveMacros.pop_back();
1663 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1664 switch (Value->getKind()) {
1665 case MCExpr::Binary: {
1666 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1667 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1670 case MCExpr::Target:
1671 case MCExpr::Constant:
1673 case MCExpr::SymbolRef: {
1674 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1676 return IsUsedIn(Sym, S.getVariableValue());
1680 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1683 llvm_unreachable("Unknown expr kind!");
1686 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1687 // FIXME: Use better location, we should use proper tokens.
1688 SMLoc EqualLoc = Lexer.getLoc();
1690 const MCExpr *Value;
1691 if (ParseExpression(Value))
1694 // Note: we don't count b as used in "a = b". This is to allow
1698 if (Lexer.isNot(AsmToken::EndOfStatement))
1699 return TokError("unexpected token in assignment");
1701 // Error on assignment to '.'.
1703 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1704 "(use '.space' or '.org').)"));
1707 // Eat the end of statement marker.
1710 // Validate that the LHS is allowed to be a variable (either it has not been
1711 // used as a symbol, or it is an absolute symbol).
1712 MCSymbol *Sym = getContext().LookupSymbol(Name);
1714 // Diagnose assignment to a label.
1716 // FIXME: Diagnostics. Note the location of the definition as a label.
1717 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1718 if (IsUsedIn(Sym, Value))
1719 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1720 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1721 ; // Allow redefinitions of undefined symbols only used in directives.
1722 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1723 ; // Allow redefinitions of variables that haven't yet been used.
1724 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1725 return Error(EqualLoc, "redefinition of '" + Name + "'");
1726 else if (!Sym->isVariable())
1727 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1728 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1729 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1732 // Don't count these checks as uses.
1733 Sym->setUsed(false);
1735 Sym = getContext().GetOrCreateSymbol(Name);
1737 // FIXME: Handle '.'.
1739 // Do the assignment.
1740 Out.EmitAssignment(Sym, Value);
1745 /// ParseIdentifier:
1748 bool AsmParser::ParseIdentifier(StringRef &Res) {
1749 // The assembler has relaxed rules for accepting identifiers, in particular we
1750 // allow things like '.globl $foo', which would normally be separate
1751 // tokens. At this level, we have already lexed so we cannot (currently)
1752 // handle this as a context dependent token, instead we detect adjacent tokens
1753 // and return the combined identifier.
1754 if (Lexer.is(AsmToken::Dollar)) {
1755 SMLoc DollarLoc = getLexer().getLoc();
1757 // Consume the dollar sign, and check for a following identifier.
1759 if (Lexer.isNot(AsmToken::Identifier))
1762 // We have a '$' followed by an identifier, make sure they are adjacent.
1763 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1766 // Construct the joined identifier and consume the token.
1767 Res = StringRef(DollarLoc.getPointer(),
1768 getTok().getIdentifier().size() + 1);
1773 if (Lexer.isNot(AsmToken::Identifier) &&
1774 Lexer.isNot(AsmToken::String))
1777 Res = getTok().getIdentifier();
1779 Lex(); // Consume the identifier token.
1784 /// ParseDirectiveSet:
1785 /// ::= .equ identifier ',' expression
1786 /// ::= .equiv identifier ',' expression
1787 /// ::= .set identifier ',' expression
1788 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1791 if (ParseIdentifier(Name))
1792 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1794 if (getLexer().isNot(AsmToken::Comma))
1795 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1798 return ParseAssignment(Name, allow_redef);
1801 bool AsmParser::ParseEscapedString(std::string &Data) {
1802 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1805 StringRef Str = getTok().getStringContents();
1806 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1807 if (Str[i] != '\\') {
1812 // Recognize escaped characters. Note that this escape semantics currently
1813 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1816 return TokError("unexpected backslash at end of string");
1818 // Recognize octal sequences.
1819 if ((unsigned) (Str[i] - '0') <= 7) {
1820 // Consume up to three octal characters.
1821 unsigned Value = Str[i] - '0';
1823 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1825 Value = Value * 8 + (Str[i] - '0');
1827 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1829 Value = Value * 8 + (Str[i] - '0');
1834 return TokError("invalid octal escape sequence (out of range)");
1836 Data += (unsigned char) Value;
1840 // Otherwise recognize individual escapes.
1843 // Just reject invalid escape sequences for now.
1844 return TokError("invalid escape sequence (unrecognized character)");
1846 case 'b': Data += '\b'; break;
1847 case 'f': Data += '\f'; break;
1848 case 'n': Data += '\n'; break;
1849 case 'r': Data += '\r'; break;
1850 case 't': Data += '\t'; break;
1851 case '"': Data += '"'; break;
1852 case '\\': Data += '\\'; break;
1859 /// ParseDirectiveAscii:
1860 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1861 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1862 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1863 CheckForValidSection();
1866 if (getLexer().isNot(AsmToken::String))
1867 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1870 if (ParseEscapedString(Data))
1873 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1875 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1879 if (getLexer().is(AsmToken::EndOfStatement))
1882 if (getLexer().isNot(AsmToken::Comma))
1883 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1892 /// ParseDirectiveValue
1893 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1894 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1895 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1896 CheckForValidSection();
1899 const MCExpr *Value;
1900 SMLoc ExprLoc = getLexer().getLoc();
1901 if (ParseExpression(Value))
1904 // Special case constant expressions to match code generator.
1905 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1906 assert(Size <= 8 && "Invalid size");
1907 uint64_t IntValue = MCE->getValue();
1908 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1909 return Error(ExprLoc, "literal value out of range for directive");
1910 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1912 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1914 if (getLexer().is(AsmToken::EndOfStatement))
1917 // FIXME: Improve diagnostic.
1918 if (getLexer().isNot(AsmToken::Comma))
1919 return TokError("unexpected token in directive");
1928 /// ParseDirectiveRealValue
1929 /// ::= (.single | .double) [ expression (, expression)* ]
1930 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1931 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1932 CheckForValidSection();
1935 // We don't truly support arithmetic on floating point expressions, so we
1936 // have to manually parse unary prefixes.
1938 if (getLexer().is(AsmToken::Minus)) {
1941 } else if (getLexer().is(AsmToken::Plus))
1944 if (getLexer().isNot(AsmToken::Integer) &&
1945 getLexer().isNot(AsmToken::Real) &&
1946 getLexer().isNot(AsmToken::Identifier))
1947 return TokError("unexpected token in directive");
1949 // Convert to an APFloat.
1950 APFloat Value(Semantics);
1951 StringRef IDVal = getTok().getString();
1952 if (getLexer().is(AsmToken::Identifier)) {
1953 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1954 Value = APFloat::getInf(Semantics);
1955 else if (!IDVal.compare_lower("nan"))
1956 Value = APFloat::getNaN(Semantics, false, ~0);
1958 return TokError("invalid floating point literal");
1959 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1960 APFloat::opInvalidOp)
1961 return TokError("invalid floating point literal");
1965 // Consume the numeric token.
1968 // Emit the value as an integer.
1969 APInt AsInt = Value.bitcastToAPInt();
1970 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1971 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1973 if (getLexer().is(AsmToken::EndOfStatement))
1976 if (getLexer().isNot(AsmToken::Comma))
1977 return TokError("unexpected token in directive");
1986 /// ParseDirectiveSpace
1987 /// ::= .space expression [ , expression ]
1988 bool AsmParser::ParseDirectiveSpace() {
1989 CheckForValidSection();
1992 if (ParseAbsoluteExpression(NumBytes))
1995 int64_t FillExpr = 0;
1996 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1997 if (getLexer().isNot(AsmToken::Comma))
1998 return TokError("unexpected token in '.space' directive");
2001 if (ParseAbsoluteExpression(FillExpr))
2004 if (getLexer().isNot(AsmToken::EndOfStatement))
2005 return TokError("unexpected token in '.space' directive");
2011 return TokError("invalid number of bytes in '.space' directive");
2013 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
2014 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
2019 /// ParseDirectiveZero
2020 /// ::= .zero expression
2021 bool AsmParser::ParseDirectiveZero() {
2022 CheckForValidSection();
2025 if (ParseAbsoluteExpression(NumBytes))
2029 if (getLexer().is(AsmToken::Comma)) {
2031 if (ParseAbsoluteExpression(Val))
2035 if (getLexer().isNot(AsmToken::EndOfStatement))
2036 return TokError("unexpected token in '.zero' directive");
2040 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2045 /// ParseDirectiveFill
2046 /// ::= .fill expression , expression , expression
2047 bool AsmParser::ParseDirectiveFill() {
2048 CheckForValidSection();
2051 if (ParseAbsoluteExpression(NumValues))
2054 if (getLexer().isNot(AsmToken::Comma))
2055 return TokError("unexpected token in '.fill' directive");
2059 if (ParseAbsoluteExpression(FillSize))
2062 if (getLexer().isNot(AsmToken::Comma))
2063 return TokError("unexpected token in '.fill' directive");
2067 if (ParseAbsoluteExpression(FillExpr))
2070 if (getLexer().isNot(AsmToken::EndOfStatement))
2071 return TokError("unexpected token in '.fill' directive");
2075 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2076 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2078 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2079 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2084 /// ParseDirectiveOrg
2085 /// ::= .org expression [ , expression ]
2086 bool AsmParser::ParseDirectiveOrg() {
2087 CheckForValidSection();
2089 const MCExpr *Offset;
2090 SMLoc Loc = getTok().getLoc();
2091 if (ParseExpression(Offset))
2094 // Parse optional fill expression.
2095 int64_t FillExpr = 0;
2096 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2097 if (getLexer().isNot(AsmToken::Comma))
2098 return TokError("unexpected token in '.org' directive");
2101 if (ParseAbsoluteExpression(FillExpr))
2104 if (getLexer().isNot(AsmToken::EndOfStatement))
2105 return TokError("unexpected token in '.org' directive");
2110 // Only limited forms of relocatable expressions are accepted here, it
2111 // has to be relative to the current section. The streamer will return
2112 // 'true' if the expression wasn't evaluatable.
2113 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2114 return Error(Loc, "expected assembly-time absolute expression");
2119 /// ParseDirectiveAlign
2120 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2121 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2122 CheckForValidSection();
2124 SMLoc AlignmentLoc = getLexer().getLoc();
2126 if (ParseAbsoluteExpression(Alignment))
2130 bool HasFillExpr = false;
2131 int64_t FillExpr = 0;
2132 int64_t MaxBytesToFill = 0;
2133 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2134 if (getLexer().isNot(AsmToken::Comma))
2135 return TokError("unexpected token in directive");
2138 // The fill expression can be omitted while specifying a maximum number of
2139 // alignment bytes, e.g:
2141 if (getLexer().isNot(AsmToken::Comma)) {
2143 if (ParseAbsoluteExpression(FillExpr))
2147 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2148 if (getLexer().isNot(AsmToken::Comma))
2149 return TokError("unexpected token in directive");
2152 MaxBytesLoc = getLexer().getLoc();
2153 if (ParseAbsoluteExpression(MaxBytesToFill))
2156 if (getLexer().isNot(AsmToken::EndOfStatement))
2157 return TokError("unexpected token in directive");
2166 // Compute alignment in bytes.
2168 // FIXME: Diagnose overflow.
2169 if (Alignment >= 32) {
2170 Error(AlignmentLoc, "invalid alignment value");
2174 Alignment = 1ULL << Alignment;
2177 // Diagnose non-sensical max bytes to align.
2178 if (MaxBytesLoc.isValid()) {
2179 if (MaxBytesToFill < 1) {
2180 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2181 "many bytes, ignoring maximum bytes expression");
2185 if (MaxBytesToFill >= Alignment) {
2186 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2192 // Check whether we should use optimal code alignment for this .align
2194 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2195 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2196 ValueSize == 1 && UseCodeAlign) {
2197 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2199 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2200 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2207 /// ParseDirectiveSymbolAttribute
2208 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2209 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2210 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2213 SMLoc Loc = getTok().getLoc();
2215 if (ParseIdentifier(Name))
2216 return Error(Loc, "expected identifier in directive");
2218 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2220 // Assembler local symbols don't make any sense here. Complain loudly.
2221 if (Sym->isTemporary())
2222 return Error(Loc, "non-local symbol required in directive");
2224 getStreamer().EmitSymbolAttribute(Sym, Attr);
2226 if (getLexer().is(AsmToken::EndOfStatement))
2229 if (getLexer().isNot(AsmToken::Comma))
2230 return TokError("unexpected token in directive");
2239 /// ParseDirectiveComm
2240 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2241 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2242 CheckForValidSection();
2244 SMLoc IDLoc = getLexer().getLoc();
2246 if (ParseIdentifier(Name))
2247 return TokError("expected identifier in directive");
2249 // Handle the identifier as the key symbol.
2250 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2252 if (getLexer().isNot(AsmToken::Comma))
2253 return TokError("unexpected token in directive");
2257 SMLoc SizeLoc = getLexer().getLoc();
2258 if (ParseAbsoluteExpression(Size))
2261 int64_t Pow2Alignment = 0;
2262 SMLoc Pow2AlignmentLoc;
2263 if (getLexer().is(AsmToken::Comma)) {
2265 Pow2AlignmentLoc = getLexer().getLoc();
2266 if (ParseAbsoluteExpression(Pow2Alignment))
2269 // If this target takes alignments in bytes (not log) validate and convert.
2270 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2271 if (!isPowerOf2_64(Pow2Alignment))
2272 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2273 Pow2Alignment = Log2_64(Pow2Alignment);
2277 if (getLexer().isNot(AsmToken::EndOfStatement))
2278 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2282 // NOTE: a size of zero for a .comm should create a undefined symbol
2283 // but a size of .lcomm creates a bss symbol of size zero.
2285 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2286 "be less than zero");
2288 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2289 // may internally end up wanting an alignment in bytes.
2290 // FIXME: Diagnose overflow.
2291 if (Pow2Alignment < 0)
2292 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2293 "alignment, can't be less than zero");
2295 if (!Sym->isUndefined())
2296 return Error(IDLoc, "invalid symbol redefinition");
2298 // '.lcomm' is equivalent to '.zerofill'.
2299 // Create the Symbol as a common or local common with Size and Pow2Alignment
2301 getStreamer().EmitZerofill(Ctx.getMachOSection(
2302 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2303 0, SectionKind::getBSS()),
2304 Sym, Size, 1 << Pow2Alignment);
2308 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2312 /// ParseDirectiveAbort
2313 /// ::= .abort [... message ...]
2314 bool AsmParser::ParseDirectiveAbort() {
2315 // FIXME: Use loc from directive.
2316 SMLoc Loc = getLexer().getLoc();
2318 StringRef Str = ParseStringToEndOfStatement();
2319 if (getLexer().isNot(AsmToken::EndOfStatement))
2320 return TokError("unexpected token in '.abort' directive");
2325 Error(Loc, ".abort detected. Assembly stopping.");
2327 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2328 // FIXME: Actually abort assembly here.
2333 /// ParseDirectiveInclude
2334 /// ::= .include "filename"
2335 bool AsmParser::ParseDirectiveInclude() {
2336 if (getLexer().isNot(AsmToken::String))
2337 return TokError("expected string in '.include' directive");
2339 std::string Filename = getTok().getString();
2340 SMLoc IncludeLoc = getLexer().getLoc();
2343 if (getLexer().isNot(AsmToken::EndOfStatement))
2344 return TokError("unexpected token in '.include' directive");
2346 // Strip the quotes.
2347 Filename = Filename.substr(1, Filename.size()-2);
2349 // Attempt to switch the lexer to the included file before consuming the end
2350 // of statement to avoid losing it when we switch.
2351 if (EnterIncludeFile(Filename)) {
2352 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2359 /// ParseDirectiveIncbin
2360 /// ::= .incbin "filename"
2361 bool AsmParser::ParseDirectiveIncbin() {
2362 if (getLexer().isNot(AsmToken::String))
2363 return TokError("expected string in '.incbin' directive");
2365 std::string Filename = getTok().getString();
2366 SMLoc IncbinLoc = getLexer().getLoc();
2369 if (getLexer().isNot(AsmToken::EndOfStatement))
2370 return TokError("unexpected token in '.incbin' directive");
2372 // Strip the quotes.
2373 Filename = Filename.substr(1, Filename.size()-2);
2375 // Attempt to process the included file.
2376 if (ProcessIncbinFile(Filename)) {
2377 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2384 /// ParseDirectiveIf
2385 /// ::= .if expression
2386 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2387 TheCondStack.push_back(TheCondState);
2388 TheCondState.TheCond = AsmCond::IfCond;
2389 if (TheCondState.Ignore) {
2390 EatToEndOfStatement();
2393 if (ParseAbsoluteExpression(ExprValue))
2396 if (getLexer().isNot(AsmToken::EndOfStatement))
2397 return TokError("unexpected token in '.if' directive");
2401 TheCondState.CondMet = ExprValue;
2402 TheCondState.Ignore = !TheCondState.CondMet;
2408 /// ParseDirectiveIfb
2410 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2411 TheCondStack.push_back(TheCondState);
2412 TheCondState.TheCond = AsmCond::IfCond;
2414 if (TheCondState.Ignore) {
2415 EatToEndOfStatement();
2417 StringRef Str = ParseStringToEndOfStatement();
2419 if (getLexer().isNot(AsmToken::EndOfStatement))
2420 return TokError("unexpected token in '.ifb' directive");
2424 TheCondState.CondMet = ExpectBlank == Str.empty();
2425 TheCondState.Ignore = !TheCondState.CondMet;
2431 /// ParseDirectiveIfc
2432 /// ::= .ifc string1, string2
2433 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2434 TheCondStack.push_back(TheCondState);
2435 TheCondState.TheCond = AsmCond::IfCond;
2437 if (TheCondState.Ignore) {
2438 EatToEndOfStatement();
2440 StringRef Str1 = ParseStringToComma();
2442 if (getLexer().isNot(AsmToken::Comma))
2443 return TokError("unexpected token in '.ifc' directive");
2447 StringRef Str2 = ParseStringToEndOfStatement();
2449 if (getLexer().isNot(AsmToken::EndOfStatement))
2450 return TokError("unexpected token in '.ifc' directive");
2454 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2455 TheCondState.Ignore = !TheCondState.CondMet;
2461 /// ParseDirectiveIfdef
2462 /// ::= .ifdef symbol
2463 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2465 TheCondStack.push_back(TheCondState);
2466 TheCondState.TheCond = AsmCond::IfCond;
2468 if (TheCondState.Ignore) {
2469 EatToEndOfStatement();
2471 if (ParseIdentifier(Name))
2472 return TokError("expected identifier after '.ifdef'");
2476 MCSymbol *Sym = getContext().LookupSymbol(Name);
2479 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2481 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2482 TheCondState.Ignore = !TheCondState.CondMet;
2488 /// ParseDirectiveElseIf
2489 /// ::= .elseif expression
2490 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2491 if (TheCondState.TheCond != AsmCond::IfCond &&
2492 TheCondState.TheCond != AsmCond::ElseIfCond)
2493 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2495 TheCondState.TheCond = AsmCond::ElseIfCond;
2497 bool LastIgnoreState = false;
2498 if (!TheCondStack.empty())
2499 LastIgnoreState = TheCondStack.back().Ignore;
2500 if (LastIgnoreState || TheCondState.CondMet) {
2501 TheCondState.Ignore = true;
2502 EatToEndOfStatement();
2506 if (ParseAbsoluteExpression(ExprValue))
2509 if (getLexer().isNot(AsmToken::EndOfStatement))
2510 return TokError("unexpected token in '.elseif' directive");
2513 TheCondState.CondMet = ExprValue;
2514 TheCondState.Ignore = !TheCondState.CondMet;
2520 /// ParseDirectiveElse
2522 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2523 if (getLexer().isNot(AsmToken::EndOfStatement))
2524 return TokError("unexpected token in '.else' directive");
2528 if (TheCondState.TheCond != AsmCond::IfCond &&
2529 TheCondState.TheCond != AsmCond::ElseIfCond)
2530 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2532 TheCondState.TheCond = AsmCond::ElseCond;
2533 bool LastIgnoreState = false;
2534 if (!TheCondStack.empty())
2535 LastIgnoreState = TheCondStack.back().Ignore;
2536 if (LastIgnoreState || TheCondState.CondMet)
2537 TheCondState.Ignore = true;
2539 TheCondState.Ignore = false;
2544 /// ParseDirectiveEndIf
2546 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2547 if (getLexer().isNot(AsmToken::EndOfStatement))
2548 return TokError("unexpected token in '.endif' directive");
2552 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2553 TheCondStack.empty())
2554 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2556 if (!TheCondStack.empty()) {
2557 TheCondState = TheCondStack.back();
2558 TheCondStack.pop_back();
2564 /// ParseDirectiveFile
2565 /// ::= .file [number] filename
2566 /// ::= .file number directory filename
2567 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2568 // FIXME: I'm not sure what this is.
2569 int64_t FileNumber = -1;
2570 SMLoc FileNumberLoc = getLexer().getLoc();
2571 if (getLexer().is(AsmToken::Integer)) {
2572 FileNumber = getTok().getIntVal();
2576 return TokError("file number less than one");
2579 if (getLexer().isNot(AsmToken::String))
2580 return TokError("unexpected token in '.file' directive");
2582 // Usually the directory and filename together, otherwise just the directory.
2583 StringRef Path = getTok().getString();
2584 Path = Path.substr(1, Path.size()-2);
2587 StringRef Directory;
2589 if (getLexer().is(AsmToken::String)) {
2590 if (FileNumber == -1)
2591 return TokError("explicit path specified, but no file number");
2592 Filename = getTok().getString();
2593 Filename = Filename.substr(1, Filename.size()-2);
2600 if (getLexer().isNot(AsmToken::EndOfStatement))
2601 return TokError("unexpected token in '.file' directive");
2603 if (FileNumber == -1)
2604 getStreamer().EmitFileDirective(Filename);
2606 if (getContext().getGenDwarfForAssembly() == true)
2607 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2608 "used to generate dwarf debug info for assembly code");
2610 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2611 Error(FileNumberLoc, "file number already allocated");
2617 /// ParseDirectiveLine
2618 /// ::= .line [number]
2619 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2620 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2621 if (getLexer().isNot(AsmToken::Integer))
2622 return TokError("unexpected token in '.line' directive");
2624 int64_t LineNumber = getTok().getIntVal();
2628 // FIXME: Do something with the .line.
2631 if (getLexer().isNot(AsmToken::EndOfStatement))
2632 return TokError("unexpected token in '.line' directive");
2638 /// ParseDirectiveLoc
2639 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2640 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2641 /// The first number is a file number, must have been previously assigned with
2642 /// a .file directive, the second number is the line number and optionally the
2643 /// third number is a column position (zero if not specified). The remaining
2644 /// optional items are .loc sub-directives.
2645 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2647 if (getLexer().isNot(AsmToken::Integer))
2648 return TokError("unexpected token in '.loc' directive");
2649 int64_t FileNumber = getTok().getIntVal();
2651 return TokError("file number less than one in '.loc' directive");
2652 if (!getContext().isValidDwarfFileNumber(FileNumber))
2653 return TokError("unassigned file number in '.loc' directive");
2656 int64_t LineNumber = 0;
2657 if (getLexer().is(AsmToken::Integer)) {
2658 LineNumber = getTok().getIntVal();
2660 return TokError("line number less than one in '.loc' directive");
2664 int64_t ColumnPos = 0;
2665 if (getLexer().is(AsmToken::Integer)) {
2666 ColumnPos = getTok().getIntVal();
2668 return TokError("column position less than zero in '.loc' directive");
2672 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2674 int64_t Discriminator = 0;
2675 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2677 if (getLexer().is(AsmToken::EndOfStatement))
2681 SMLoc Loc = getTok().getLoc();
2682 if (getParser().ParseIdentifier(Name))
2683 return TokError("unexpected token in '.loc' directive");
2685 if (Name == "basic_block")
2686 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2687 else if (Name == "prologue_end")
2688 Flags |= DWARF2_FLAG_PROLOGUE_END;
2689 else if (Name == "epilogue_begin")
2690 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2691 else if (Name == "is_stmt") {
2692 SMLoc Loc = getTok().getLoc();
2693 const MCExpr *Value;
2694 if (getParser().ParseExpression(Value))
2696 // The expression must be the constant 0 or 1.
2697 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2698 int Value = MCE->getValue();
2700 Flags &= ~DWARF2_FLAG_IS_STMT;
2701 else if (Value == 1)
2702 Flags |= DWARF2_FLAG_IS_STMT;
2704 return Error(Loc, "is_stmt value not 0 or 1");
2707 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2710 else if (Name == "isa") {
2711 SMLoc Loc = getTok().getLoc();
2712 const MCExpr *Value;
2713 if (getParser().ParseExpression(Value))
2715 // The expression must be a constant greater or equal to 0.
2716 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2717 int Value = MCE->getValue();
2719 return Error(Loc, "isa number less than zero");
2723 return Error(Loc, "isa number not a constant value");
2726 else if (Name == "discriminator") {
2727 if (getParser().ParseAbsoluteExpression(Discriminator))
2731 return Error(Loc, "unknown sub-directive in '.loc' directive");
2734 if (getLexer().is(AsmToken::EndOfStatement))
2739 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2740 Isa, Discriminator, StringRef());
2745 /// ParseDirectiveStabs
2746 /// ::= .stabs string, number, number, number
2747 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2748 SMLoc DirectiveLoc) {
2749 return TokError("unsupported directive '" + Directive + "'");
2752 /// ParseDirectiveCFISections
2753 /// ::= .cfi_sections section [, section]
2754 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2755 SMLoc DirectiveLoc) {
2760 if (getParser().ParseIdentifier(Name))
2761 return TokError("Expected an identifier");
2763 if (Name == ".eh_frame")
2765 else if (Name == ".debug_frame")
2768 if (getLexer().is(AsmToken::Comma)) {
2771 if (getParser().ParseIdentifier(Name))
2772 return TokError("Expected an identifier");
2774 if (Name == ".eh_frame")
2776 else if (Name == ".debug_frame")
2780 getStreamer().EmitCFISections(EH, Debug);
2785 /// ParseDirectiveCFIStartProc
2786 /// ::= .cfi_startproc
2787 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2788 SMLoc DirectiveLoc) {
2789 getStreamer().EmitCFIStartProc();
2793 /// ParseDirectiveCFIEndProc
2794 /// ::= .cfi_endproc
2795 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2796 getStreamer().EmitCFIEndProc();
2800 /// ParseRegisterOrRegisterNumber - parse register name or number.
2801 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2802 SMLoc DirectiveLoc) {
2805 if (getLexer().isNot(AsmToken::Integer)) {
2806 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2809 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2811 return getParser().ParseAbsoluteExpression(Register);
2816 /// ParseDirectiveCFIDefCfa
2817 /// ::= .cfi_def_cfa register, offset
2818 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2819 SMLoc DirectiveLoc) {
2820 int64_t Register = 0;
2821 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2824 if (getLexer().isNot(AsmToken::Comma))
2825 return TokError("unexpected token in directive");
2829 if (getParser().ParseAbsoluteExpression(Offset))
2832 getStreamer().EmitCFIDefCfa(Register, Offset);
2836 /// ParseDirectiveCFIDefCfaOffset
2837 /// ::= .cfi_def_cfa_offset offset
2838 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2839 SMLoc DirectiveLoc) {
2841 if (getParser().ParseAbsoluteExpression(Offset))
2844 getStreamer().EmitCFIDefCfaOffset(Offset);
2848 /// ParseDirectiveCFIAdjustCfaOffset
2849 /// ::= .cfi_adjust_cfa_offset adjustment
2850 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2851 SMLoc DirectiveLoc) {
2852 int64_t Adjustment = 0;
2853 if (getParser().ParseAbsoluteExpression(Adjustment))
2856 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2860 /// ParseDirectiveCFIDefCfaRegister
2861 /// ::= .cfi_def_cfa_register register
2862 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2863 SMLoc DirectiveLoc) {
2864 int64_t Register = 0;
2865 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2868 getStreamer().EmitCFIDefCfaRegister(Register);
2872 /// ParseDirectiveCFIOffset
2873 /// ::= .cfi_offset register, offset
2874 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2875 int64_t Register = 0;
2878 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2881 if (getLexer().isNot(AsmToken::Comma))
2882 return TokError("unexpected token in directive");
2885 if (getParser().ParseAbsoluteExpression(Offset))
2888 getStreamer().EmitCFIOffset(Register, Offset);
2892 /// ParseDirectiveCFIRelOffset
2893 /// ::= .cfi_rel_offset register, offset
2894 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2895 SMLoc DirectiveLoc) {
2896 int64_t Register = 0;
2898 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2901 if (getLexer().isNot(AsmToken::Comma))
2902 return TokError("unexpected token in directive");
2906 if (getParser().ParseAbsoluteExpression(Offset))
2909 getStreamer().EmitCFIRelOffset(Register, Offset);
2913 static bool isValidEncoding(int64_t Encoding) {
2914 if (Encoding & ~0xff)
2917 if (Encoding == dwarf::DW_EH_PE_omit)
2920 const unsigned Format = Encoding & 0xf;
2921 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2922 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2923 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2924 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2927 const unsigned Application = Encoding & 0x70;
2928 if (Application != dwarf::DW_EH_PE_absptr &&
2929 Application != dwarf::DW_EH_PE_pcrel)
2935 /// ParseDirectiveCFIPersonalityOrLsda
2936 /// ::= .cfi_personality encoding, [symbol_name]
2937 /// ::= .cfi_lsda encoding, [symbol_name]
2938 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2939 SMLoc DirectiveLoc) {
2940 int64_t Encoding = 0;
2941 if (getParser().ParseAbsoluteExpression(Encoding))
2943 if (Encoding == dwarf::DW_EH_PE_omit)
2946 if (!isValidEncoding(Encoding))
2947 return TokError("unsupported encoding.");
2949 if (getLexer().isNot(AsmToken::Comma))
2950 return TokError("unexpected token in directive");
2954 if (getParser().ParseIdentifier(Name))
2955 return TokError("expected identifier in directive");
2957 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2959 if (IDVal == ".cfi_personality")
2960 getStreamer().EmitCFIPersonality(Sym, Encoding);
2962 assert(IDVal == ".cfi_lsda");
2963 getStreamer().EmitCFILsda(Sym, Encoding);
2968 /// ParseDirectiveCFIRememberState
2969 /// ::= .cfi_remember_state
2970 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2971 SMLoc DirectiveLoc) {
2972 getStreamer().EmitCFIRememberState();
2976 /// ParseDirectiveCFIRestoreState
2977 /// ::= .cfi_remember_state
2978 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2979 SMLoc DirectiveLoc) {
2980 getStreamer().EmitCFIRestoreState();
2984 /// ParseDirectiveCFISameValue
2985 /// ::= .cfi_same_value register
2986 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2987 SMLoc DirectiveLoc) {
2988 int64_t Register = 0;
2990 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2993 getStreamer().EmitCFISameValue(Register);
2998 /// ParseDirectiveCFIRestore
2999 /// ::= .cfi_restore register
3000 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
3001 SMLoc DirectiveLoc) {
3002 int64_t Register = 0;
3003 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3006 getStreamer().EmitCFIRestore(Register);
3011 /// ParseDirectiveCFIEscape
3012 /// ::= .cfi_escape expression[,...]
3013 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3014 SMLoc DirectiveLoc) {
3017 if (getParser().ParseAbsoluteExpression(CurrValue))
3020 Values.push_back((uint8_t)CurrValue);
3022 while (getLexer().is(AsmToken::Comma)) {
3025 if (getParser().ParseAbsoluteExpression(CurrValue))
3028 Values.push_back((uint8_t)CurrValue);
3031 getStreamer().EmitCFIEscape(Values);
3035 /// ParseDirectiveCFISignalFrame
3036 /// ::= .cfi_signal_frame
3037 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3038 SMLoc DirectiveLoc) {
3039 if (getLexer().isNot(AsmToken::EndOfStatement))
3040 return Error(getLexer().getLoc(),
3041 "unexpected token in '" + Directive + "' directive");
3043 getStreamer().EmitCFISignalFrame();
3048 /// ParseDirectiveMacrosOnOff
3051 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3052 SMLoc DirectiveLoc) {
3053 if (getLexer().isNot(AsmToken::EndOfStatement))
3054 return Error(getLexer().getLoc(),
3055 "unexpected token in '" + Directive + "' directive");
3057 getParser().MacrosEnabled = Directive == ".macros_on";
3062 /// ParseDirectiveMacro
3063 /// ::= .macro name [parameters]
3064 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3065 SMLoc DirectiveLoc) {
3067 if (getParser().ParseIdentifier(Name))
3068 return TokError("expected identifier in directive");
3070 std::vector<StringRef> Parameters;
3071 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3073 StringRef Parameter;
3074 if (getParser().ParseIdentifier(Parameter))
3075 return TokError("expected identifier in directive");
3076 Parameters.push_back(Parameter);
3078 if (getLexer().isNot(AsmToken::Comma))
3084 if (getLexer().isNot(AsmToken::EndOfStatement))
3085 return TokError("unexpected token in '.macro' directive");
3087 // Eat the end of statement.
3090 AsmToken EndToken, StartToken = getTok();
3092 // Lex the macro definition.
3094 // Check whether we have reached the end of the file.
3095 if (getLexer().is(AsmToken::Eof))
3096 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3098 // Otherwise, check whether we have reach the .endmacro.
3099 if (getLexer().is(AsmToken::Identifier) &&
3100 (getTok().getIdentifier() == ".endm" ||
3101 getTok().getIdentifier() == ".endmacro")) {
3102 EndToken = getTok();
3104 if (getLexer().isNot(AsmToken::EndOfStatement))
3105 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3110 // Otherwise, scan til the end of the statement.
3111 getParser().EatToEndOfStatement();
3114 if (getParser().MacroMap.lookup(Name)) {
3115 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3118 const char *BodyStart = StartToken.getLoc().getPointer();
3119 const char *BodyEnd = EndToken.getLoc().getPointer();
3120 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3121 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3125 /// ParseDirectiveEndMacro
3128 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3129 SMLoc DirectiveLoc) {
3130 if (getLexer().isNot(AsmToken::EndOfStatement))
3131 return TokError("unexpected token in '" + Directive + "' directive");
3133 // If we are inside a macro instantiation, terminate the current
3135 if (!getParser().ActiveMacros.empty()) {
3136 getParser().HandleMacroExit();
3140 // Otherwise, this .endmacro is a stray entry in the file; well formed
3141 // .endmacro directives are handled during the macro definition parsing.
3142 return TokError("unexpected '" + Directive + "' in file, "
3143 "no current macro definition");
3146 /// ParseDirectivePurgeMacro
3148 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3149 SMLoc DirectiveLoc) {
3151 if (getParser().ParseIdentifier(Name))
3152 return TokError("expected identifier in '.purgem' directive");
3154 if (getLexer().isNot(AsmToken::EndOfStatement))
3155 return TokError("unexpected token in '.purgem' directive");
3157 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3158 if (I == getParser().MacroMap.end())
3159 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3161 // Undefine the macro.
3162 delete I->getValue();
3163 getParser().MacroMap.erase(I);
3167 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3168 getParser().CheckForValidSection();
3170 const MCExpr *Value;
3172 if (getParser().ParseExpression(Value))
3175 if (getLexer().isNot(AsmToken::EndOfStatement))
3176 return TokError("unexpected token in directive");
3178 if (DirName[1] == 's')
3179 getStreamer().EmitSLEB128Value(Value);
3181 getStreamer().EmitULEB128Value(Value);
3186 Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3187 AsmToken EndToken, StartToken = getTok();
3189 unsigned NestLevel = 0;
3191 // Check whether we have reached the end of the file.
3192 if (getLexer().is(AsmToken::Eof)) {
3193 Error(DirectiveLoc, "no matching '.endr' in definition");
3197 if (Lexer.is(AsmToken::Identifier) &&
3198 (getTok().getIdentifier() == ".rept")) {
3202 // Otherwise, check whether we have reached the .endr.
3203 if (Lexer.is(AsmToken::Identifier) &&
3204 getTok().getIdentifier() == ".endr") {
3205 if (NestLevel == 0) {
3206 EndToken = getTok();
3208 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3209 TokError("unexpected token in '.endr' directive");
3217 // Otherwise, scan till the end of the statement.
3218 EatToEndOfStatement();
3221 const char *BodyStart = StartToken.getLoc().getPointer();
3222 const char *BodyEnd = EndToken.getLoc().getPointer();
3223 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3225 // We Are Anonymous.
3227 std::vector<StringRef> Parameters;
3228 return new Macro(Name, Body, Parameters);
3231 void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3232 raw_svector_ostream &OS) {
3235 MemoryBuffer *Instantiation =
3236 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3238 // Create the macro instantiation object and add to the current macro
3239 // instantiation stack.
3240 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3243 ActiveMacros.push_back(MI);
3245 // Jump to the macro instantiation and prime the lexer.
3246 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3247 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3251 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3253 if (ParseAbsoluteExpression(Count))
3254 return TokError("unexpected token in '.rept' directive");
3257 return TokError("Count is negative");
3259 if (Lexer.isNot(AsmToken::EndOfStatement))
3260 return TokError("unexpected token in '.rept' directive");
3262 // Eat the end of statement.
3265 // Lex the rept definition.
3266 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3270 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3271 // to hold the macro body with substitutions.
3272 SmallString<256> Buf;
3273 std::vector<StringRef> Parameters;
3274 const std::vector<MacroArgument> A;
3275 raw_svector_ostream OS(Buf);
3277 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3280 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3285 /// ParseDirectiveIrp
3286 /// ::= .irp symbol,values
3287 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3288 std::vector<StringRef> Parameters;
3289 StringRef Parameter;
3291 if (ParseIdentifier(Parameter))
3292 return TokError("expected identifier in '.irp' directive");
3294 Parameters.push_back(Parameter);
3296 if (Lexer.isNot(AsmToken::Comma))
3297 return TokError("expected comma in '.irp' directive");
3301 std::vector<MacroArgument> A;
3302 if (ParseMacroArguments(0, A))
3305 // Eat the end of statement.
3308 // Lex the irp definition.
3309 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3313 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3314 // to hold the macro body with substitutions.
3315 SmallString<256> Buf;
3316 raw_svector_ostream OS(Buf);
3318 for (std::vector<MacroArgument>::iterator i = A.begin(), e = A.end(); i != e;
3320 std::vector<MacroArgument> Args;
3323 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3327 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3332 /// ParseDirectiveIrpc
3333 /// ::= .irpc symbol,values
3334 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3335 std::vector<StringRef> Parameters;
3336 StringRef Parameter;
3338 if (ParseIdentifier(Parameter))
3339 return TokError("expected identifier in '.irpc' directive");
3341 Parameters.push_back(Parameter);
3343 if (Lexer.isNot(AsmToken::Comma))
3344 return TokError("expected comma in '.irpc' directive");
3348 std::vector<MacroArgument> A;
3349 if (ParseMacroArguments(0, A))
3352 if (A.size() != 1 || A.front().size() != 1)
3353 return TokError("unexpected token in '.irpc' directive");
3355 // Eat the end of statement.
3358 // Lex the irpc definition.
3359 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3363 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3364 // to hold the macro body with substitutions.
3365 SmallString<256> Buf;
3366 raw_svector_ostream OS(Buf);
3368 StringRef Values = A.front().front().getString();
3369 std::size_t I, End = Values.size();
3370 for (I = 0; I < End; ++I) {
3372 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3374 std::vector<MacroArgument> Args;
3375 Args.push_back(Arg);
3377 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3381 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3386 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3387 if (ActiveMacros.empty())
3388 return TokError("unexpected '.endr' directive, no current .rept");
3390 // The only .repl that should get here are the ones created by
3391 // InstantiateMacroLikeBody.
3392 assert(getLexer().is(AsmToken::EndOfStatement));
3398 /// \brief Create an MCAsmParser instance.
3399 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3400 MCContext &C, MCStreamer &Out,
3401 const MCAsmInfo &MAI) {
3402 return new AsmParser(SM, C, Out, MAI);