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 /// \brief Parse up to the end of statement and a return the contents from the
210 /// current token until the end of the statement; the current token on exit
211 /// will be either the EndOfStatement or EOF.
212 StringRef ParseStringToEndOfStatement();
214 /// \brief Parse until the end of a statement or a comma is encountered,
215 /// return the contents from the current token up to the end or comma.
216 StringRef ParseStringToComma();
218 bool ParseAssignment(StringRef Name, bool allow_redef);
220 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
221 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
222 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
223 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
225 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
226 /// and set \arg Res to the identifier contents.
227 bool ParseIdentifier(StringRef &Res);
229 // Directive Parsing.
231 // ".ascii", ".asciiz", ".string"
232 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
233 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
234 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
235 bool ParseDirectiveFill(); // ".fill"
236 bool ParseDirectiveSpace(); // ".space"
237 bool ParseDirectiveZero(); // ".zero"
238 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
239 bool ParseDirectiveOrg(); // ".org"
240 // ".align{,32}", ".p2align{,w,l}"
241 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
243 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
244 /// accepts a single symbol (which should be a label or an external).
245 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
247 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
249 bool ParseDirectiveAbort(); // ".abort"
250 bool ParseDirectiveInclude(); // ".include"
251 bool ParseDirectiveIncbin(); // ".incbin"
253 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
254 // ".ifb" or ".ifnb", depending on ExpectBlank.
255 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
256 // ".ifc" or ".ifnc", depending on ExpectEqual.
257 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
258 // ".ifdef" or ".ifndef", depending on expect_defined
259 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
260 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
261 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
262 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
264 /// ParseEscapedString - Parse the current token as a string which may include
265 /// escaped characters and return the string contents.
266 bool ParseEscapedString(std::string &Data);
268 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
269 MCSymbolRefExpr::VariantKind Variant);
271 // Macro-like directives
272 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
273 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
274 raw_svector_ostream &OS);
275 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
276 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
279 /// \brief Generic implementations of directive handling, etc. which is shared
280 /// (or the default, at least) for all assembler parser.
281 class GenericAsmParser : public MCAsmParserExtension {
282 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
283 void AddDirectiveHandler(StringRef Directive) {
284 getParser().AddDirectiveHandler(this, Directive,
285 HandleDirective<GenericAsmParser, Handler>);
288 GenericAsmParser() {}
290 AsmParser &getParser() {
291 return (AsmParser&) this->MCAsmParserExtension::getParser();
294 virtual void Initialize(MCAsmParser &Parser) {
295 // Call the base implementation.
296 this->MCAsmParserExtension::Initialize(Parser);
298 // Debugging directives.
299 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
300 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
301 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
302 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
305 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
307 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
309 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
311 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
313 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
314 ".cfi_def_cfa_offset");
315 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
316 ".cfi_adjust_cfa_offset");
317 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
318 ".cfi_def_cfa_register");
319 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
321 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
324 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
326 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
328 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
330 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
332 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
334 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
336 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
338 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
341 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
343 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
345 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
346 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
347 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
348 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
350 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
351 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
354 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
356 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
357 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
358 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
359 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
360 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
361 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
362 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
363 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
364 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
365 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
366 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
367 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
368 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
369 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
370 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
371 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
372 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
373 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
374 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
375 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
377 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
378 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
379 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
380 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
382 bool ParseDirectiveLEB128(StringRef, SMLoc);
389 extern MCAsmParserExtension *createDarwinAsmParser();
390 extern MCAsmParserExtension *createELFAsmParser();
391 extern MCAsmParserExtension *createCOFFAsmParser();
395 enum { DEFAULT_ADDRSPACE = 0 };
397 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
398 MCStreamer &_Out, const MCAsmInfo &_MAI)
399 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
400 GenericParser(new GenericAsmParser), PlatformParser(0),
401 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
402 AssemblerDialect(~0U) {
403 // Save the old handler.
404 SavedDiagHandler = SrcMgr.getDiagHandler();
405 SavedDiagContext = SrcMgr.getDiagContext();
406 // Set our own handler which calls the saved handler.
407 SrcMgr.setDiagHandler(DiagHandler, this);
408 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
410 // Initialize the generic parser.
411 GenericParser->Initialize(*this);
413 // Initialize the platform / file format parser.
415 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
417 if (_MAI.hasMicrosoftFastStdCallMangling()) {
418 PlatformParser = createCOFFAsmParser();
419 PlatformParser->Initialize(*this);
420 } else if (_MAI.hasSubsectionsViaSymbols()) {
421 PlatformParser = createDarwinAsmParser();
422 PlatformParser->Initialize(*this);
424 PlatformParser = createELFAsmParser();
425 PlatformParser->Initialize(*this);
429 AsmParser::~AsmParser() {
430 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
432 // Destroy any macros.
433 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
434 ie = MacroMap.end(); it != ie; ++it)
435 delete it->getValue();
437 delete PlatformParser;
438 delete GenericParser;
441 void AsmParser::PrintMacroInstantiations() {
442 // Print the active macro instantiation stack.
443 for (std::vector<MacroInstantiation*>::const_reverse_iterator
444 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
445 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
446 "while in macro instantiation");
449 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
450 if (FatalAssemblerWarnings)
451 return Error(L, Msg, Ranges);
452 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
453 PrintMacroInstantiations();
457 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
459 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
460 PrintMacroInstantiations();
464 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
465 std::string IncludedFile;
466 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
472 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
477 /// Process the specified .incbin file by seaching for it in the include paths
478 /// then just emitting the byte contents of the file to the streamer. This
479 /// returns true on failure.
480 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
481 std::string IncludedFile;
482 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
486 // Pick up the bytes from the file and emit them.
487 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
492 void AsmParser::JumpToLoc(SMLoc Loc) {
493 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
494 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
497 const AsmToken &AsmParser::Lex() {
498 const AsmToken *tok = &Lexer.Lex();
500 if (tok->is(AsmToken::Eof)) {
501 // If this is the end of an included file, pop the parent file off the
503 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
504 if (ParentIncludeLoc != SMLoc()) {
505 JumpToLoc(ParentIncludeLoc);
510 if (tok->is(AsmToken::Error))
511 Error(Lexer.getErrLoc(), Lexer.getErr());
516 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
517 // Create the initial section, if requested.
518 if (!NoInitialTextSection)
525 AsmCond StartingCondState = TheCondState;
527 // If we are generating dwarf for assembly source files save the initial text
528 // section and generate a .file directive.
529 if (getContext().getGenDwarfForAssembly()) {
530 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
531 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
532 getStreamer().EmitLabel(SectionStartSym);
533 getContext().setGenDwarfSectionStartSym(SectionStartSym);
534 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
535 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
538 // While we have input, parse each statement.
539 while (Lexer.isNot(AsmToken::Eof)) {
540 if (!ParseStatement()) continue;
542 // We had an error, validate that one was emitted and recover by skipping to
544 assert(HadError && "Parse statement returned an error, but none emitted!");
545 EatToEndOfStatement();
548 if (TheCondState.TheCond != StartingCondState.TheCond ||
549 TheCondState.Ignore != StartingCondState.Ignore)
550 return TokError("unmatched .ifs or .elses");
552 // Check to see there are no empty DwarfFile slots.
553 const std::vector<MCDwarfFile *> &MCDwarfFiles =
554 getContext().getMCDwarfFiles();
555 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
556 if (!MCDwarfFiles[i])
557 TokError("unassigned file number: " + Twine(i) + " for .file directives");
560 // Check to see that all assembler local symbols were actually defined.
561 // Targets that don't do subsections via symbols may not want this, though,
562 // so conservatively exclude them. Only do this if we're finalizing, though,
563 // as otherwise we won't necessarilly have seen everything yet.
564 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
565 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
566 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
569 MCSymbol *Sym = i->getValue();
570 // Variable symbols may not be marked as defined, so check those
571 // explicitly. If we know it's a variable, we have a definition for
572 // the purposes of this check.
573 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
574 // FIXME: We would really like to refer back to where the symbol was
575 // first referenced for a source location. We need to add something
576 // to track that. Currently, we just point to the end of the file.
577 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
578 "assembler local symbol '" + Sym->getName() +
584 // Finalize the output stream if there are no errors and if the client wants
586 if (!HadError && !NoFinalize)
592 void AsmParser::CheckForValidSection() {
593 if (!getStreamer().getCurrentSection()) {
594 TokError("expected section directive before assembly directive");
595 Out.SwitchSection(Ctx.getMachOSection(
597 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
598 0, SectionKind::getText()));
602 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
603 void AsmParser::EatToEndOfStatement() {
604 while (Lexer.isNot(AsmToken::EndOfStatement) &&
605 Lexer.isNot(AsmToken::Eof))
609 if (Lexer.is(AsmToken::EndOfStatement))
613 StringRef AsmParser::ParseStringToEndOfStatement() {
614 const char *Start = getTok().getLoc().getPointer();
616 while (Lexer.isNot(AsmToken::EndOfStatement) &&
617 Lexer.isNot(AsmToken::Eof))
620 const char *End = getTok().getLoc().getPointer();
621 return StringRef(Start, End - Start);
624 StringRef AsmParser::ParseStringToComma() {
625 const char *Start = getTok().getLoc().getPointer();
627 while (Lexer.isNot(AsmToken::EndOfStatement) &&
628 Lexer.isNot(AsmToken::Comma) &&
629 Lexer.isNot(AsmToken::Eof))
632 const char *End = getTok().getLoc().getPointer();
633 return StringRef(Start, End - Start);
636 /// ParseParenExpr - Parse a paren expression and return it.
637 /// NOTE: This assumes the leading '(' has already been consumed.
639 /// parenexpr ::= expr)
641 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
642 if (ParseExpression(Res)) return true;
643 if (Lexer.isNot(AsmToken::RParen))
644 return TokError("expected ')' in parentheses expression");
645 EndLoc = Lexer.getLoc();
650 /// ParseBracketExpr - Parse a bracket expression and return it.
651 /// NOTE: This assumes the leading '[' has already been consumed.
653 /// bracketexpr ::= expr]
655 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
656 if (ParseExpression(Res)) return true;
657 if (Lexer.isNot(AsmToken::RBrac))
658 return TokError("expected ']' in brackets expression");
659 EndLoc = Lexer.getLoc();
664 /// ParsePrimaryExpr - Parse a primary expression and return it.
665 /// primaryexpr ::= (parenexpr
666 /// primaryexpr ::= symbol
667 /// primaryexpr ::= number
668 /// primaryexpr ::= '.'
669 /// primaryexpr ::= ~,+,- primaryexpr
670 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
671 switch (Lexer.getKind()) {
673 return TokError("unknown token in expression");
674 // If we have an error assume that we've already handled it.
675 case AsmToken::Error:
677 case AsmToken::Exclaim:
678 Lex(); // Eat the operator.
679 if (ParsePrimaryExpr(Res, EndLoc))
681 Res = MCUnaryExpr::CreateLNot(Res, getContext());
683 case AsmToken::Dollar:
684 case AsmToken::String:
685 case AsmToken::Identifier: {
686 EndLoc = Lexer.getLoc();
688 StringRef Identifier;
689 if (ParseIdentifier(Identifier))
692 // This is a symbol reference.
693 std::pair<StringRef, StringRef> Split = Identifier.split('@');
694 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
696 // Lookup the symbol variant if used.
697 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
698 if (Split.first.size() != Identifier.size()) {
699 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
700 if (Variant == MCSymbolRefExpr::VK_Invalid) {
701 Variant = MCSymbolRefExpr::VK_None;
702 return TokError("invalid variant '" + Split.second + "'");
706 // If this is an absolute variable reference, substitute it now to preserve
707 // semantics in the face of reassignment.
708 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
710 return Error(EndLoc, "unexpected modifier on variable reference");
712 Res = Sym->getVariableValue();
716 // Otherwise create a symbol ref.
717 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
720 case AsmToken::Integer: {
721 SMLoc Loc = getTok().getLoc();
722 int64_t IntVal = getTok().getIntVal();
723 Res = MCConstantExpr::Create(IntVal, getContext());
724 EndLoc = Lexer.getLoc();
726 // Look for 'b' or 'f' following an Integer as a directional label
727 if (Lexer.getKind() == AsmToken::Identifier) {
728 StringRef IDVal = getTok().getString();
729 if (IDVal == "f" || IDVal == "b"){
730 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
731 IDVal == "f" ? 1 : 0);
732 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
734 if (IDVal == "b" && Sym->isUndefined())
735 return Error(Loc, "invalid reference to undefined symbol");
736 EndLoc = Lexer.getLoc();
737 Lex(); // Eat identifier.
742 case AsmToken::Real: {
743 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
744 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
745 Res = MCConstantExpr::Create(IntVal, getContext());
749 case AsmToken::Dot: {
750 // This is a '.' reference, which references the current PC. Emit a
751 // temporary label to the streamer and refer to it.
752 MCSymbol *Sym = Ctx.CreateTempSymbol();
754 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
755 EndLoc = Lexer.getLoc();
756 Lex(); // Eat identifier.
759 case AsmToken::LParen:
760 Lex(); // Eat the '('.
761 return ParseParenExpr(Res, EndLoc);
762 case AsmToken::LBrac:
763 if (!PlatformParser->HasBracketExpressions())
764 return TokError("brackets expression not supported on this target");
765 Lex(); // Eat the '['.
766 return ParseBracketExpr(Res, EndLoc);
767 case AsmToken::Minus:
768 Lex(); // Eat the operator.
769 if (ParsePrimaryExpr(Res, EndLoc))
771 Res = MCUnaryExpr::CreateMinus(Res, getContext());
774 Lex(); // Eat the operator.
775 if (ParsePrimaryExpr(Res, EndLoc))
777 Res = MCUnaryExpr::CreatePlus(Res, getContext());
779 case AsmToken::Tilde:
780 Lex(); // Eat the operator.
781 if (ParsePrimaryExpr(Res, EndLoc))
783 Res = MCUnaryExpr::CreateNot(Res, getContext());
788 bool AsmParser::ParseExpression(const MCExpr *&Res) {
790 return ParseExpression(Res, EndLoc);
794 AsmParser::ApplyModifierToExpr(const MCExpr *E,
795 MCSymbolRefExpr::VariantKind Variant) {
796 // Recurse over the given expression, rebuilding it to apply the given variant
797 // if there is exactly one symbol.
798 switch (E->getKind()) {
800 case MCExpr::Constant:
803 case MCExpr::SymbolRef: {
804 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
806 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
807 TokError("invalid variant on expression '" +
808 getTok().getIdentifier() + "' (already modified)");
812 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
815 case MCExpr::Unary: {
816 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
817 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
820 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
823 case MCExpr::Binary: {
824 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
825 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
826 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
831 if (!LHS) LHS = BE->getLHS();
832 if (!RHS) RHS = BE->getRHS();
834 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
838 llvm_unreachable("Invalid expression kind!");
841 /// ParseExpression - Parse an expression and return it.
843 /// expr ::= expr &&,|| expr -> lowest.
844 /// expr ::= expr |,^,&,! expr
845 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
846 /// expr ::= expr <<,>> expr
847 /// expr ::= expr +,- expr
848 /// expr ::= expr *,/,% expr -> highest.
849 /// expr ::= primaryexpr
851 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
852 // Parse the expression.
854 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
857 // As a special case, we support 'a op b @ modifier' by rewriting the
858 // expression to include the modifier. This is inefficient, but in general we
859 // expect users to use 'a@modifier op b'.
860 if (Lexer.getKind() == AsmToken::At) {
863 if (Lexer.isNot(AsmToken::Identifier))
864 return TokError("unexpected symbol modifier following '@'");
866 MCSymbolRefExpr::VariantKind Variant =
867 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
868 if (Variant == MCSymbolRefExpr::VK_Invalid)
869 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
871 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
873 return TokError("invalid modifier '" + getTok().getIdentifier() +
874 "' (no symbols present)");
881 // Try to constant fold it up front, if possible.
883 if (Res->EvaluateAsAbsolute(Value))
884 Res = MCConstantExpr::Create(Value, getContext());
889 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
891 return ParseParenExpr(Res, EndLoc) ||
892 ParseBinOpRHS(1, Res, EndLoc);
895 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
898 SMLoc StartLoc = Lexer.getLoc();
899 if (ParseExpression(Expr))
902 if (!Expr->EvaluateAsAbsolute(Res))
903 return Error(StartLoc, "expected absolute expression");
908 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
909 MCBinaryExpr::Opcode &Kind) {
912 return 0; // not a binop.
914 // Lowest Precedence: &&, ||
915 case AsmToken::AmpAmp:
916 Kind = MCBinaryExpr::LAnd;
918 case AsmToken::PipePipe:
919 Kind = MCBinaryExpr::LOr;
923 // Low Precedence: |, &, ^
925 // FIXME: gas seems to support '!' as an infix operator?
927 Kind = MCBinaryExpr::Or;
929 case AsmToken::Caret:
930 Kind = MCBinaryExpr::Xor;
933 Kind = MCBinaryExpr::And;
936 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
937 case AsmToken::EqualEqual:
938 Kind = MCBinaryExpr::EQ;
940 case AsmToken::ExclaimEqual:
941 case AsmToken::LessGreater:
942 Kind = MCBinaryExpr::NE;
945 Kind = MCBinaryExpr::LT;
947 case AsmToken::LessEqual:
948 Kind = MCBinaryExpr::LTE;
950 case AsmToken::Greater:
951 Kind = MCBinaryExpr::GT;
953 case AsmToken::GreaterEqual:
954 Kind = MCBinaryExpr::GTE;
957 // Intermediate Precedence: <<, >>
958 case AsmToken::LessLess:
959 Kind = MCBinaryExpr::Shl;
961 case AsmToken::GreaterGreater:
962 Kind = MCBinaryExpr::Shr;
965 // High Intermediate Precedence: +, -
967 Kind = MCBinaryExpr::Add;
969 case AsmToken::Minus:
970 Kind = MCBinaryExpr::Sub;
973 // Highest Precedence: *, /, %
975 Kind = MCBinaryExpr::Mul;
977 case AsmToken::Slash:
978 Kind = MCBinaryExpr::Div;
980 case AsmToken::Percent:
981 Kind = MCBinaryExpr::Mod;
987 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
988 /// Res contains the LHS of the expression on input.
989 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
992 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
993 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
995 // If the next token is lower precedence than we are allowed to eat, return
996 // successfully with what we ate already.
997 if (TokPrec < Precedence)
1002 // Eat the next primary expression.
1004 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1006 // If BinOp binds less tightly with RHS than the operator after RHS, let
1007 // the pending operator take RHS as its LHS.
1008 MCBinaryExpr::Opcode Dummy;
1009 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1010 if (TokPrec < NextTokPrec) {
1011 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1014 // Merge LHS and RHS according to operator.
1015 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1023 /// ::= EndOfStatement
1024 /// ::= Label* Directive ...Operands... EndOfStatement
1025 /// ::= Label* Identifier OperandList* EndOfStatement
1026 bool AsmParser::ParseStatement() {
1027 if (Lexer.is(AsmToken::EndOfStatement)) {
1033 // Statements always start with an identifier or are a full line comment.
1034 AsmToken ID = getTok();
1035 SMLoc IDLoc = ID.getLoc();
1037 int64_t LocalLabelVal = -1;
1038 // A full line comment is a '#' as the first token.
1039 if (Lexer.is(AsmToken::Hash))
1040 return ParseCppHashLineFilenameComment(IDLoc);
1042 // Allow an integer followed by a ':' as a directional local label.
1043 if (Lexer.is(AsmToken::Integer)) {
1044 LocalLabelVal = getTok().getIntVal();
1045 if (LocalLabelVal < 0) {
1046 if (!TheCondState.Ignore)
1047 return TokError("unexpected token at start of statement");
1051 IDVal = getTok().getString();
1052 Lex(); // Consume the integer token to be used as an identifier token.
1053 if (Lexer.getKind() != AsmToken::Colon) {
1054 if (!TheCondState.Ignore)
1055 return TokError("unexpected token at start of statement");
1059 } else if (Lexer.is(AsmToken::Dot)) {
1060 // Treat '.' as a valid identifier in this context.
1064 } else if (ParseIdentifier(IDVal)) {
1065 if (!TheCondState.Ignore)
1066 return TokError("unexpected token at start of statement");
1071 // Handle conditional assembly here before checking for skipping. We
1072 // have to do this so that .endif isn't skipped in a ".if 0" block for
1075 return ParseDirectiveIf(IDLoc);
1076 if (IDVal == ".ifb")
1077 return ParseDirectiveIfb(IDLoc, true);
1078 if (IDVal == ".ifnb")
1079 return ParseDirectiveIfb(IDLoc, false);
1080 if (IDVal == ".ifc")
1081 return ParseDirectiveIfc(IDLoc, true);
1082 if (IDVal == ".ifnc")
1083 return ParseDirectiveIfc(IDLoc, false);
1084 if (IDVal == ".ifdef")
1085 return ParseDirectiveIfdef(IDLoc, true);
1086 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1087 return ParseDirectiveIfdef(IDLoc, false);
1088 if (IDVal == ".elseif")
1089 return ParseDirectiveElseIf(IDLoc);
1090 if (IDVal == ".else")
1091 return ParseDirectiveElse(IDLoc);
1092 if (IDVal == ".endif")
1093 return ParseDirectiveEndIf(IDLoc);
1095 // If we are in a ".if 0" block, ignore this statement.
1096 if (TheCondState.Ignore) {
1097 EatToEndOfStatement();
1101 // FIXME: Recurse on local labels?
1103 // See what kind of statement we have.
1104 switch (Lexer.getKind()) {
1105 case AsmToken::Colon: {
1106 CheckForValidSection();
1108 // identifier ':' -> Label.
1111 // Diagnose attempt to use '.' as a label.
1113 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1115 // Diagnose attempt to use a variable as a label.
1117 // FIXME: Diagnostics. Note the location of the definition as a label.
1118 // FIXME: This doesn't diagnose assignment to a symbol which has been
1119 // implicitly marked as external.
1121 if (LocalLabelVal == -1)
1122 Sym = getContext().GetOrCreateSymbol(IDVal);
1124 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1125 if (!Sym->isUndefined() || Sym->isVariable())
1126 return Error(IDLoc, "invalid symbol redefinition");
1131 // If we are generating dwarf for assembly source files then gather the
1132 // info to make a dwarf label entry for this label if needed.
1133 if (getContext().getGenDwarfForAssembly())
1134 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1137 // Consume any end of statement token, if present, to avoid spurious
1138 // AddBlankLine calls().
1139 if (Lexer.is(AsmToken::EndOfStatement)) {
1141 if (Lexer.is(AsmToken::Eof))
1145 return ParseStatement();
1148 case AsmToken::Equal:
1149 // identifier '=' ... -> assignment statement
1152 return ParseAssignment(IDVal, true);
1154 default: // Normal instruction or directive.
1158 // If macros are enabled, check to see if this is a macro instantiation.
1160 if (const Macro *M = MacroMap.lookup(IDVal))
1161 return HandleMacroEntry(IDVal, IDLoc, M);
1163 // Otherwise, we have a normal instruction or directive.
1164 if (IDVal[0] == '.' && IDVal != ".") {
1165 // Assembler features
1166 if (IDVal == ".set" || IDVal == ".equ")
1167 return ParseDirectiveSet(IDVal, true);
1168 if (IDVal == ".equiv")
1169 return ParseDirectiveSet(IDVal, false);
1173 if (IDVal == ".ascii")
1174 return ParseDirectiveAscii(IDVal, false);
1175 if (IDVal == ".asciz" || IDVal == ".string")
1176 return ParseDirectiveAscii(IDVal, true);
1178 if (IDVal == ".byte")
1179 return ParseDirectiveValue(1);
1180 if (IDVal == ".short")
1181 return ParseDirectiveValue(2);
1182 if (IDVal == ".value")
1183 return ParseDirectiveValue(2);
1184 if (IDVal == ".2byte")
1185 return ParseDirectiveValue(2);
1186 if (IDVal == ".long")
1187 return ParseDirectiveValue(4);
1188 if (IDVal == ".int")
1189 return ParseDirectiveValue(4);
1190 if (IDVal == ".4byte")
1191 return ParseDirectiveValue(4);
1192 if (IDVal == ".quad")
1193 return ParseDirectiveValue(8);
1194 if (IDVal == ".8byte")
1195 return ParseDirectiveValue(8);
1196 if (IDVal == ".single" || IDVal == ".float")
1197 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1198 if (IDVal == ".double")
1199 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1201 if (IDVal == ".align") {
1202 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1203 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1205 if (IDVal == ".align32") {
1206 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1207 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1209 if (IDVal == ".balign")
1210 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1211 if (IDVal == ".balignw")
1212 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1213 if (IDVal == ".balignl")
1214 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1215 if (IDVal == ".p2align")
1216 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1217 if (IDVal == ".p2alignw")
1218 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1219 if (IDVal == ".p2alignl")
1220 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1222 if (IDVal == ".org")
1223 return ParseDirectiveOrg();
1225 if (IDVal == ".fill")
1226 return ParseDirectiveFill();
1227 if (IDVal == ".space" || IDVal == ".skip")
1228 return ParseDirectiveSpace();
1229 if (IDVal == ".zero")
1230 return ParseDirectiveZero();
1232 // Symbol attribute directives
1234 if (IDVal == ".extern") {
1235 EatToEndOfStatement(); // .extern is the default, ignore it.
1238 if (IDVal == ".globl" || IDVal == ".global")
1239 return ParseDirectiveSymbolAttribute(MCSA_Global);
1240 if (IDVal == ".indirect_symbol")
1241 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1242 if (IDVal == ".lazy_reference")
1243 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1244 if (IDVal == ".no_dead_strip")
1245 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1246 if (IDVal == ".symbol_resolver")
1247 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1248 if (IDVal == ".private_extern")
1249 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1250 if (IDVal == ".reference")
1251 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1252 if (IDVal == ".weak_definition")
1253 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1254 if (IDVal == ".weak_reference")
1255 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1256 if (IDVal == ".weak_def_can_be_hidden")
1257 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1259 if (IDVal == ".comm" || IDVal == ".common")
1260 return ParseDirectiveComm(/*IsLocal=*/false);
1261 if (IDVal == ".lcomm")
1262 return ParseDirectiveComm(/*IsLocal=*/true);
1264 if (IDVal == ".abort")
1265 return ParseDirectiveAbort();
1266 if (IDVal == ".include")
1267 return ParseDirectiveInclude();
1268 if (IDVal == ".incbin")
1269 return ParseDirectiveIncbin();
1271 if (IDVal == ".code16" || IDVal == ".code16gcc")
1272 return TokError(Twine(IDVal) + " not supported yet");
1274 // Macro-like directives
1275 if (IDVal == ".rept")
1276 return ParseDirectiveRept(IDLoc);
1277 if (IDVal == ".endr")
1278 return ParseDirectiveEndr(IDLoc);
1280 // Look up the handler in the handler table.
1281 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1282 DirectiveMap.lookup(IDVal);
1284 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1286 // Target hook for parsing target specific directives.
1287 if (!getTargetParser().ParseDirective(ID))
1290 return Error(IDLoc, "unknown directive");
1293 CheckForValidSection();
1295 // Canonicalize the opcode to lower case.
1296 SmallString<128> Opcode;
1297 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1298 Opcode.push_back(tolower(IDVal[i]));
1300 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1301 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1304 // Dump the parsed representation, if requested.
1305 if (getShowParsedOperands()) {
1306 SmallString<256> Str;
1307 raw_svector_ostream OS(Str);
1308 OS << "parsed instruction: [";
1309 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1312 ParsedOperands[i]->print(OS);
1316 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1319 // If we are generating dwarf for assembly source files and the current
1320 // section is the initial text section then generate a .loc directive for
1322 if (!HadError && getContext().getGenDwarfForAssembly() &&
1323 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1324 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1325 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1326 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1327 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1331 // If parsing succeeded, match the instruction.
1333 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1336 // Free any parsed operands.
1337 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1338 delete ParsedOperands[i];
1340 // Don't skip the rest of the line, the instruction parser is responsible for
1345 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1346 /// since they may not be able to be tokenized to get to the end of line token.
1347 void AsmParser::EatToEndOfLine() {
1348 if (!Lexer.is(AsmToken::EndOfStatement))
1349 Lexer.LexUntilEndOfLine();
1354 /// ParseCppHashLineFilenameComment as this:
1355 /// ::= # number "filename"
1356 /// or just as a full line comment if it doesn't have a number and a string.
1357 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1358 Lex(); // Eat the hash token.
1360 if (getLexer().isNot(AsmToken::Integer)) {
1361 // Consume the line since in cases it is not a well-formed line directive,
1362 // as if were simply a full line comment.
1367 int64_t LineNumber = getTok().getIntVal();
1370 if (getLexer().isNot(AsmToken::String)) {
1375 StringRef Filename = getTok().getString();
1376 // Get rid of the enclosing quotes.
1377 Filename = Filename.substr(1, Filename.size()-2);
1379 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1381 CppHashFilename = Filename;
1382 CppHashLineNumber = LineNumber;
1384 // Ignore any trailing characters, they're just comment.
1389 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1390 /// for the Filename and LineNo if any in the diagnostic.
1391 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1392 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1393 raw_ostream &OS = errs();
1395 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1396 const SMLoc &DiagLoc = Diag.getLoc();
1397 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1398 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1400 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1401 // before printing the message.
1402 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1403 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1404 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1405 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1408 // If we have not parsed a cpp hash line filename comment or the source
1409 // manager changed or buffer changed (like in a nested include) then just
1410 // print the normal diagnostic using its Filename and LineNo.
1411 if (!Parser->CppHashLineNumber ||
1412 &DiagSrcMgr != &Parser->SrcMgr ||
1413 DiagBuf != CppHashBuf) {
1414 if (Parser->SavedDiagHandler)
1415 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1421 // Use the CppHashFilename and calculate a line number based on the
1422 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1424 const std::string Filename = Parser->CppHashFilename;
1426 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1427 int CppHashLocLineNo =
1428 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1429 int LineNo = Parser->CppHashLineNumber - 1 +
1430 (DiagLocLineNo - CppHashLocLineNo);
1432 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1433 Filename, LineNo, Diag.getColumnNo(),
1434 Diag.getKind(), Diag.getMessage(),
1435 Diag.getLineContents(), Diag.getRanges());
1437 if (Parser->SavedDiagHandler)
1438 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1440 NewDiag.print(0, OS);
1443 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1444 const std::vector<StringRef> &Parameters,
1445 const std::vector<MacroArgument> &A,
1447 unsigned NParameters = Parameters.size();
1448 if (NParameters != 0 && NParameters != A.size())
1449 return Error(L, "Wrong number of arguments");
1451 while (!Body.empty()) {
1452 // Scan for the next substitution.
1453 std::size_t End = Body.size(), Pos = 0;
1454 for (; Pos != End; ++Pos) {
1455 // Check for a substitution or escape.
1457 // This macro has no parameters, look for $0, $1, etc.
1458 if (Body[Pos] != '$' || Pos + 1 == End)
1461 char Next = Body[Pos + 1];
1462 if (Next == '$' || Next == 'n' || isdigit(Next))
1465 // This macro has parameters, look for \foo, \bar, etc.
1466 if (Body[Pos] == '\\' && Pos + 1 != End)
1472 OS << Body.slice(0, Pos);
1474 // Check if we reached the end.
1479 switch (Body[Pos+1]) {
1485 // $n => number of arguments
1490 // $[0-9] => argument
1492 // Missing arguments are ignored.
1493 unsigned Index = Body[Pos+1] - '0';
1494 if (Index >= A.size())
1497 // Otherwise substitute with the token values, with spaces eliminated.
1498 for (MacroArgument::const_iterator it = A[Index].begin(),
1499 ie = A[Index].end(); it != ie; ++it)
1500 OS << it->getString();
1506 unsigned I = Pos + 1;
1507 while (isalnum(Body[I]) && I + 1 != End)
1510 const char *Begin = Body.data() + Pos +1;
1511 StringRef Argument(Begin, I - (Pos +1));
1513 for (; Index < NParameters; ++Index)
1514 if (Parameters[Index] == Argument)
1517 // FIXME: We should error at the macro definition.
1518 if (Index == NParameters)
1519 return Error(L, "Parameter not found");
1521 for (MacroArgument::const_iterator it = A[Index].begin(),
1522 ie = A[Index].end(); it != ie; ++it)
1523 OS << it->getString();
1525 Pos += 1 + Argument.size();
1527 // Update the scan point.
1528 Body = Body.substr(Pos);
1534 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1536 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1540 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1542 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1543 // this, although we should protect against infinite loops.
1544 if (ActiveMacros.size() == 20)
1545 return TokError("macros cannot be nested more than 20 levels deep");
1547 // Parse the macro instantiation arguments.
1548 std::vector<MacroArgument> MacroArguments;
1549 MacroArguments.push_back(MacroArgument());
1550 unsigned ParenLevel = 0;
1552 if (Lexer.is(AsmToken::Eof))
1553 return TokError("unexpected token in macro instantiation");
1554 if (Lexer.is(AsmToken::EndOfStatement))
1557 // If we aren't inside parentheses and this is a comma, start a new token
1559 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1560 MacroArguments.push_back(MacroArgument());
1562 // Adjust the current parentheses level.
1563 if (Lexer.is(AsmToken::LParen))
1565 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1568 // Append the token to the current argument list.
1569 MacroArguments.back().push_back(getTok());
1573 // If the last argument didn't end up with any tokens, it's not a real
1574 // argument and we should remove it from the list. This happens with either
1575 // a tailing comma or an empty argument list.
1576 if (MacroArguments.back().empty())
1577 MacroArguments.pop_back();
1579 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1580 // to hold the macro body with substitutions.
1581 SmallString<256> Buf;
1582 StringRef Body = M->Body;
1583 raw_svector_ostream OS(Buf);
1585 if (expandMacro(OS, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1588 // We include the .endmacro in the buffer as our queue to exit the macro
1590 OS << ".endmacro\n";
1592 MemoryBuffer *Instantiation =
1593 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1595 // Create the macro instantiation object and add to the current macro
1596 // instantiation stack.
1597 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1600 ActiveMacros.push_back(MI);
1602 // Jump to the macro instantiation and prime the lexer.
1603 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1604 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1610 void AsmParser::HandleMacroExit() {
1611 // Jump to the EndOfStatement we should return to, and consume it.
1612 JumpToLoc(ActiveMacros.back()->ExitLoc);
1615 // Pop the instantiation entry.
1616 delete ActiveMacros.back();
1617 ActiveMacros.pop_back();
1620 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1621 switch (Value->getKind()) {
1622 case MCExpr::Binary: {
1623 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1624 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1627 case MCExpr::Target:
1628 case MCExpr::Constant:
1630 case MCExpr::SymbolRef: {
1631 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1633 return IsUsedIn(Sym, S.getVariableValue());
1637 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1640 llvm_unreachable("Unknown expr kind!");
1643 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1644 // FIXME: Use better location, we should use proper tokens.
1645 SMLoc EqualLoc = Lexer.getLoc();
1647 const MCExpr *Value;
1648 if (ParseExpression(Value))
1651 // Note: we don't count b as used in "a = b". This is to allow
1655 if (Lexer.isNot(AsmToken::EndOfStatement))
1656 return TokError("unexpected token in assignment");
1658 // Error on assignment to '.'.
1660 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1661 "(use '.space' or '.org').)"));
1664 // Eat the end of statement marker.
1667 // Validate that the LHS is allowed to be a variable (either it has not been
1668 // used as a symbol, or it is an absolute symbol).
1669 MCSymbol *Sym = getContext().LookupSymbol(Name);
1671 // Diagnose assignment to a label.
1673 // FIXME: Diagnostics. Note the location of the definition as a label.
1674 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1675 if (IsUsedIn(Sym, Value))
1676 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1677 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1678 ; // Allow redefinitions of undefined symbols only used in directives.
1679 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1680 ; // Allow redefinitions of variables that haven't yet been used.
1681 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1682 return Error(EqualLoc, "redefinition of '" + Name + "'");
1683 else if (!Sym->isVariable())
1684 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1685 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1686 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1689 // Don't count these checks as uses.
1690 Sym->setUsed(false);
1692 Sym = getContext().GetOrCreateSymbol(Name);
1694 // FIXME: Handle '.'.
1696 // Do the assignment.
1697 Out.EmitAssignment(Sym, Value);
1702 /// ParseIdentifier:
1705 bool AsmParser::ParseIdentifier(StringRef &Res) {
1706 // The assembler has relaxed rules for accepting identifiers, in particular we
1707 // allow things like '.globl $foo', which would normally be separate
1708 // tokens. At this level, we have already lexed so we cannot (currently)
1709 // handle this as a context dependent token, instead we detect adjacent tokens
1710 // and return the combined identifier.
1711 if (Lexer.is(AsmToken::Dollar)) {
1712 SMLoc DollarLoc = getLexer().getLoc();
1714 // Consume the dollar sign, and check for a following identifier.
1716 if (Lexer.isNot(AsmToken::Identifier))
1719 // We have a '$' followed by an identifier, make sure they are adjacent.
1720 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1723 // Construct the joined identifier and consume the token.
1724 Res = StringRef(DollarLoc.getPointer(),
1725 getTok().getIdentifier().size() + 1);
1730 if (Lexer.isNot(AsmToken::Identifier) &&
1731 Lexer.isNot(AsmToken::String))
1734 Res = getTok().getIdentifier();
1736 Lex(); // Consume the identifier token.
1741 /// ParseDirectiveSet:
1742 /// ::= .equ identifier ',' expression
1743 /// ::= .equiv identifier ',' expression
1744 /// ::= .set identifier ',' expression
1745 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1748 if (ParseIdentifier(Name))
1749 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1751 if (getLexer().isNot(AsmToken::Comma))
1752 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1755 return ParseAssignment(Name, allow_redef);
1758 bool AsmParser::ParseEscapedString(std::string &Data) {
1759 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1762 StringRef Str = getTok().getStringContents();
1763 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1764 if (Str[i] != '\\') {
1769 // Recognize escaped characters. Note that this escape semantics currently
1770 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1773 return TokError("unexpected backslash at end of string");
1775 // Recognize octal sequences.
1776 if ((unsigned) (Str[i] - '0') <= 7) {
1777 // Consume up to three octal characters.
1778 unsigned Value = Str[i] - '0';
1780 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1782 Value = Value * 8 + (Str[i] - '0');
1784 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1786 Value = Value * 8 + (Str[i] - '0');
1791 return TokError("invalid octal escape sequence (out of range)");
1793 Data += (unsigned char) Value;
1797 // Otherwise recognize individual escapes.
1800 // Just reject invalid escape sequences for now.
1801 return TokError("invalid escape sequence (unrecognized character)");
1803 case 'b': Data += '\b'; break;
1804 case 'f': Data += '\f'; break;
1805 case 'n': Data += '\n'; break;
1806 case 'r': Data += '\r'; break;
1807 case 't': Data += '\t'; break;
1808 case '"': Data += '"'; break;
1809 case '\\': Data += '\\'; break;
1816 /// ParseDirectiveAscii:
1817 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1818 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1819 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1820 CheckForValidSection();
1823 if (getLexer().isNot(AsmToken::String))
1824 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1827 if (ParseEscapedString(Data))
1830 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1832 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1836 if (getLexer().is(AsmToken::EndOfStatement))
1839 if (getLexer().isNot(AsmToken::Comma))
1840 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1849 /// ParseDirectiveValue
1850 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1851 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1852 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1853 CheckForValidSection();
1856 const MCExpr *Value;
1857 SMLoc ExprLoc = getLexer().getLoc();
1858 if (ParseExpression(Value))
1861 // Special case constant expressions to match code generator.
1862 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1863 assert(Size <= 8 && "Invalid size");
1864 uint64_t IntValue = MCE->getValue();
1865 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1866 return Error(ExprLoc, "literal value out of range for directive");
1867 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1869 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1871 if (getLexer().is(AsmToken::EndOfStatement))
1874 // FIXME: Improve diagnostic.
1875 if (getLexer().isNot(AsmToken::Comma))
1876 return TokError("unexpected token in directive");
1885 /// ParseDirectiveRealValue
1886 /// ::= (.single | .double) [ expression (, expression)* ]
1887 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1888 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1889 CheckForValidSection();
1892 // We don't truly support arithmetic on floating point expressions, so we
1893 // have to manually parse unary prefixes.
1895 if (getLexer().is(AsmToken::Minus)) {
1898 } else if (getLexer().is(AsmToken::Plus))
1901 if (getLexer().isNot(AsmToken::Integer) &&
1902 getLexer().isNot(AsmToken::Real) &&
1903 getLexer().isNot(AsmToken::Identifier))
1904 return TokError("unexpected token in directive");
1906 // Convert to an APFloat.
1907 APFloat Value(Semantics);
1908 StringRef IDVal = getTok().getString();
1909 if (getLexer().is(AsmToken::Identifier)) {
1910 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1911 Value = APFloat::getInf(Semantics);
1912 else if (!IDVal.compare_lower("nan"))
1913 Value = APFloat::getNaN(Semantics, false, ~0);
1915 return TokError("invalid floating point literal");
1916 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1917 APFloat::opInvalidOp)
1918 return TokError("invalid floating point literal");
1922 // Consume the numeric token.
1925 // Emit the value as an integer.
1926 APInt AsInt = Value.bitcastToAPInt();
1927 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1928 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1930 if (getLexer().is(AsmToken::EndOfStatement))
1933 if (getLexer().isNot(AsmToken::Comma))
1934 return TokError("unexpected token in directive");
1943 /// ParseDirectiveSpace
1944 /// ::= .space expression [ , expression ]
1945 bool AsmParser::ParseDirectiveSpace() {
1946 CheckForValidSection();
1949 if (ParseAbsoluteExpression(NumBytes))
1952 int64_t FillExpr = 0;
1953 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1954 if (getLexer().isNot(AsmToken::Comma))
1955 return TokError("unexpected token in '.space' directive");
1958 if (ParseAbsoluteExpression(FillExpr))
1961 if (getLexer().isNot(AsmToken::EndOfStatement))
1962 return TokError("unexpected token in '.space' directive");
1968 return TokError("invalid number of bytes in '.space' directive");
1970 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1971 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1976 /// ParseDirectiveZero
1977 /// ::= .zero expression
1978 bool AsmParser::ParseDirectiveZero() {
1979 CheckForValidSection();
1982 if (ParseAbsoluteExpression(NumBytes))
1986 if (getLexer().is(AsmToken::Comma)) {
1988 if (ParseAbsoluteExpression(Val))
1992 if (getLexer().isNot(AsmToken::EndOfStatement))
1993 return TokError("unexpected token in '.zero' directive");
1997 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2002 /// ParseDirectiveFill
2003 /// ::= .fill expression , expression , expression
2004 bool AsmParser::ParseDirectiveFill() {
2005 CheckForValidSection();
2008 if (ParseAbsoluteExpression(NumValues))
2011 if (getLexer().isNot(AsmToken::Comma))
2012 return TokError("unexpected token in '.fill' directive");
2016 if (ParseAbsoluteExpression(FillSize))
2019 if (getLexer().isNot(AsmToken::Comma))
2020 return TokError("unexpected token in '.fill' directive");
2024 if (ParseAbsoluteExpression(FillExpr))
2027 if (getLexer().isNot(AsmToken::EndOfStatement))
2028 return TokError("unexpected token in '.fill' directive");
2032 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2033 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2035 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2036 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2041 /// ParseDirectiveOrg
2042 /// ::= .org expression [ , expression ]
2043 bool AsmParser::ParseDirectiveOrg() {
2044 CheckForValidSection();
2046 const MCExpr *Offset;
2047 SMLoc Loc = getTok().getLoc();
2048 if (ParseExpression(Offset))
2051 // Parse optional fill expression.
2052 int64_t FillExpr = 0;
2053 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2054 if (getLexer().isNot(AsmToken::Comma))
2055 return TokError("unexpected token in '.org' directive");
2058 if (ParseAbsoluteExpression(FillExpr))
2061 if (getLexer().isNot(AsmToken::EndOfStatement))
2062 return TokError("unexpected token in '.org' directive");
2067 // Only limited forms of relocatable expressions are accepted here, it
2068 // has to be relative to the current section. The streamer will return
2069 // 'true' if the expression wasn't evaluatable.
2070 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2071 return Error(Loc, "expected assembly-time absolute expression");
2076 /// ParseDirectiveAlign
2077 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2078 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2079 CheckForValidSection();
2081 SMLoc AlignmentLoc = getLexer().getLoc();
2083 if (ParseAbsoluteExpression(Alignment))
2087 bool HasFillExpr = false;
2088 int64_t FillExpr = 0;
2089 int64_t MaxBytesToFill = 0;
2090 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2091 if (getLexer().isNot(AsmToken::Comma))
2092 return TokError("unexpected token in directive");
2095 // The fill expression can be omitted while specifying a maximum number of
2096 // alignment bytes, e.g:
2098 if (getLexer().isNot(AsmToken::Comma)) {
2100 if (ParseAbsoluteExpression(FillExpr))
2104 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2105 if (getLexer().isNot(AsmToken::Comma))
2106 return TokError("unexpected token in directive");
2109 MaxBytesLoc = getLexer().getLoc();
2110 if (ParseAbsoluteExpression(MaxBytesToFill))
2113 if (getLexer().isNot(AsmToken::EndOfStatement))
2114 return TokError("unexpected token in directive");
2123 // Compute alignment in bytes.
2125 // FIXME: Diagnose overflow.
2126 if (Alignment >= 32) {
2127 Error(AlignmentLoc, "invalid alignment value");
2131 Alignment = 1ULL << Alignment;
2134 // Diagnose non-sensical max bytes to align.
2135 if (MaxBytesLoc.isValid()) {
2136 if (MaxBytesToFill < 1) {
2137 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2138 "many bytes, ignoring maximum bytes expression");
2142 if (MaxBytesToFill >= Alignment) {
2143 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2149 // Check whether we should use optimal code alignment for this .align
2151 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2152 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2153 ValueSize == 1 && UseCodeAlign) {
2154 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2156 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2157 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2164 /// ParseDirectiveSymbolAttribute
2165 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2166 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2167 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2170 SMLoc Loc = getTok().getLoc();
2172 if (ParseIdentifier(Name))
2173 return Error(Loc, "expected identifier in directive");
2175 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2177 // Assembler local symbols don't make any sense here. Complain loudly.
2178 if (Sym->isTemporary())
2179 return Error(Loc, "non-local symbol required in directive");
2181 getStreamer().EmitSymbolAttribute(Sym, Attr);
2183 if (getLexer().is(AsmToken::EndOfStatement))
2186 if (getLexer().isNot(AsmToken::Comma))
2187 return TokError("unexpected token in directive");
2196 /// ParseDirectiveComm
2197 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2198 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2199 CheckForValidSection();
2201 SMLoc IDLoc = getLexer().getLoc();
2203 if (ParseIdentifier(Name))
2204 return TokError("expected identifier in directive");
2206 // Handle the identifier as the key symbol.
2207 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2209 if (getLexer().isNot(AsmToken::Comma))
2210 return TokError("unexpected token in directive");
2214 SMLoc SizeLoc = getLexer().getLoc();
2215 if (ParseAbsoluteExpression(Size))
2218 int64_t Pow2Alignment = 0;
2219 SMLoc Pow2AlignmentLoc;
2220 if (getLexer().is(AsmToken::Comma)) {
2222 Pow2AlignmentLoc = getLexer().getLoc();
2223 if (ParseAbsoluteExpression(Pow2Alignment))
2226 // If this target takes alignments in bytes (not log) validate and convert.
2227 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2228 if (!isPowerOf2_64(Pow2Alignment))
2229 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2230 Pow2Alignment = Log2_64(Pow2Alignment);
2234 if (getLexer().isNot(AsmToken::EndOfStatement))
2235 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2239 // NOTE: a size of zero for a .comm should create a undefined symbol
2240 // but a size of .lcomm creates a bss symbol of size zero.
2242 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2243 "be less than zero");
2245 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2246 // may internally end up wanting an alignment in bytes.
2247 // FIXME: Diagnose overflow.
2248 if (Pow2Alignment < 0)
2249 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2250 "alignment, can't be less than zero");
2252 if (!Sym->isUndefined())
2253 return Error(IDLoc, "invalid symbol redefinition");
2255 // '.lcomm' is equivalent to '.zerofill'.
2256 // Create the Symbol as a common or local common with Size and Pow2Alignment
2258 getStreamer().EmitZerofill(Ctx.getMachOSection(
2259 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2260 0, SectionKind::getBSS()),
2261 Sym, Size, 1 << Pow2Alignment);
2265 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2269 /// ParseDirectiveAbort
2270 /// ::= .abort [... message ...]
2271 bool AsmParser::ParseDirectiveAbort() {
2272 // FIXME: Use loc from directive.
2273 SMLoc Loc = getLexer().getLoc();
2275 StringRef Str = ParseStringToEndOfStatement();
2276 if (getLexer().isNot(AsmToken::EndOfStatement))
2277 return TokError("unexpected token in '.abort' directive");
2282 Error(Loc, ".abort detected. Assembly stopping.");
2284 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2285 // FIXME: Actually abort assembly here.
2290 /// ParseDirectiveInclude
2291 /// ::= .include "filename"
2292 bool AsmParser::ParseDirectiveInclude() {
2293 if (getLexer().isNot(AsmToken::String))
2294 return TokError("expected string in '.include' directive");
2296 std::string Filename = getTok().getString();
2297 SMLoc IncludeLoc = getLexer().getLoc();
2300 if (getLexer().isNot(AsmToken::EndOfStatement))
2301 return TokError("unexpected token in '.include' directive");
2303 // Strip the quotes.
2304 Filename = Filename.substr(1, Filename.size()-2);
2306 // Attempt to switch the lexer to the included file before consuming the end
2307 // of statement to avoid losing it when we switch.
2308 if (EnterIncludeFile(Filename)) {
2309 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2316 /// ParseDirectiveIncbin
2317 /// ::= .incbin "filename"
2318 bool AsmParser::ParseDirectiveIncbin() {
2319 if (getLexer().isNot(AsmToken::String))
2320 return TokError("expected string in '.incbin' directive");
2322 std::string Filename = getTok().getString();
2323 SMLoc IncbinLoc = getLexer().getLoc();
2326 if (getLexer().isNot(AsmToken::EndOfStatement))
2327 return TokError("unexpected token in '.incbin' directive");
2329 // Strip the quotes.
2330 Filename = Filename.substr(1, Filename.size()-2);
2332 // Attempt to process the included file.
2333 if (ProcessIncbinFile(Filename)) {
2334 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2341 /// ParseDirectiveIf
2342 /// ::= .if expression
2343 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2344 TheCondStack.push_back(TheCondState);
2345 TheCondState.TheCond = AsmCond::IfCond;
2346 if (TheCondState.Ignore) {
2347 EatToEndOfStatement();
2350 if (ParseAbsoluteExpression(ExprValue))
2353 if (getLexer().isNot(AsmToken::EndOfStatement))
2354 return TokError("unexpected token in '.if' directive");
2358 TheCondState.CondMet = ExprValue;
2359 TheCondState.Ignore = !TheCondState.CondMet;
2365 /// ParseDirectiveIfb
2367 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2368 TheCondStack.push_back(TheCondState);
2369 TheCondState.TheCond = AsmCond::IfCond;
2371 if (TheCondState.Ignore) {
2372 EatToEndOfStatement();
2374 StringRef Str = ParseStringToEndOfStatement();
2376 if (getLexer().isNot(AsmToken::EndOfStatement))
2377 return TokError("unexpected token in '.ifb' directive");
2381 TheCondState.CondMet = ExpectBlank == Str.empty();
2382 TheCondState.Ignore = !TheCondState.CondMet;
2388 /// ParseDirectiveIfc
2389 /// ::= .ifc string1, string2
2390 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2391 TheCondStack.push_back(TheCondState);
2392 TheCondState.TheCond = AsmCond::IfCond;
2394 if (TheCondState.Ignore) {
2395 EatToEndOfStatement();
2397 StringRef Str1 = ParseStringToComma();
2399 if (getLexer().isNot(AsmToken::Comma))
2400 return TokError("unexpected token in '.ifc' directive");
2404 StringRef Str2 = ParseStringToEndOfStatement();
2406 if (getLexer().isNot(AsmToken::EndOfStatement))
2407 return TokError("unexpected token in '.ifc' directive");
2411 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2412 TheCondState.Ignore = !TheCondState.CondMet;
2418 /// ParseDirectiveIfdef
2419 /// ::= .ifdef symbol
2420 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2422 TheCondStack.push_back(TheCondState);
2423 TheCondState.TheCond = AsmCond::IfCond;
2425 if (TheCondState.Ignore) {
2426 EatToEndOfStatement();
2428 if (ParseIdentifier(Name))
2429 return TokError("expected identifier after '.ifdef'");
2433 MCSymbol *Sym = getContext().LookupSymbol(Name);
2436 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2438 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2439 TheCondState.Ignore = !TheCondState.CondMet;
2445 /// ParseDirectiveElseIf
2446 /// ::= .elseif expression
2447 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2448 if (TheCondState.TheCond != AsmCond::IfCond &&
2449 TheCondState.TheCond != AsmCond::ElseIfCond)
2450 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2452 TheCondState.TheCond = AsmCond::ElseIfCond;
2454 bool LastIgnoreState = false;
2455 if (!TheCondStack.empty())
2456 LastIgnoreState = TheCondStack.back().Ignore;
2457 if (LastIgnoreState || TheCondState.CondMet) {
2458 TheCondState.Ignore = true;
2459 EatToEndOfStatement();
2463 if (ParseAbsoluteExpression(ExprValue))
2466 if (getLexer().isNot(AsmToken::EndOfStatement))
2467 return TokError("unexpected token in '.elseif' directive");
2470 TheCondState.CondMet = ExprValue;
2471 TheCondState.Ignore = !TheCondState.CondMet;
2477 /// ParseDirectiveElse
2479 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2480 if (getLexer().isNot(AsmToken::EndOfStatement))
2481 return TokError("unexpected token in '.else' directive");
2485 if (TheCondState.TheCond != AsmCond::IfCond &&
2486 TheCondState.TheCond != AsmCond::ElseIfCond)
2487 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2489 TheCondState.TheCond = AsmCond::ElseCond;
2490 bool LastIgnoreState = false;
2491 if (!TheCondStack.empty())
2492 LastIgnoreState = TheCondStack.back().Ignore;
2493 if (LastIgnoreState || TheCondState.CondMet)
2494 TheCondState.Ignore = true;
2496 TheCondState.Ignore = false;
2501 /// ParseDirectiveEndIf
2503 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2504 if (getLexer().isNot(AsmToken::EndOfStatement))
2505 return TokError("unexpected token in '.endif' directive");
2509 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2510 TheCondStack.empty())
2511 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2513 if (!TheCondStack.empty()) {
2514 TheCondState = TheCondStack.back();
2515 TheCondStack.pop_back();
2521 /// ParseDirectiveFile
2522 /// ::= .file [number] filename
2523 /// ::= .file number directory filename
2524 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2525 // FIXME: I'm not sure what this is.
2526 int64_t FileNumber = -1;
2527 SMLoc FileNumberLoc = getLexer().getLoc();
2528 if (getLexer().is(AsmToken::Integer)) {
2529 FileNumber = getTok().getIntVal();
2533 return TokError("file number less than one");
2536 if (getLexer().isNot(AsmToken::String))
2537 return TokError("unexpected token in '.file' directive");
2539 // Usually the directory and filename together, otherwise just the directory.
2540 StringRef Path = getTok().getString();
2541 Path = Path.substr(1, Path.size()-2);
2544 StringRef Directory;
2546 if (getLexer().is(AsmToken::String)) {
2547 if (FileNumber == -1)
2548 return TokError("explicit path specified, but no file number");
2549 Filename = getTok().getString();
2550 Filename = Filename.substr(1, Filename.size()-2);
2557 if (getLexer().isNot(AsmToken::EndOfStatement))
2558 return TokError("unexpected token in '.file' directive");
2560 if (FileNumber == -1)
2561 getStreamer().EmitFileDirective(Filename);
2563 if (getContext().getGenDwarfForAssembly() == true)
2564 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2565 "used to generate dwarf debug info for assembly code");
2567 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2568 Error(FileNumberLoc, "file number already allocated");
2574 /// ParseDirectiveLine
2575 /// ::= .line [number]
2576 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2577 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2578 if (getLexer().isNot(AsmToken::Integer))
2579 return TokError("unexpected token in '.line' directive");
2581 int64_t LineNumber = getTok().getIntVal();
2585 // FIXME: Do something with the .line.
2588 if (getLexer().isNot(AsmToken::EndOfStatement))
2589 return TokError("unexpected token in '.line' directive");
2595 /// ParseDirectiveLoc
2596 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2597 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2598 /// The first number is a file number, must have been previously assigned with
2599 /// a .file directive, the second number is the line number and optionally the
2600 /// third number is a column position (zero if not specified). The remaining
2601 /// optional items are .loc sub-directives.
2602 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2604 if (getLexer().isNot(AsmToken::Integer))
2605 return TokError("unexpected token in '.loc' directive");
2606 int64_t FileNumber = getTok().getIntVal();
2608 return TokError("file number less than one in '.loc' directive");
2609 if (!getContext().isValidDwarfFileNumber(FileNumber))
2610 return TokError("unassigned file number in '.loc' directive");
2613 int64_t LineNumber = 0;
2614 if (getLexer().is(AsmToken::Integer)) {
2615 LineNumber = getTok().getIntVal();
2617 return TokError("line number less than one in '.loc' directive");
2621 int64_t ColumnPos = 0;
2622 if (getLexer().is(AsmToken::Integer)) {
2623 ColumnPos = getTok().getIntVal();
2625 return TokError("column position less than zero in '.loc' directive");
2629 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2631 int64_t Discriminator = 0;
2632 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2634 if (getLexer().is(AsmToken::EndOfStatement))
2638 SMLoc Loc = getTok().getLoc();
2639 if (getParser().ParseIdentifier(Name))
2640 return TokError("unexpected token in '.loc' directive");
2642 if (Name == "basic_block")
2643 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2644 else if (Name == "prologue_end")
2645 Flags |= DWARF2_FLAG_PROLOGUE_END;
2646 else if (Name == "epilogue_begin")
2647 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2648 else if (Name == "is_stmt") {
2649 SMLoc Loc = getTok().getLoc();
2650 const MCExpr *Value;
2651 if (getParser().ParseExpression(Value))
2653 // The expression must be the constant 0 or 1.
2654 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2655 int Value = MCE->getValue();
2657 Flags &= ~DWARF2_FLAG_IS_STMT;
2658 else if (Value == 1)
2659 Flags |= DWARF2_FLAG_IS_STMT;
2661 return Error(Loc, "is_stmt value not 0 or 1");
2664 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2667 else if (Name == "isa") {
2668 SMLoc Loc = getTok().getLoc();
2669 const MCExpr *Value;
2670 if (getParser().ParseExpression(Value))
2672 // The expression must be a constant greater or equal to 0.
2673 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2674 int Value = MCE->getValue();
2676 return Error(Loc, "isa number less than zero");
2680 return Error(Loc, "isa number not a constant value");
2683 else if (Name == "discriminator") {
2684 if (getParser().ParseAbsoluteExpression(Discriminator))
2688 return Error(Loc, "unknown sub-directive in '.loc' directive");
2691 if (getLexer().is(AsmToken::EndOfStatement))
2696 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2697 Isa, Discriminator, StringRef());
2702 /// ParseDirectiveStabs
2703 /// ::= .stabs string, number, number, number
2704 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2705 SMLoc DirectiveLoc) {
2706 return TokError("unsupported directive '" + Directive + "'");
2709 /// ParseDirectiveCFISections
2710 /// ::= .cfi_sections section [, section]
2711 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2712 SMLoc DirectiveLoc) {
2717 if (getParser().ParseIdentifier(Name))
2718 return TokError("Expected an identifier");
2720 if (Name == ".eh_frame")
2722 else if (Name == ".debug_frame")
2725 if (getLexer().is(AsmToken::Comma)) {
2728 if (getParser().ParseIdentifier(Name))
2729 return TokError("Expected an identifier");
2731 if (Name == ".eh_frame")
2733 else if (Name == ".debug_frame")
2737 getStreamer().EmitCFISections(EH, Debug);
2742 /// ParseDirectiveCFIStartProc
2743 /// ::= .cfi_startproc
2744 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2745 SMLoc DirectiveLoc) {
2746 getStreamer().EmitCFIStartProc();
2750 /// ParseDirectiveCFIEndProc
2751 /// ::= .cfi_endproc
2752 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2753 getStreamer().EmitCFIEndProc();
2757 /// ParseRegisterOrRegisterNumber - parse register name or number.
2758 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2759 SMLoc DirectiveLoc) {
2762 if (getLexer().isNot(AsmToken::Integer)) {
2763 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2766 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2768 return getParser().ParseAbsoluteExpression(Register);
2773 /// ParseDirectiveCFIDefCfa
2774 /// ::= .cfi_def_cfa register, offset
2775 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2776 SMLoc DirectiveLoc) {
2777 int64_t Register = 0;
2778 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2781 if (getLexer().isNot(AsmToken::Comma))
2782 return TokError("unexpected token in directive");
2786 if (getParser().ParseAbsoluteExpression(Offset))
2789 getStreamer().EmitCFIDefCfa(Register, Offset);
2793 /// ParseDirectiveCFIDefCfaOffset
2794 /// ::= .cfi_def_cfa_offset offset
2795 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2796 SMLoc DirectiveLoc) {
2798 if (getParser().ParseAbsoluteExpression(Offset))
2801 getStreamer().EmitCFIDefCfaOffset(Offset);
2805 /// ParseDirectiveCFIAdjustCfaOffset
2806 /// ::= .cfi_adjust_cfa_offset adjustment
2807 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2808 SMLoc DirectiveLoc) {
2809 int64_t Adjustment = 0;
2810 if (getParser().ParseAbsoluteExpression(Adjustment))
2813 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2817 /// ParseDirectiveCFIDefCfaRegister
2818 /// ::= .cfi_def_cfa_register register
2819 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2820 SMLoc DirectiveLoc) {
2821 int64_t Register = 0;
2822 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2825 getStreamer().EmitCFIDefCfaRegister(Register);
2829 /// ParseDirectiveCFIOffset
2830 /// ::= .cfi_offset register, offset
2831 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2832 int64_t Register = 0;
2835 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2838 if (getLexer().isNot(AsmToken::Comma))
2839 return TokError("unexpected token in directive");
2842 if (getParser().ParseAbsoluteExpression(Offset))
2845 getStreamer().EmitCFIOffset(Register, Offset);
2849 /// ParseDirectiveCFIRelOffset
2850 /// ::= .cfi_rel_offset register, offset
2851 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2852 SMLoc DirectiveLoc) {
2853 int64_t Register = 0;
2855 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2858 if (getLexer().isNot(AsmToken::Comma))
2859 return TokError("unexpected token in directive");
2863 if (getParser().ParseAbsoluteExpression(Offset))
2866 getStreamer().EmitCFIRelOffset(Register, Offset);
2870 static bool isValidEncoding(int64_t Encoding) {
2871 if (Encoding & ~0xff)
2874 if (Encoding == dwarf::DW_EH_PE_omit)
2877 const unsigned Format = Encoding & 0xf;
2878 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2879 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2880 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2881 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2884 const unsigned Application = Encoding & 0x70;
2885 if (Application != dwarf::DW_EH_PE_absptr &&
2886 Application != dwarf::DW_EH_PE_pcrel)
2892 /// ParseDirectiveCFIPersonalityOrLsda
2893 /// ::= .cfi_personality encoding, [symbol_name]
2894 /// ::= .cfi_lsda encoding, [symbol_name]
2895 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2896 SMLoc DirectiveLoc) {
2897 int64_t Encoding = 0;
2898 if (getParser().ParseAbsoluteExpression(Encoding))
2900 if (Encoding == dwarf::DW_EH_PE_omit)
2903 if (!isValidEncoding(Encoding))
2904 return TokError("unsupported encoding.");
2906 if (getLexer().isNot(AsmToken::Comma))
2907 return TokError("unexpected token in directive");
2911 if (getParser().ParseIdentifier(Name))
2912 return TokError("expected identifier in directive");
2914 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2916 if (IDVal == ".cfi_personality")
2917 getStreamer().EmitCFIPersonality(Sym, Encoding);
2919 assert(IDVal == ".cfi_lsda");
2920 getStreamer().EmitCFILsda(Sym, Encoding);
2925 /// ParseDirectiveCFIRememberState
2926 /// ::= .cfi_remember_state
2927 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2928 SMLoc DirectiveLoc) {
2929 getStreamer().EmitCFIRememberState();
2933 /// ParseDirectiveCFIRestoreState
2934 /// ::= .cfi_remember_state
2935 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2936 SMLoc DirectiveLoc) {
2937 getStreamer().EmitCFIRestoreState();
2941 /// ParseDirectiveCFISameValue
2942 /// ::= .cfi_same_value register
2943 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2944 SMLoc DirectiveLoc) {
2945 int64_t Register = 0;
2947 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2950 getStreamer().EmitCFISameValue(Register);
2955 /// ParseDirectiveCFIRestore
2956 /// ::= .cfi_restore register
2957 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
2958 SMLoc DirectiveLoc) {
2959 int64_t Register = 0;
2960 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2963 getStreamer().EmitCFIRestore(Register);
2968 /// ParseDirectiveCFIEscape
2969 /// ::= .cfi_escape expression[,...]
2970 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
2971 SMLoc DirectiveLoc) {
2974 if (getParser().ParseAbsoluteExpression(CurrValue))
2977 Values.push_back((uint8_t)CurrValue);
2979 while (getLexer().is(AsmToken::Comma)) {
2982 if (getParser().ParseAbsoluteExpression(CurrValue))
2985 Values.push_back((uint8_t)CurrValue);
2988 getStreamer().EmitCFIEscape(Values);
2992 /// ParseDirectiveCFISignalFrame
2993 /// ::= .cfi_signal_frame
2994 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
2995 SMLoc DirectiveLoc) {
2996 if (getLexer().isNot(AsmToken::EndOfStatement))
2997 return Error(getLexer().getLoc(),
2998 "unexpected token in '" + Directive + "' directive");
3000 getStreamer().EmitCFISignalFrame();
3005 /// ParseDirectiveMacrosOnOff
3008 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3009 SMLoc DirectiveLoc) {
3010 if (getLexer().isNot(AsmToken::EndOfStatement))
3011 return Error(getLexer().getLoc(),
3012 "unexpected token in '" + Directive + "' directive");
3014 getParser().MacrosEnabled = Directive == ".macros_on";
3019 /// ParseDirectiveMacro
3020 /// ::= .macro name [parameters]
3021 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3022 SMLoc DirectiveLoc) {
3024 if (getParser().ParseIdentifier(Name))
3025 return TokError("expected identifier in directive");
3027 std::vector<StringRef> Parameters;
3028 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3030 StringRef Parameter;
3031 if (getParser().ParseIdentifier(Parameter))
3032 return TokError("expected identifier in directive");
3033 Parameters.push_back(Parameter);
3035 if (getLexer().isNot(AsmToken::Comma))
3041 if (getLexer().isNot(AsmToken::EndOfStatement))
3042 return TokError("unexpected token in '.macro' directive");
3044 // Eat the end of statement.
3047 AsmToken EndToken, StartToken = getTok();
3049 // Lex the macro definition.
3051 // Check whether we have reached the end of the file.
3052 if (getLexer().is(AsmToken::Eof))
3053 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3055 // Otherwise, check whether we have reach the .endmacro.
3056 if (getLexer().is(AsmToken::Identifier) &&
3057 (getTok().getIdentifier() == ".endm" ||
3058 getTok().getIdentifier() == ".endmacro")) {
3059 EndToken = getTok();
3061 if (getLexer().isNot(AsmToken::EndOfStatement))
3062 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3067 // Otherwise, scan til the end of the statement.
3068 getParser().EatToEndOfStatement();
3071 if (getParser().MacroMap.lookup(Name)) {
3072 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3075 const char *BodyStart = StartToken.getLoc().getPointer();
3076 const char *BodyEnd = EndToken.getLoc().getPointer();
3077 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3078 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3082 /// ParseDirectiveEndMacro
3085 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3086 SMLoc DirectiveLoc) {
3087 if (getLexer().isNot(AsmToken::EndOfStatement))
3088 return TokError("unexpected token in '" + Directive + "' directive");
3090 // If we are inside a macro instantiation, terminate the current
3092 if (!getParser().ActiveMacros.empty()) {
3093 getParser().HandleMacroExit();
3097 // Otherwise, this .endmacro is a stray entry in the file; well formed
3098 // .endmacro directives are handled during the macro definition parsing.
3099 return TokError("unexpected '" + Directive + "' in file, "
3100 "no current macro definition");
3103 /// ParseDirectivePurgeMacro
3105 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3106 SMLoc DirectiveLoc) {
3108 if (getParser().ParseIdentifier(Name))
3109 return TokError("expected identifier in '.purgem' directive");
3111 if (getLexer().isNot(AsmToken::EndOfStatement))
3112 return TokError("unexpected token in '.purgem' directive");
3114 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3115 if (I == getParser().MacroMap.end())
3116 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3118 // Undefine the macro.
3119 delete I->getValue();
3120 getParser().MacroMap.erase(I);
3124 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3125 getParser().CheckForValidSection();
3127 const MCExpr *Value;
3129 if (getParser().ParseExpression(Value))
3132 if (getLexer().isNot(AsmToken::EndOfStatement))
3133 return TokError("unexpected token in directive");
3135 if (DirName[1] == 's')
3136 getStreamer().EmitSLEB128Value(Value);
3138 getStreamer().EmitULEB128Value(Value);
3143 Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3144 AsmToken EndToken, StartToken = getTok();
3146 unsigned NestLevel = 0;
3148 // Check whether we have reached the end of the file.
3149 if (getLexer().is(AsmToken::Eof)) {
3150 Error(DirectiveLoc, "no matching '.endr' in definition");
3154 if (Lexer.is(AsmToken::Identifier) &&
3155 (getTok().getIdentifier() == ".rept")) {
3159 // Otherwise, check whether we have reached the .endr.
3160 if (Lexer.is(AsmToken::Identifier) &&
3161 getTok().getIdentifier() == ".endr") {
3162 if (NestLevel == 0) {
3163 EndToken = getTok();
3165 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3166 TokError("unexpected token in '.endr' directive");
3174 // Otherwise, scan till the end of the statement.
3175 EatToEndOfStatement();
3178 const char *BodyStart = StartToken.getLoc().getPointer();
3179 const char *BodyEnd = EndToken.getLoc().getPointer();
3180 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3182 // We Are Anonymous.
3184 std::vector<StringRef> Parameters;
3185 return new Macro(Name, Body, Parameters);
3188 void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3189 raw_svector_ostream &OS) {
3192 MemoryBuffer *Instantiation =
3193 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3195 // Create the macro instantiation object and add to the current macro
3196 // instantiation stack.
3197 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3200 ActiveMacros.push_back(MI);
3202 // Jump to the macro instantiation and prime the lexer.
3203 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3204 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3208 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3210 if (ParseAbsoluteExpression(Count))
3211 return TokError("unexpected token in '.rept' directive");
3214 return TokError("Count is negative");
3216 if (Lexer.isNot(AsmToken::EndOfStatement))
3217 return TokError("unexpected token in '.rept' directive");
3219 // Eat the end of statement.
3222 // Lex the rept definition.
3223 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3227 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3228 // to hold the macro body with substitutions.
3229 SmallString<256> Buf;
3230 std::vector<StringRef> Parameters;
3231 const std::vector<MacroArgument> A;
3232 raw_svector_ostream OS(Buf);
3234 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3237 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3242 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3243 if (ActiveMacros.empty())
3244 return TokError("unexpected '.endr' directive, no current .rept");
3246 // The only .repl that should get here are the ones created by
3247 // InstantiateMacroLikeBody.
3248 assert(getLexer().is(AsmToken::EndOfStatement));
3254 /// \brief Create an MCAsmParser instance.
3255 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3256 MCContext &C, MCStreamer &Out,
3257 const MCAsmInfo &MAI) {
3258 return new AsmParser(SM, C, Out, MAI);