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.
51 std::vector<StringRef> Parameters;
54 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
55 Name(N), Body(B), Parameters(P) {}
58 /// \brief Helper class for storing information about an active macro
60 struct MacroInstantiation {
61 /// The macro being instantiated.
62 const Macro *TheMacro;
64 /// The macro instantiation with substitutions.
65 MemoryBuffer *Instantiation;
67 /// The location of the instantiation.
68 SMLoc InstantiationLoc;
70 /// The location where parsing should resume upon instantiation completion.
74 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
78 /// \brief The concrete assembly parser instance.
79 class AsmParser : public MCAsmParser {
80 friend class GenericAsmParser;
82 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
83 void operator=(const AsmParser &); // DO NOT IMPLEMENT
90 SourceMgr::DiagHandlerTy SavedDiagHandler;
91 void *SavedDiagContext;
92 MCAsmParserExtension *GenericParser;
93 MCAsmParserExtension *PlatformParser;
95 /// This is the current buffer index we're lexing from as managed by the
100 std::vector<AsmCond> TheCondStack;
102 /// DirectiveMap - This is a table handlers for directives. Each handler is
103 /// invoked after the directive identifier is read and is responsible for
104 /// parsing and validating the rest of the directive. The handler is passed
105 /// in the directive name and the location of the directive keyword.
106 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
108 /// MacroMap - Map of currently defined macros.
109 StringMap<Macro*> MacroMap;
111 /// ActiveMacros - Stack of active macro instantiations.
112 std::vector<MacroInstantiation*> ActiveMacros;
114 /// Boolean tracking whether macro substitution is enabled.
115 unsigned MacrosEnabled : 1;
117 /// Flag tracking whether any errors have been encountered.
118 unsigned HadError : 1;
120 /// The values from the last parsed cpp hash file line comment if any.
121 StringRef CppHashFilename;
122 int64_t CppHashLineNumber;
125 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
126 unsigned AssemblerDialect;
129 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
130 const MCAsmInfo &MAI);
133 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
135 void AddDirectiveHandler(MCAsmParserExtension *Object,
137 DirectiveHandler Handler) {
138 DirectiveMap[Directive] = std::make_pair(Object, Handler);
142 /// @name MCAsmParser Interface
145 virtual SourceMgr &getSourceManager() { return SrcMgr; }
146 virtual MCAsmLexer &getLexer() { return Lexer; }
147 virtual MCContext &getContext() { return Ctx; }
148 virtual MCStreamer &getStreamer() { return Out; }
149 virtual unsigned getAssemblerDialect() {
150 if (AssemblerDialect == ~0U)
151 return MAI.getAssemblerDialect();
153 return AssemblerDialect;
155 virtual void setAssemblerDialect(unsigned i) {
156 AssemblerDialect = i;
159 virtual bool Warning(SMLoc L, const Twine &Msg,
160 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
161 virtual bool Error(SMLoc L, const Twine &Msg,
162 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
164 const AsmToken &Lex();
166 bool ParseExpression(const MCExpr *&Res);
167 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
168 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
169 virtual bool ParseAbsoluteExpression(int64_t &Res);
174 void CheckForValidSection();
176 bool ParseStatement();
177 void EatToEndOfLine();
178 bool ParseCppHashLineFilenameComment(const SMLoc &L);
180 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
181 bool expandMacro(SmallString<256> &Buf, StringRef Body,
182 const std::vector<StringRef> &Parameters,
183 const std::vector<std::vector<AsmToken> > &A,
185 void HandleMacroExit();
187 void PrintMacroInstantiations();
188 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
189 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
190 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
192 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
194 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
195 bool EnterIncludeFile(const std::string &Filename);
196 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
197 /// This returns true on failure.
198 bool ProcessIncbinFile(const std::string &Filename);
200 /// \brief Reset the current lexer position to that given by \arg Loc. The
201 /// current token is not set; clients should ensure Lex() is called
203 void JumpToLoc(SMLoc Loc);
205 void EatToEndOfStatement();
207 /// \brief Parse up to the end of statement and a return the contents from the
208 /// current token until the end of the statement; the current token on exit
209 /// will be either the EndOfStatement or EOF.
210 StringRef ParseStringToEndOfStatement();
212 bool ParseAssignment(StringRef Name, bool allow_redef);
214 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
215 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
216 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
217 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
219 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
220 /// and set \arg Res to the identifier contents.
221 bool ParseIdentifier(StringRef &Res);
223 // Directive Parsing.
225 // ".ascii", ".asciiz", ".string"
226 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
227 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
228 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
229 bool ParseDirectiveFill(); // ".fill"
230 bool ParseDirectiveSpace(); // ".space"
231 bool ParseDirectiveZero(); // ".zero"
232 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
233 bool ParseDirectiveOrg(); // ".org"
234 // ".align{,32}", ".p2align{,w,l}"
235 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
237 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
238 /// accepts a single symbol (which should be a label or an external).
239 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
241 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
243 bool ParseDirectiveAbort(); // ".abort"
244 bool ParseDirectiveInclude(); // ".include"
245 bool ParseDirectiveIncbin(); // ".incbin"
247 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
248 // ".ifdef" or ".ifndef", depending on expect_defined
249 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
250 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
251 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
252 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
254 /// ParseEscapedString - Parse the current token as a string which may include
255 /// escaped characters and return the string contents.
256 bool ParseEscapedString(std::string &Data);
258 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
259 MCSymbolRefExpr::VariantKind Variant);
262 /// \brief Generic implementations of directive handling, etc. which is shared
263 /// (or the default, at least) for all assembler parser.
264 class GenericAsmParser : public MCAsmParserExtension {
265 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
266 void AddDirectiveHandler(StringRef Directive) {
267 getParser().AddDirectiveHandler(this, Directive,
268 HandleDirective<GenericAsmParser, Handler>);
271 GenericAsmParser() {}
273 AsmParser &getParser() {
274 return (AsmParser&) this->MCAsmParserExtension::getParser();
277 virtual void Initialize(MCAsmParser &Parser) {
278 // Call the base implementation.
279 this->MCAsmParserExtension::Initialize(Parser);
281 // Debugging directives.
282 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
283 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
284 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
285 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
288 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
290 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
292 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
294 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
296 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
297 ".cfi_def_cfa_offset");
298 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
299 ".cfi_adjust_cfa_offset");
300 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
301 ".cfi_def_cfa_register");
302 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
304 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
307 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
309 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
311 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
313 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
315 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
317 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
319 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
321 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
324 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
326 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
328 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
329 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
330 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
332 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
333 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
336 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
338 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
339 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
340 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
341 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
342 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
343 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
344 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
345 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
346 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
347 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
348 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
349 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
350 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
351 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
352 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
353 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
354 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
355 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
356 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
357 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
359 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
360 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
361 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
363 bool ParseDirectiveLEB128(StringRef, SMLoc);
370 extern MCAsmParserExtension *createDarwinAsmParser();
371 extern MCAsmParserExtension *createELFAsmParser();
372 extern MCAsmParserExtension *createCOFFAsmParser();
376 enum { DEFAULT_ADDRSPACE = 0 };
378 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
379 MCStreamer &_Out, const MCAsmInfo &_MAI)
380 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
381 GenericParser(new GenericAsmParser), PlatformParser(0),
382 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
383 AssemblerDialect(~0U) {
384 // Save the old handler.
385 SavedDiagHandler = SrcMgr.getDiagHandler();
386 SavedDiagContext = SrcMgr.getDiagContext();
387 // Set our own handler which calls the saved handler.
388 SrcMgr.setDiagHandler(DiagHandler, this);
389 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
391 // Initialize the generic parser.
392 GenericParser->Initialize(*this);
394 // Initialize the platform / file format parser.
396 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
398 if (_MAI.hasMicrosoftFastStdCallMangling()) {
399 PlatformParser = createCOFFAsmParser();
400 PlatformParser->Initialize(*this);
401 } else if (_MAI.hasSubsectionsViaSymbols()) {
402 PlatformParser = createDarwinAsmParser();
403 PlatformParser->Initialize(*this);
405 PlatformParser = createELFAsmParser();
406 PlatformParser->Initialize(*this);
410 AsmParser::~AsmParser() {
411 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
413 // Destroy any macros.
414 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
415 ie = MacroMap.end(); it != ie; ++it)
416 delete it->getValue();
418 delete PlatformParser;
419 delete GenericParser;
422 void AsmParser::PrintMacroInstantiations() {
423 // Print the active macro instantiation stack.
424 for (std::vector<MacroInstantiation*>::const_reverse_iterator
425 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
426 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
427 "while in macro instantiation");
430 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
431 if (FatalAssemblerWarnings)
432 return Error(L, Msg, Ranges);
433 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
434 PrintMacroInstantiations();
438 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
440 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
441 PrintMacroInstantiations();
445 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
446 std::string IncludedFile;
447 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
453 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
458 /// Process the specified .incbin file by seaching for it in the include paths
459 /// then just emiting the byte contents of the file to the streamer. This
460 /// returns true on failure.
461 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
462 std::string IncludedFile;
463 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
467 // Pick up the bytes from the file and emit them.
468 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
473 void AsmParser::JumpToLoc(SMLoc Loc) {
474 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
475 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
478 const AsmToken &AsmParser::Lex() {
479 const AsmToken *tok = &Lexer.Lex();
481 if (tok->is(AsmToken::Eof)) {
482 // If this is the end of an included file, pop the parent file off the
484 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
485 if (ParentIncludeLoc != SMLoc()) {
486 JumpToLoc(ParentIncludeLoc);
491 if (tok->is(AsmToken::Error))
492 Error(Lexer.getErrLoc(), Lexer.getErr());
497 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
498 // Create the initial section, if requested.
499 if (!NoInitialTextSection)
506 AsmCond StartingCondState = TheCondState;
508 // If we are generating dwarf for assembly source files save the initial text
509 // section and generate a .file directive.
510 if (getContext().getGenDwarfForAssembly()) {
511 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
512 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
513 getStreamer().EmitLabel(SectionStartSym);
514 getContext().setGenDwarfSectionStartSym(SectionStartSym);
515 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
516 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
519 // While we have input, parse each statement.
520 while (Lexer.isNot(AsmToken::Eof)) {
521 if (!ParseStatement()) continue;
523 // We had an error, validate that one was emitted and recover by skipping to
525 assert(HadError && "Parse statement returned an error, but none emitted!");
526 EatToEndOfStatement();
529 if (TheCondState.TheCond != StartingCondState.TheCond ||
530 TheCondState.Ignore != StartingCondState.Ignore)
531 return TokError("unmatched .ifs or .elses");
533 // Check to see there are no empty DwarfFile slots.
534 const std::vector<MCDwarfFile *> &MCDwarfFiles =
535 getContext().getMCDwarfFiles();
536 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
537 if (!MCDwarfFiles[i])
538 TokError("unassigned file number: " + Twine(i) + " for .file directives");
541 // Check to see that all assembler local symbols were actually defined.
542 // Targets that don't do subsections via symbols may not want this, though,
543 // so conservatively exclude them. Only do this if we're finalizing, though,
544 // as otherwise we won't necessarilly have seen everything yet.
545 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
546 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
547 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
550 MCSymbol *Sym = i->getValue();
551 // Variable symbols may not be marked as defined, so check those
552 // explicitly. If we know it's a variable, we have a definition for
553 // the purposes of this check.
554 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
555 // FIXME: We would really like to refer back to where the symbol was
556 // first referenced for a source location. We need to add something
557 // to track that. Currently, we just point to the end of the file.
558 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
559 "assembler local symbol '" + Sym->getName() +
565 // Finalize the output stream if there are no errors and if the client wants
567 if (!HadError && !NoFinalize)
573 void AsmParser::CheckForValidSection() {
574 if (!getStreamer().getCurrentSection()) {
575 TokError("expected section directive before assembly directive");
576 Out.SwitchSection(Ctx.getMachOSection(
578 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
579 0, SectionKind::getText()));
583 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
584 void AsmParser::EatToEndOfStatement() {
585 while (Lexer.isNot(AsmToken::EndOfStatement) &&
586 Lexer.isNot(AsmToken::Eof))
590 if (Lexer.is(AsmToken::EndOfStatement))
594 StringRef AsmParser::ParseStringToEndOfStatement() {
595 const char *Start = getTok().getLoc().getPointer();
597 while (Lexer.isNot(AsmToken::EndOfStatement) &&
598 Lexer.isNot(AsmToken::Eof))
601 const char *End = getTok().getLoc().getPointer();
602 return StringRef(Start, End - Start);
605 /// ParseParenExpr - Parse a paren expression and return it.
606 /// NOTE: This assumes the leading '(' has already been consumed.
608 /// parenexpr ::= expr)
610 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
611 if (ParseExpression(Res)) return true;
612 if (Lexer.isNot(AsmToken::RParen))
613 return TokError("expected ')' in parentheses expression");
614 EndLoc = Lexer.getLoc();
619 /// ParseBracketExpr - Parse a bracket expression and return it.
620 /// NOTE: This assumes the leading '[' has already been consumed.
622 /// bracketexpr ::= expr]
624 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
625 if (ParseExpression(Res)) return true;
626 if (Lexer.isNot(AsmToken::RBrac))
627 return TokError("expected ']' in brackets expression");
628 EndLoc = Lexer.getLoc();
633 /// ParsePrimaryExpr - Parse a primary expression and return it.
634 /// primaryexpr ::= (parenexpr
635 /// primaryexpr ::= symbol
636 /// primaryexpr ::= number
637 /// primaryexpr ::= '.'
638 /// primaryexpr ::= ~,+,- primaryexpr
639 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
640 switch (Lexer.getKind()) {
642 return TokError("unknown token in expression");
643 // If we have an error assume that we've already handled it.
644 case AsmToken::Error:
646 case AsmToken::Exclaim:
647 Lex(); // Eat the operator.
648 if (ParsePrimaryExpr(Res, EndLoc))
650 Res = MCUnaryExpr::CreateLNot(Res, getContext());
652 case AsmToken::Dollar:
653 case AsmToken::String:
654 case AsmToken::Identifier: {
655 EndLoc = Lexer.getLoc();
657 StringRef Identifier;
658 if (ParseIdentifier(Identifier))
661 // This is a symbol reference.
662 std::pair<StringRef, StringRef> Split = Identifier.split('@');
663 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
665 // Lookup the symbol variant if used.
666 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
667 if (Split.first.size() != Identifier.size()) {
668 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
669 if (Variant == MCSymbolRefExpr::VK_Invalid) {
670 Variant = MCSymbolRefExpr::VK_None;
671 return TokError("invalid variant '" + Split.second + "'");
675 // If this is an absolute variable reference, substitute it now to preserve
676 // semantics in the face of reassignment.
677 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
679 return Error(EndLoc, "unexpected modifier on variable reference");
681 Res = Sym->getVariableValue();
685 // Otherwise create a symbol ref.
686 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
689 case AsmToken::Integer: {
690 SMLoc Loc = getTok().getLoc();
691 int64_t IntVal = getTok().getIntVal();
692 Res = MCConstantExpr::Create(IntVal, getContext());
693 EndLoc = Lexer.getLoc();
695 // Look for 'b' or 'f' following an Integer as a directional label
696 if (Lexer.getKind() == AsmToken::Identifier) {
697 StringRef IDVal = getTok().getString();
698 if (IDVal == "f" || IDVal == "b"){
699 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
700 IDVal == "f" ? 1 : 0);
701 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
703 if(IDVal == "b" && Sym->isUndefined())
704 return Error(Loc, "invalid reference to undefined symbol");
705 EndLoc = Lexer.getLoc();
706 Lex(); // Eat identifier.
711 case AsmToken::Real: {
712 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
713 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
714 Res = MCConstantExpr::Create(IntVal, getContext());
718 case AsmToken::Dot: {
719 // This is a '.' reference, which references the current PC. Emit a
720 // temporary label to the streamer and refer to it.
721 MCSymbol *Sym = Ctx.CreateTempSymbol();
723 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
724 EndLoc = Lexer.getLoc();
725 Lex(); // Eat identifier.
728 case AsmToken::LParen:
729 Lex(); // Eat the '('.
730 return ParseParenExpr(Res, EndLoc);
731 case AsmToken::LBrac:
732 if (!PlatformParser->HasBracketExpressions())
733 return TokError("brackets expression not supported on this target");
734 Lex(); // Eat the '['.
735 return ParseBracketExpr(Res, EndLoc);
736 case AsmToken::Minus:
737 Lex(); // Eat the operator.
738 if (ParsePrimaryExpr(Res, EndLoc))
740 Res = MCUnaryExpr::CreateMinus(Res, getContext());
743 Lex(); // Eat the operator.
744 if (ParsePrimaryExpr(Res, EndLoc))
746 Res = MCUnaryExpr::CreatePlus(Res, getContext());
748 case AsmToken::Tilde:
749 Lex(); // Eat the operator.
750 if (ParsePrimaryExpr(Res, EndLoc))
752 Res = MCUnaryExpr::CreateNot(Res, getContext());
757 bool AsmParser::ParseExpression(const MCExpr *&Res) {
759 return ParseExpression(Res, EndLoc);
763 AsmParser::ApplyModifierToExpr(const MCExpr *E,
764 MCSymbolRefExpr::VariantKind Variant) {
765 // Recurse over the given expression, rebuilding it to apply the given variant
766 // if there is exactly one symbol.
767 switch (E->getKind()) {
769 case MCExpr::Constant:
772 case MCExpr::SymbolRef: {
773 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
775 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
776 TokError("invalid variant on expression '" +
777 getTok().getIdentifier() + "' (already modified)");
781 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
784 case MCExpr::Unary: {
785 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
786 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
789 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
792 case MCExpr::Binary: {
793 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
794 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
795 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
800 if (!LHS) LHS = BE->getLHS();
801 if (!RHS) RHS = BE->getRHS();
803 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
807 llvm_unreachable("Invalid expression kind!");
810 /// ParseExpression - Parse an expression and return it.
812 /// expr ::= expr &&,|| expr -> lowest.
813 /// expr ::= expr |,^,&,! expr
814 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
815 /// expr ::= expr <<,>> expr
816 /// expr ::= expr +,- expr
817 /// expr ::= expr *,/,% expr -> highest.
818 /// expr ::= primaryexpr
820 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
821 // Parse the expression.
823 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
826 // As a special case, we support 'a op b @ modifier' by rewriting the
827 // expression to include the modifier. This is inefficient, but in general we
828 // expect users to use 'a@modifier op b'.
829 if (Lexer.getKind() == AsmToken::At) {
832 if (Lexer.isNot(AsmToken::Identifier))
833 return TokError("unexpected symbol modifier following '@'");
835 MCSymbolRefExpr::VariantKind Variant =
836 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
837 if (Variant == MCSymbolRefExpr::VK_Invalid)
838 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
840 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
842 return TokError("invalid modifier '" + getTok().getIdentifier() +
843 "' (no symbols present)");
850 // Try to constant fold it up front, if possible.
852 if (Res->EvaluateAsAbsolute(Value))
853 Res = MCConstantExpr::Create(Value, getContext());
858 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
860 return ParseParenExpr(Res, EndLoc) ||
861 ParseBinOpRHS(1, Res, EndLoc);
864 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
867 SMLoc StartLoc = Lexer.getLoc();
868 if (ParseExpression(Expr))
871 if (!Expr->EvaluateAsAbsolute(Res))
872 return Error(StartLoc, "expected absolute expression");
877 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
878 MCBinaryExpr::Opcode &Kind) {
881 return 0; // not a binop.
883 // Lowest Precedence: &&, ||
884 case AsmToken::AmpAmp:
885 Kind = MCBinaryExpr::LAnd;
887 case AsmToken::PipePipe:
888 Kind = MCBinaryExpr::LOr;
892 // Low Precedence: |, &, ^
894 // FIXME: gas seems to support '!' as an infix operator?
896 Kind = MCBinaryExpr::Or;
898 case AsmToken::Caret:
899 Kind = MCBinaryExpr::Xor;
902 Kind = MCBinaryExpr::And;
905 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
906 case AsmToken::EqualEqual:
907 Kind = MCBinaryExpr::EQ;
909 case AsmToken::ExclaimEqual:
910 case AsmToken::LessGreater:
911 Kind = MCBinaryExpr::NE;
914 Kind = MCBinaryExpr::LT;
916 case AsmToken::LessEqual:
917 Kind = MCBinaryExpr::LTE;
919 case AsmToken::Greater:
920 Kind = MCBinaryExpr::GT;
922 case AsmToken::GreaterEqual:
923 Kind = MCBinaryExpr::GTE;
926 // Intermediate Precedence: <<, >>
927 case AsmToken::LessLess:
928 Kind = MCBinaryExpr::Shl;
930 case AsmToken::GreaterGreater:
931 Kind = MCBinaryExpr::Shr;
934 // High Intermediate Precedence: +, -
936 Kind = MCBinaryExpr::Add;
938 case AsmToken::Minus:
939 Kind = MCBinaryExpr::Sub;
942 // Highest Precedence: *, /, %
944 Kind = MCBinaryExpr::Mul;
946 case AsmToken::Slash:
947 Kind = MCBinaryExpr::Div;
949 case AsmToken::Percent:
950 Kind = MCBinaryExpr::Mod;
956 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
957 /// Res contains the LHS of the expression on input.
958 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
961 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
962 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
964 // If the next token is lower precedence than we are allowed to eat, return
965 // successfully with what we ate already.
966 if (TokPrec < Precedence)
971 // Eat the next primary expression.
973 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
975 // If BinOp binds less tightly with RHS than the operator after RHS, let
976 // the pending operator take RHS as its LHS.
977 MCBinaryExpr::Opcode Dummy;
978 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
979 if (TokPrec < NextTokPrec) {
980 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
983 // Merge LHS and RHS according to operator.
984 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
992 /// ::= EndOfStatement
993 /// ::= Label* Directive ...Operands... EndOfStatement
994 /// ::= Label* Identifier OperandList* EndOfStatement
995 bool AsmParser::ParseStatement() {
996 if (Lexer.is(AsmToken::EndOfStatement)) {
1002 // Statements always start with an identifier or are a full line comment.
1003 AsmToken ID = getTok();
1004 SMLoc IDLoc = ID.getLoc();
1006 int64_t LocalLabelVal = -1;
1007 // A full line comment is a '#' as the first token.
1008 if (Lexer.is(AsmToken::Hash))
1009 return ParseCppHashLineFilenameComment(IDLoc);
1011 // Allow an integer followed by a ':' as a directional local label.
1012 if (Lexer.is(AsmToken::Integer)) {
1013 LocalLabelVal = getTok().getIntVal();
1014 if (LocalLabelVal < 0) {
1015 if (!TheCondState.Ignore)
1016 return TokError("unexpected token at start of statement");
1020 IDVal = getTok().getString();
1021 Lex(); // Consume the integer token to be used as an identifier token.
1022 if (Lexer.getKind() != AsmToken::Colon) {
1023 if (!TheCondState.Ignore)
1024 return TokError("unexpected token at start of statement");
1028 } else if (Lexer.is(AsmToken::Dot)) {
1029 // Treat '.' as a valid identifier in this context.
1033 } else if (ParseIdentifier(IDVal)) {
1034 if (!TheCondState.Ignore)
1035 return TokError("unexpected token at start of statement");
1040 // Handle conditional assembly here before checking for skipping. We
1041 // have to do this so that .endif isn't skipped in a ".if 0" block for
1044 return ParseDirectiveIf(IDLoc);
1045 if (IDVal == ".ifdef")
1046 return ParseDirectiveIfdef(IDLoc, true);
1047 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1048 return ParseDirectiveIfdef(IDLoc, false);
1049 if (IDVal == ".elseif")
1050 return ParseDirectiveElseIf(IDLoc);
1051 if (IDVal == ".else")
1052 return ParseDirectiveElse(IDLoc);
1053 if (IDVal == ".endif")
1054 return ParseDirectiveEndIf(IDLoc);
1056 // If we are in a ".if 0" block, ignore this statement.
1057 if (TheCondState.Ignore) {
1058 EatToEndOfStatement();
1062 // FIXME: Recurse on local labels?
1064 // See what kind of statement we have.
1065 switch (Lexer.getKind()) {
1066 case AsmToken::Colon: {
1067 CheckForValidSection();
1069 // identifier ':' -> Label.
1072 // Diagnose attempt to use '.' as a label.
1074 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1076 // Diagnose attempt to use a variable as a label.
1078 // FIXME: Diagnostics. Note the location of the definition as a label.
1079 // FIXME: This doesn't diagnose assignment to a symbol which has been
1080 // implicitly marked as external.
1082 if (LocalLabelVal == -1)
1083 Sym = getContext().GetOrCreateSymbol(IDVal);
1085 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1086 if (!Sym->isUndefined() || Sym->isVariable())
1087 return Error(IDLoc, "invalid symbol redefinition");
1092 // If we are generating dwarf for assembly source files then gather the
1093 // info to make a dwarf label entry for this label if needed.
1094 if (getContext().getGenDwarfForAssembly())
1095 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1098 // Consume any end of statement token, if present, to avoid spurious
1099 // AddBlankLine calls().
1100 if (Lexer.is(AsmToken::EndOfStatement)) {
1102 if (Lexer.is(AsmToken::Eof))
1106 return ParseStatement();
1109 case AsmToken::Equal:
1110 // identifier '=' ... -> assignment statement
1113 return ParseAssignment(IDVal, true);
1115 default: // Normal instruction or directive.
1119 // If macros are enabled, check to see if this is a macro instantiation.
1121 if (const Macro *M = MacroMap.lookup(IDVal))
1122 return HandleMacroEntry(IDVal, IDLoc, M);
1124 // Otherwise, we have a normal instruction or directive.
1125 if (IDVal[0] == '.' && IDVal != ".") {
1126 // Assembler features
1127 if (IDVal == ".set" || IDVal == ".equ")
1128 return ParseDirectiveSet(IDVal, true);
1129 if (IDVal == ".equiv")
1130 return ParseDirectiveSet(IDVal, false);
1134 if (IDVal == ".ascii")
1135 return ParseDirectiveAscii(IDVal, false);
1136 if (IDVal == ".asciz" || IDVal == ".string")
1137 return ParseDirectiveAscii(IDVal, true);
1139 if (IDVal == ".byte")
1140 return ParseDirectiveValue(1);
1141 if (IDVal == ".short")
1142 return ParseDirectiveValue(2);
1143 if (IDVal == ".value")
1144 return ParseDirectiveValue(2);
1145 if (IDVal == ".2byte")
1146 return ParseDirectiveValue(2);
1147 if (IDVal == ".long")
1148 return ParseDirectiveValue(4);
1149 if (IDVal == ".int")
1150 return ParseDirectiveValue(4);
1151 if (IDVal == ".4byte")
1152 return ParseDirectiveValue(4);
1153 if (IDVal == ".quad")
1154 return ParseDirectiveValue(8);
1155 if (IDVal == ".8byte")
1156 return ParseDirectiveValue(8);
1157 if (IDVal == ".single" || IDVal == ".float")
1158 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1159 if (IDVal == ".double")
1160 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1162 if (IDVal == ".align") {
1163 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1164 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1166 if (IDVal == ".align32") {
1167 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1168 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1170 if (IDVal == ".balign")
1171 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1172 if (IDVal == ".balignw")
1173 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1174 if (IDVal == ".balignl")
1175 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1176 if (IDVal == ".p2align")
1177 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1178 if (IDVal == ".p2alignw")
1179 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1180 if (IDVal == ".p2alignl")
1181 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1183 if (IDVal == ".org")
1184 return ParseDirectiveOrg();
1186 if (IDVal == ".fill")
1187 return ParseDirectiveFill();
1188 if (IDVal == ".space" || IDVal == ".skip")
1189 return ParseDirectiveSpace();
1190 if (IDVal == ".zero")
1191 return ParseDirectiveZero();
1193 // Symbol attribute directives
1195 if (IDVal == ".globl" || IDVal == ".global")
1196 return ParseDirectiveSymbolAttribute(MCSA_Global);
1197 if (IDVal == ".indirect_symbol")
1198 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1199 if (IDVal == ".lazy_reference")
1200 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1201 if (IDVal == ".no_dead_strip")
1202 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1203 if (IDVal == ".symbol_resolver")
1204 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1205 if (IDVal == ".private_extern")
1206 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1207 if (IDVal == ".reference")
1208 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1209 if (IDVal == ".weak_definition")
1210 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1211 if (IDVal == ".weak_reference")
1212 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1213 if (IDVal == ".weak_def_can_be_hidden")
1214 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1216 if (IDVal == ".comm" || IDVal == ".common")
1217 return ParseDirectiveComm(/*IsLocal=*/false);
1218 if (IDVal == ".lcomm")
1219 return ParseDirectiveComm(/*IsLocal=*/true);
1221 if (IDVal == ".abort")
1222 return ParseDirectiveAbort();
1223 if (IDVal == ".include")
1224 return ParseDirectiveInclude();
1225 if (IDVal == ".incbin")
1226 return ParseDirectiveIncbin();
1228 if (IDVal == ".code16")
1229 return TokError(Twine(IDVal) + " not supported yet");
1231 // Look up the handler in the handler table.
1232 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1233 DirectiveMap.lookup(IDVal);
1235 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1237 // Target hook for parsing target specific directives.
1238 if (!getTargetParser().ParseDirective(ID))
1241 return Warning(IDLoc, "ignoring directive for now");
1244 CheckForValidSection();
1246 // Canonicalize the opcode to lower case.
1247 SmallString<128> Opcode;
1248 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1249 Opcode.push_back(tolower(IDVal[i]));
1251 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1252 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1255 // Dump the parsed representation, if requested.
1256 if (getShowParsedOperands()) {
1257 SmallString<256> Str;
1258 raw_svector_ostream OS(Str);
1259 OS << "parsed instruction: [";
1260 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1263 ParsedOperands[i]->print(OS);
1267 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1270 // If we are generating dwarf for assembly source files and the current
1271 // section is the initial text section then generate a .loc directive for
1273 if (!HadError && getContext().getGenDwarfForAssembly() &&
1274 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1275 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1276 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1277 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1278 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1282 // If parsing succeeded, match the instruction.
1284 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1287 // Free any parsed operands.
1288 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1289 delete ParsedOperands[i];
1291 // Don't skip the rest of the line, the instruction parser is responsible for
1296 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1297 /// since they may not be able to be tokenized to get to the end of line token.
1298 void AsmParser::EatToEndOfLine() {
1299 if (!Lexer.is(AsmToken::EndOfStatement))
1300 Lexer.LexUntilEndOfLine();
1305 /// ParseCppHashLineFilenameComment as this:
1306 /// ::= # number "filename"
1307 /// or just as a full line comment if it doesn't have a number and a string.
1308 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1309 Lex(); // Eat the hash token.
1311 if (getLexer().isNot(AsmToken::Integer)) {
1312 // Consume the line since in cases it is not a well-formed line directive,
1313 // as if were simply a full line comment.
1318 int64_t LineNumber = getTok().getIntVal();
1321 if (getLexer().isNot(AsmToken::String)) {
1326 StringRef Filename = getTok().getString();
1327 // Get rid of the enclosing quotes.
1328 Filename = Filename.substr(1, Filename.size()-2);
1330 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1332 CppHashFilename = Filename;
1333 CppHashLineNumber = LineNumber;
1335 // Ignore any trailing characters, they're just comment.
1340 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1341 /// for the Filename and LineNo if any in the diagnostic.
1342 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1343 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1344 raw_ostream &OS = errs();
1346 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1347 const SMLoc &DiagLoc = Diag.getLoc();
1348 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1349 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1351 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1352 // before printing the message.
1353 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1354 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1355 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1356 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1359 // If we have not parsed a cpp hash line filename comment or the source
1360 // manager changed or buffer changed (like in a nested include) then just
1361 // print the normal diagnostic using its Filename and LineNo.
1362 if (!Parser->CppHashLineNumber ||
1363 &DiagSrcMgr != &Parser->SrcMgr ||
1364 DiagBuf != CppHashBuf) {
1365 if (Parser->SavedDiagHandler)
1366 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1372 // Use the CppHashFilename and calculate a line number based on the
1373 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1375 const std::string Filename = Parser->CppHashFilename;
1377 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1378 int CppHashLocLineNo =
1379 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1380 int LineNo = Parser->CppHashLineNumber - 1 +
1381 (DiagLocLineNo - CppHashLocLineNo);
1383 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1384 Filename, LineNo, Diag.getColumnNo(),
1385 Diag.getKind(), Diag.getMessage(),
1386 Diag.getLineContents(), Diag.getRanges());
1388 if (Parser->SavedDiagHandler)
1389 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1391 NewDiag.print(0, OS);
1394 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1395 const std::vector<StringRef> &Parameters,
1396 const std::vector<std::vector<AsmToken> > &A,
1398 raw_svector_ostream OS(Buf);
1399 unsigned NParameters = Parameters.size();
1400 if (NParameters != 0 && NParameters != A.size())
1401 return Error(L, "Wrong number of arguments");
1403 while (!Body.empty()) {
1404 // Scan for the next substitution.
1405 std::size_t End = Body.size(), Pos = 0;
1406 for (; Pos != End; ++Pos) {
1407 // Check for a substitution or escape.
1409 // This macro has no parameters, look for $0, $1, etc.
1410 if (Body[Pos] != '$' || Pos + 1 == End)
1413 char Next = Body[Pos + 1];
1414 if (Next == '$' || Next == 'n' || isdigit(Next))
1417 // This macro has parameters, look for \foo, \bar, etc.
1418 if (Body[Pos] == '\\' && Pos + 1 != End)
1424 OS << Body.slice(0, Pos);
1426 // Check if we reached the end.
1431 switch (Body[Pos+1]) {
1437 // $n => number of arguments
1442 // $[0-9] => argument
1444 // Missing arguments are ignored.
1445 unsigned Index = Body[Pos+1] - '0';
1446 if (Index >= A.size())
1449 // Otherwise substitute with the token values, with spaces eliminated.
1450 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1451 ie = A[Index].end(); it != ie; ++it)
1452 OS << it->getString();
1458 unsigned I = Pos + 1;
1459 while (isalnum(Body[I]) && I + 1 != End)
1462 const char *Begin = Body.data() + Pos +1;
1463 StringRef Argument(Begin, I - (Pos +1));
1465 for (; Index < NParameters; ++Index)
1466 if (Parameters[Index] == Argument)
1469 // FIXME: We should error at the macro definition.
1470 if (Index == NParameters)
1471 return Error(L, "Parameter not found");
1473 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1474 ie = A[Index].end(); it != ie; ++it)
1475 OS << it->getString();
1477 Pos += 1 + Argument.size();
1479 // Update the scan point.
1480 Body = Body.substr(Pos);
1483 // We include the .endmacro in the buffer as our queue to exit the macro
1485 OS << ".endmacro\n";
1489 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1491 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1495 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1497 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1498 // this, although we should protect against infinite loops.
1499 if (ActiveMacros.size() == 20)
1500 return TokError("macros cannot be nested more than 20 levels deep");
1502 // Parse the macro instantiation arguments.
1503 std::vector<std::vector<AsmToken> > MacroArguments;
1504 MacroArguments.push_back(std::vector<AsmToken>());
1505 unsigned ParenLevel = 0;
1507 if (Lexer.is(AsmToken::Eof))
1508 return TokError("unexpected token in macro instantiation");
1509 if (Lexer.is(AsmToken::EndOfStatement))
1512 // If we aren't inside parentheses and this is a comma, start a new token
1514 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1515 MacroArguments.push_back(std::vector<AsmToken>());
1517 // Adjust the current parentheses level.
1518 if (Lexer.is(AsmToken::LParen))
1520 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1523 // Append the token to the current argument list.
1524 MacroArguments.back().push_back(getTok());
1528 // If the last argument didn't end up with any tokens, it's not a real
1529 // argument and we should remove it from the list. This happens with either
1530 // a tailing comma or an empty argument list.
1531 if (MacroArguments.back().empty())
1532 MacroArguments.pop_back();
1534 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1535 // to hold the macro body with substitutions.
1536 SmallString<256> Buf;
1537 StringRef Body = M->Body;
1539 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1542 MemoryBuffer *Instantiation =
1543 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1545 // Create the macro instantiation object and add to the current macro
1546 // instantiation stack.
1547 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1550 ActiveMacros.push_back(MI);
1552 // Jump to the macro instantiation and prime the lexer.
1553 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1554 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1560 void AsmParser::HandleMacroExit() {
1561 // Jump to the EndOfStatement we should return to, and consume it.
1562 JumpToLoc(ActiveMacros.back()->ExitLoc);
1565 // Pop the instantiation entry.
1566 delete ActiveMacros.back();
1567 ActiveMacros.pop_back();
1570 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1571 switch (Value->getKind()) {
1572 case MCExpr::Binary: {
1573 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1574 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1577 case MCExpr::Target:
1578 case MCExpr::Constant:
1580 case MCExpr::SymbolRef: {
1581 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1583 return IsUsedIn(Sym, S.getVariableValue());
1587 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1590 llvm_unreachable("Unknown expr kind!");
1593 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1594 // FIXME: Use better location, we should use proper tokens.
1595 SMLoc EqualLoc = Lexer.getLoc();
1597 const MCExpr *Value;
1598 if (ParseExpression(Value))
1601 // Note: we don't count b as used in "a = b". This is to allow
1605 if (Lexer.isNot(AsmToken::EndOfStatement))
1606 return TokError("unexpected token in assignment");
1608 // Error on assignment to '.'.
1610 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1611 "(use '.space' or '.org').)"));
1614 // Eat the end of statement marker.
1617 // Validate that the LHS is allowed to be a variable (either it has not been
1618 // used as a symbol, or it is an absolute symbol).
1619 MCSymbol *Sym = getContext().LookupSymbol(Name);
1621 // Diagnose assignment to a label.
1623 // FIXME: Diagnostics. Note the location of the definition as a label.
1624 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1625 if (IsUsedIn(Sym, Value))
1626 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1627 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1628 ; // Allow redefinitions of undefined symbols only used in directives.
1629 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1630 ; // Allow redefinitions of variables that haven't yet been used.
1631 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1632 return Error(EqualLoc, "redefinition of '" + Name + "'");
1633 else if (!Sym->isVariable())
1634 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1635 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1636 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1639 // Don't count these checks as uses.
1640 Sym->setUsed(false);
1642 Sym = getContext().GetOrCreateSymbol(Name);
1644 // FIXME: Handle '.'.
1646 // Do the assignment.
1647 Out.EmitAssignment(Sym, Value);
1652 /// ParseIdentifier:
1655 bool AsmParser::ParseIdentifier(StringRef &Res) {
1656 // The assembler has relaxed rules for accepting identifiers, in particular we
1657 // allow things like '.globl $foo', which would normally be separate
1658 // tokens. At this level, we have already lexed so we cannot (currently)
1659 // handle this as a context dependent token, instead we detect adjacent tokens
1660 // and return the combined identifier.
1661 if (Lexer.is(AsmToken::Dollar)) {
1662 SMLoc DollarLoc = getLexer().getLoc();
1664 // Consume the dollar sign, and check for a following identifier.
1666 if (Lexer.isNot(AsmToken::Identifier))
1669 // We have a '$' followed by an identifier, make sure they are adjacent.
1670 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1673 // Construct the joined identifier and consume the token.
1674 Res = StringRef(DollarLoc.getPointer(),
1675 getTok().getIdentifier().size() + 1);
1680 if (Lexer.isNot(AsmToken::Identifier) &&
1681 Lexer.isNot(AsmToken::String))
1684 Res = getTok().getIdentifier();
1686 Lex(); // Consume the identifier token.
1691 /// ParseDirectiveSet:
1692 /// ::= .equ identifier ',' expression
1693 /// ::= .equiv identifier ',' expression
1694 /// ::= .set identifier ',' expression
1695 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1698 if (ParseIdentifier(Name))
1699 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1701 if (getLexer().isNot(AsmToken::Comma))
1702 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1705 return ParseAssignment(Name, allow_redef);
1708 bool AsmParser::ParseEscapedString(std::string &Data) {
1709 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1712 StringRef Str = getTok().getStringContents();
1713 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1714 if (Str[i] != '\\') {
1719 // Recognize escaped characters. Note that this escape semantics currently
1720 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1723 return TokError("unexpected backslash at end of string");
1725 // Recognize octal sequences.
1726 if ((unsigned) (Str[i] - '0') <= 7) {
1727 // Consume up to three octal characters.
1728 unsigned Value = Str[i] - '0';
1730 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1732 Value = Value * 8 + (Str[i] - '0');
1734 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1736 Value = Value * 8 + (Str[i] - '0');
1741 return TokError("invalid octal escape sequence (out of range)");
1743 Data += (unsigned char) Value;
1747 // Otherwise recognize individual escapes.
1750 // Just reject invalid escape sequences for now.
1751 return TokError("invalid escape sequence (unrecognized character)");
1753 case 'b': Data += '\b'; break;
1754 case 'f': Data += '\f'; break;
1755 case 'n': Data += '\n'; break;
1756 case 'r': Data += '\r'; break;
1757 case 't': Data += '\t'; break;
1758 case '"': Data += '"'; break;
1759 case '\\': Data += '\\'; break;
1766 /// ParseDirectiveAscii:
1767 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1768 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1769 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1770 CheckForValidSection();
1773 if (getLexer().isNot(AsmToken::String))
1774 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1777 if (ParseEscapedString(Data))
1780 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1782 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1786 if (getLexer().is(AsmToken::EndOfStatement))
1789 if (getLexer().isNot(AsmToken::Comma))
1790 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1799 /// ParseDirectiveValue
1800 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1801 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1802 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1803 CheckForValidSection();
1806 const MCExpr *Value;
1807 SMLoc ExprLoc = getLexer().getLoc();
1808 if (ParseExpression(Value))
1811 // Special case constant expressions to match code generator.
1812 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1813 assert(Size <= 8 && "Invalid size");
1814 uint64_t IntValue = MCE->getValue();
1815 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1816 return Error(ExprLoc, "literal value out of range for directive");
1817 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1819 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1821 if (getLexer().is(AsmToken::EndOfStatement))
1824 // FIXME: Improve diagnostic.
1825 if (getLexer().isNot(AsmToken::Comma))
1826 return TokError("unexpected token in directive");
1835 /// ParseDirectiveRealValue
1836 /// ::= (.single | .double) [ expression (, expression)* ]
1837 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1838 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1839 CheckForValidSection();
1842 // We don't truly support arithmetic on floating point expressions, so we
1843 // have to manually parse unary prefixes.
1845 if (getLexer().is(AsmToken::Minus)) {
1848 } else if (getLexer().is(AsmToken::Plus))
1851 if (getLexer().isNot(AsmToken::Integer) &&
1852 getLexer().isNot(AsmToken::Real) &&
1853 getLexer().isNot(AsmToken::Identifier))
1854 return TokError("unexpected token in directive");
1856 // Convert to an APFloat.
1857 APFloat Value(Semantics);
1858 StringRef IDVal = getTok().getString();
1859 if (getLexer().is(AsmToken::Identifier)) {
1860 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1861 Value = APFloat::getInf(Semantics);
1862 else if (!IDVal.compare_lower("nan"))
1863 Value = APFloat::getNaN(Semantics, false, ~0);
1865 return TokError("invalid floating point literal");
1866 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1867 APFloat::opInvalidOp)
1868 return TokError("invalid floating point literal");
1872 // Consume the numeric token.
1875 // Emit the value as an integer.
1876 APInt AsInt = Value.bitcastToAPInt();
1877 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1878 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1880 if (getLexer().is(AsmToken::EndOfStatement))
1883 if (getLexer().isNot(AsmToken::Comma))
1884 return TokError("unexpected token in directive");
1893 /// ParseDirectiveSpace
1894 /// ::= .space expression [ , expression ]
1895 bool AsmParser::ParseDirectiveSpace() {
1896 CheckForValidSection();
1899 if (ParseAbsoluteExpression(NumBytes))
1902 int64_t FillExpr = 0;
1903 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1904 if (getLexer().isNot(AsmToken::Comma))
1905 return TokError("unexpected token in '.space' directive");
1908 if (ParseAbsoluteExpression(FillExpr))
1911 if (getLexer().isNot(AsmToken::EndOfStatement))
1912 return TokError("unexpected token in '.space' directive");
1918 return TokError("invalid number of bytes in '.space' directive");
1920 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1921 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1926 /// ParseDirectiveZero
1927 /// ::= .zero expression
1928 bool AsmParser::ParseDirectiveZero() {
1929 CheckForValidSection();
1932 if (ParseAbsoluteExpression(NumBytes))
1936 if (getLexer().is(AsmToken::Comma)) {
1938 if (ParseAbsoluteExpression(Val))
1942 if (getLexer().isNot(AsmToken::EndOfStatement))
1943 return TokError("unexpected token in '.zero' directive");
1947 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1952 /// ParseDirectiveFill
1953 /// ::= .fill expression , expression , expression
1954 bool AsmParser::ParseDirectiveFill() {
1955 CheckForValidSection();
1958 if (ParseAbsoluteExpression(NumValues))
1961 if (getLexer().isNot(AsmToken::Comma))
1962 return TokError("unexpected token in '.fill' directive");
1966 if (ParseAbsoluteExpression(FillSize))
1969 if (getLexer().isNot(AsmToken::Comma))
1970 return TokError("unexpected token in '.fill' directive");
1974 if (ParseAbsoluteExpression(FillExpr))
1977 if (getLexer().isNot(AsmToken::EndOfStatement))
1978 return TokError("unexpected token in '.fill' directive");
1982 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1983 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1985 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1986 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1991 /// ParseDirectiveOrg
1992 /// ::= .org expression [ , expression ]
1993 bool AsmParser::ParseDirectiveOrg() {
1994 CheckForValidSection();
1996 const MCExpr *Offset;
1997 SMLoc Loc = getTok().getLoc();
1998 if (ParseExpression(Offset))
2001 // Parse optional fill expression.
2002 int64_t FillExpr = 0;
2003 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2004 if (getLexer().isNot(AsmToken::Comma))
2005 return TokError("unexpected token in '.org' directive");
2008 if (ParseAbsoluteExpression(FillExpr))
2011 if (getLexer().isNot(AsmToken::EndOfStatement))
2012 return TokError("unexpected token in '.org' directive");
2017 // Only limited forms of relocatable expressions are accepted here, it
2018 // has to be relative to the current section. The streamer will return
2019 // 'true' if the expression wasn't evaluatable.
2020 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2021 return Error(Loc, "expected assembly-time absolute expression");
2026 /// ParseDirectiveAlign
2027 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2028 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2029 CheckForValidSection();
2031 SMLoc AlignmentLoc = getLexer().getLoc();
2033 if (ParseAbsoluteExpression(Alignment))
2037 bool HasFillExpr = false;
2038 int64_t FillExpr = 0;
2039 int64_t MaxBytesToFill = 0;
2040 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2041 if (getLexer().isNot(AsmToken::Comma))
2042 return TokError("unexpected token in directive");
2045 // The fill expression can be omitted while specifying a maximum number of
2046 // alignment bytes, e.g:
2048 if (getLexer().isNot(AsmToken::Comma)) {
2050 if (ParseAbsoluteExpression(FillExpr))
2054 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2055 if (getLexer().isNot(AsmToken::Comma))
2056 return TokError("unexpected token in directive");
2059 MaxBytesLoc = getLexer().getLoc();
2060 if (ParseAbsoluteExpression(MaxBytesToFill))
2063 if (getLexer().isNot(AsmToken::EndOfStatement))
2064 return TokError("unexpected token in directive");
2073 // Compute alignment in bytes.
2075 // FIXME: Diagnose overflow.
2076 if (Alignment >= 32) {
2077 Error(AlignmentLoc, "invalid alignment value");
2081 Alignment = 1ULL << Alignment;
2084 // Diagnose non-sensical max bytes to align.
2085 if (MaxBytesLoc.isValid()) {
2086 if (MaxBytesToFill < 1) {
2087 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2088 "many bytes, ignoring maximum bytes expression");
2092 if (MaxBytesToFill >= Alignment) {
2093 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2099 // Check whether we should use optimal code alignment for this .align
2101 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2102 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2103 ValueSize == 1 && UseCodeAlign) {
2104 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2106 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2107 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2114 /// ParseDirectiveSymbolAttribute
2115 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2116 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2117 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2120 SMLoc Loc = getTok().getLoc();
2122 if (ParseIdentifier(Name))
2123 return Error(Loc, "expected identifier in directive");
2125 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2127 // Assembler local symbols don't make any sense here. Complain loudly.
2128 if (Sym->isTemporary())
2129 return Error(Loc, "non-local symbol required in directive");
2131 getStreamer().EmitSymbolAttribute(Sym, Attr);
2133 if (getLexer().is(AsmToken::EndOfStatement))
2136 if (getLexer().isNot(AsmToken::Comma))
2137 return TokError("unexpected token in directive");
2146 /// ParseDirectiveComm
2147 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2148 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2149 CheckForValidSection();
2151 SMLoc IDLoc = getLexer().getLoc();
2153 if (ParseIdentifier(Name))
2154 return TokError("expected identifier in directive");
2156 // Handle the identifier as the key symbol.
2157 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2159 if (getLexer().isNot(AsmToken::Comma))
2160 return TokError("unexpected token in directive");
2164 SMLoc SizeLoc = getLexer().getLoc();
2165 if (ParseAbsoluteExpression(Size))
2168 int64_t Pow2Alignment = 0;
2169 SMLoc Pow2AlignmentLoc;
2170 if (getLexer().is(AsmToken::Comma)) {
2172 Pow2AlignmentLoc = getLexer().getLoc();
2173 if (ParseAbsoluteExpression(Pow2Alignment))
2176 // If this target takes alignments in bytes (not log) validate and convert.
2177 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2178 if (!isPowerOf2_64(Pow2Alignment))
2179 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2180 Pow2Alignment = Log2_64(Pow2Alignment);
2184 if (getLexer().isNot(AsmToken::EndOfStatement))
2185 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2189 // NOTE: a size of zero for a .comm should create a undefined symbol
2190 // but a size of .lcomm creates a bss symbol of size zero.
2192 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2193 "be less than zero");
2195 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2196 // may internally end up wanting an alignment in bytes.
2197 // FIXME: Diagnose overflow.
2198 if (Pow2Alignment < 0)
2199 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2200 "alignment, can't be less than zero");
2202 if (!Sym->isUndefined())
2203 return Error(IDLoc, "invalid symbol redefinition");
2205 // '.lcomm' is equivalent to '.zerofill'.
2206 // Create the Symbol as a common or local common with Size and Pow2Alignment
2208 getStreamer().EmitZerofill(Ctx.getMachOSection(
2209 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2210 0, SectionKind::getBSS()),
2211 Sym, Size, 1 << Pow2Alignment);
2215 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2219 /// ParseDirectiveAbort
2220 /// ::= .abort [... message ...]
2221 bool AsmParser::ParseDirectiveAbort() {
2222 // FIXME: Use loc from directive.
2223 SMLoc Loc = getLexer().getLoc();
2225 StringRef Str = ParseStringToEndOfStatement();
2226 if (getLexer().isNot(AsmToken::EndOfStatement))
2227 return TokError("unexpected token in '.abort' directive");
2232 Error(Loc, ".abort detected. Assembly stopping.");
2234 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2235 // FIXME: Actually abort assembly here.
2240 /// ParseDirectiveInclude
2241 /// ::= .include "filename"
2242 bool AsmParser::ParseDirectiveInclude() {
2243 if (getLexer().isNot(AsmToken::String))
2244 return TokError("expected string in '.include' directive");
2246 std::string Filename = getTok().getString();
2247 SMLoc IncludeLoc = getLexer().getLoc();
2250 if (getLexer().isNot(AsmToken::EndOfStatement))
2251 return TokError("unexpected token in '.include' directive");
2253 // Strip the quotes.
2254 Filename = Filename.substr(1, Filename.size()-2);
2256 // Attempt to switch the lexer to the included file before consuming the end
2257 // of statement to avoid losing it when we switch.
2258 if (EnterIncludeFile(Filename)) {
2259 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2266 /// ParseDirectiveIncbin
2267 /// ::= .incbin "filename"
2268 bool AsmParser::ParseDirectiveIncbin() {
2269 if (getLexer().isNot(AsmToken::String))
2270 return TokError("expected string in '.incbin' directive");
2272 std::string Filename = getTok().getString();
2273 SMLoc IncbinLoc = getLexer().getLoc();
2276 if (getLexer().isNot(AsmToken::EndOfStatement))
2277 return TokError("unexpected token in '.incbin' directive");
2279 // Strip the quotes.
2280 Filename = Filename.substr(1, Filename.size()-2);
2282 // Attempt to process the included file.
2283 if (ProcessIncbinFile(Filename)) {
2284 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2291 /// ParseDirectiveIf
2292 /// ::= .if expression
2293 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2294 TheCondStack.push_back(TheCondState);
2295 TheCondState.TheCond = AsmCond::IfCond;
2296 if(TheCondState.Ignore) {
2297 EatToEndOfStatement();
2301 if (ParseAbsoluteExpression(ExprValue))
2304 if (getLexer().isNot(AsmToken::EndOfStatement))
2305 return TokError("unexpected token in '.if' directive");
2309 TheCondState.CondMet = ExprValue;
2310 TheCondState.Ignore = !TheCondState.CondMet;
2316 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2318 TheCondStack.push_back(TheCondState);
2319 TheCondState.TheCond = AsmCond::IfCond;
2321 if (TheCondState.Ignore) {
2322 EatToEndOfStatement();
2324 if (ParseIdentifier(Name))
2325 return TokError("expected identifier after '.ifdef'");
2329 MCSymbol *Sym = getContext().LookupSymbol(Name);
2332 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2334 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2335 TheCondState.Ignore = !TheCondState.CondMet;
2341 /// ParseDirectiveElseIf
2342 /// ::= .elseif expression
2343 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2344 if (TheCondState.TheCond != AsmCond::IfCond &&
2345 TheCondState.TheCond != AsmCond::ElseIfCond)
2346 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2348 TheCondState.TheCond = AsmCond::ElseIfCond;
2350 bool LastIgnoreState = false;
2351 if (!TheCondStack.empty())
2352 LastIgnoreState = TheCondStack.back().Ignore;
2353 if (LastIgnoreState || TheCondState.CondMet) {
2354 TheCondState.Ignore = true;
2355 EatToEndOfStatement();
2359 if (ParseAbsoluteExpression(ExprValue))
2362 if (getLexer().isNot(AsmToken::EndOfStatement))
2363 return TokError("unexpected token in '.elseif' directive");
2366 TheCondState.CondMet = ExprValue;
2367 TheCondState.Ignore = !TheCondState.CondMet;
2373 /// ParseDirectiveElse
2375 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2376 if (getLexer().isNot(AsmToken::EndOfStatement))
2377 return TokError("unexpected token in '.else' directive");
2381 if (TheCondState.TheCond != AsmCond::IfCond &&
2382 TheCondState.TheCond != AsmCond::ElseIfCond)
2383 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2385 TheCondState.TheCond = AsmCond::ElseCond;
2386 bool LastIgnoreState = false;
2387 if (!TheCondStack.empty())
2388 LastIgnoreState = TheCondStack.back().Ignore;
2389 if (LastIgnoreState || TheCondState.CondMet)
2390 TheCondState.Ignore = true;
2392 TheCondState.Ignore = false;
2397 /// ParseDirectiveEndIf
2399 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2400 if (getLexer().isNot(AsmToken::EndOfStatement))
2401 return TokError("unexpected token in '.endif' directive");
2405 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2406 TheCondStack.empty())
2407 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2409 if (!TheCondStack.empty()) {
2410 TheCondState = TheCondStack.back();
2411 TheCondStack.pop_back();
2417 /// ParseDirectiveFile
2418 /// ::= .file [number] filename
2419 /// ::= .file number directory filename
2420 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2421 // FIXME: I'm not sure what this is.
2422 int64_t FileNumber = -1;
2423 SMLoc FileNumberLoc = getLexer().getLoc();
2424 if (getLexer().is(AsmToken::Integer)) {
2425 FileNumber = getTok().getIntVal();
2429 return TokError("file number less than one");
2432 if (getLexer().isNot(AsmToken::String))
2433 return TokError("unexpected token in '.file' directive");
2435 // Usually the directory and filename together, otherwise just the directory.
2436 StringRef Path = getTok().getString();
2437 Path = Path.substr(1, Path.size()-2);
2440 StringRef Directory;
2442 if (getLexer().is(AsmToken::String)) {
2443 if (FileNumber == -1)
2444 return TokError("explicit path specified, but no file number");
2445 Filename = getTok().getString();
2446 Filename = Filename.substr(1, Filename.size()-2);
2453 if (getLexer().isNot(AsmToken::EndOfStatement))
2454 return TokError("unexpected token in '.file' directive");
2456 if (FileNumber == -1)
2457 getStreamer().EmitFileDirective(Filename);
2459 if (getContext().getGenDwarfForAssembly() == true)
2460 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2461 "used to generate dwarf debug info for assembly code");
2463 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2464 Error(FileNumberLoc, "file number already allocated");
2470 /// ParseDirectiveLine
2471 /// ::= .line [number]
2472 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2473 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2474 if (getLexer().isNot(AsmToken::Integer))
2475 return TokError("unexpected token in '.line' directive");
2477 int64_t LineNumber = getTok().getIntVal();
2481 // FIXME: Do something with the .line.
2484 if (getLexer().isNot(AsmToken::EndOfStatement))
2485 return TokError("unexpected token in '.line' directive");
2491 /// ParseDirectiveLoc
2492 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2493 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2494 /// The first number is a file number, must have been previously assigned with
2495 /// a .file directive, the second number is the line number and optionally the
2496 /// third number is a column position (zero if not specified). The remaining
2497 /// optional items are .loc sub-directives.
2498 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2500 if (getLexer().isNot(AsmToken::Integer))
2501 return TokError("unexpected token in '.loc' directive");
2502 int64_t FileNumber = getTok().getIntVal();
2504 return TokError("file number less than one in '.loc' directive");
2505 if (!getContext().isValidDwarfFileNumber(FileNumber))
2506 return TokError("unassigned file number in '.loc' directive");
2509 int64_t LineNumber = 0;
2510 if (getLexer().is(AsmToken::Integer)) {
2511 LineNumber = getTok().getIntVal();
2513 return TokError("line number less than one in '.loc' directive");
2517 int64_t ColumnPos = 0;
2518 if (getLexer().is(AsmToken::Integer)) {
2519 ColumnPos = getTok().getIntVal();
2521 return TokError("column position less than zero in '.loc' directive");
2525 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2527 int64_t Discriminator = 0;
2528 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2530 if (getLexer().is(AsmToken::EndOfStatement))
2534 SMLoc Loc = getTok().getLoc();
2535 if (getParser().ParseIdentifier(Name))
2536 return TokError("unexpected token in '.loc' directive");
2538 if (Name == "basic_block")
2539 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2540 else if (Name == "prologue_end")
2541 Flags |= DWARF2_FLAG_PROLOGUE_END;
2542 else if (Name == "epilogue_begin")
2543 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2544 else if (Name == "is_stmt") {
2545 SMLoc Loc = getTok().getLoc();
2546 const MCExpr *Value;
2547 if (getParser().ParseExpression(Value))
2549 // The expression must be the constant 0 or 1.
2550 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2551 int Value = MCE->getValue();
2553 Flags &= ~DWARF2_FLAG_IS_STMT;
2554 else if (Value == 1)
2555 Flags |= DWARF2_FLAG_IS_STMT;
2557 return Error(Loc, "is_stmt value not 0 or 1");
2560 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2563 else if (Name == "isa") {
2564 SMLoc Loc = getTok().getLoc();
2565 const MCExpr *Value;
2566 if (getParser().ParseExpression(Value))
2568 // The expression must be a constant greater or equal to 0.
2569 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2570 int Value = MCE->getValue();
2572 return Error(Loc, "isa number less than zero");
2576 return Error(Loc, "isa number not a constant value");
2579 else if (Name == "discriminator") {
2580 if (getParser().ParseAbsoluteExpression(Discriminator))
2584 return Error(Loc, "unknown sub-directive in '.loc' directive");
2587 if (getLexer().is(AsmToken::EndOfStatement))
2592 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2593 Isa, Discriminator, StringRef());
2598 /// ParseDirectiveStabs
2599 /// ::= .stabs string, number, number, number
2600 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2601 SMLoc DirectiveLoc) {
2602 return TokError("unsupported directive '" + Directive + "'");
2605 /// ParseDirectiveCFISections
2606 /// ::= .cfi_sections section [, section]
2607 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2608 SMLoc DirectiveLoc) {
2613 if (getParser().ParseIdentifier(Name))
2614 return TokError("Expected an identifier");
2616 if (Name == ".eh_frame")
2618 else if (Name == ".debug_frame")
2621 if (getLexer().is(AsmToken::Comma)) {
2624 if (getParser().ParseIdentifier(Name))
2625 return TokError("Expected an identifier");
2627 if (Name == ".eh_frame")
2629 else if (Name == ".debug_frame")
2633 getStreamer().EmitCFISections(EH, Debug);
2638 /// ParseDirectiveCFIStartProc
2639 /// ::= .cfi_startproc
2640 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2641 SMLoc DirectiveLoc) {
2642 getStreamer().EmitCFIStartProc();
2646 /// ParseDirectiveCFIEndProc
2647 /// ::= .cfi_endproc
2648 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2649 getStreamer().EmitCFIEndProc();
2653 /// ParseRegisterOrRegisterNumber - parse register name or number.
2654 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2655 SMLoc DirectiveLoc) {
2658 if (getLexer().isNot(AsmToken::Integer)) {
2659 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2662 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2664 return getParser().ParseAbsoluteExpression(Register);
2669 /// ParseDirectiveCFIDefCfa
2670 /// ::= .cfi_def_cfa register, offset
2671 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2672 SMLoc DirectiveLoc) {
2673 int64_t Register = 0;
2674 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2677 if (getLexer().isNot(AsmToken::Comma))
2678 return TokError("unexpected token in directive");
2682 if (getParser().ParseAbsoluteExpression(Offset))
2685 getStreamer().EmitCFIDefCfa(Register, Offset);
2689 /// ParseDirectiveCFIDefCfaOffset
2690 /// ::= .cfi_def_cfa_offset offset
2691 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2692 SMLoc DirectiveLoc) {
2694 if (getParser().ParseAbsoluteExpression(Offset))
2697 getStreamer().EmitCFIDefCfaOffset(Offset);
2701 /// ParseDirectiveCFIAdjustCfaOffset
2702 /// ::= .cfi_adjust_cfa_offset adjustment
2703 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2704 SMLoc DirectiveLoc) {
2705 int64_t Adjustment = 0;
2706 if (getParser().ParseAbsoluteExpression(Adjustment))
2709 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2713 /// ParseDirectiveCFIDefCfaRegister
2714 /// ::= .cfi_def_cfa_register register
2715 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2716 SMLoc DirectiveLoc) {
2717 int64_t Register = 0;
2718 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2721 getStreamer().EmitCFIDefCfaRegister(Register);
2725 /// ParseDirectiveCFIOffset
2726 /// ::= .cfi_offset register, offset
2727 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2728 int64_t Register = 0;
2731 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2734 if (getLexer().isNot(AsmToken::Comma))
2735 return TokError("unexpected token in directive");
2738 if (getParser().ParseAbsoluteExpression(Offset))
2741 getStreamer().EmitCFIOffset(Register, Offset);
2745 /// ParseDirectiveCFIRelOffset
2746 /// ::= .cfi_rel_offset register, offset
2747 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2748 SMLoc DirectiveLoc) {
2749 int64_t Register = 0;
2751 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2754 if (getLexer().isNot(AsmToken::Comma))
2755 return TokError("unexpected token in directive");
2759 if (getParser().ParseAbsoluteExpression(Offset))
2762 getStreamer().EmitCFIRelOffset(Register, Offset);
2766 static bool isValidEncoding(int64_t Encoding) {
2767 if (Encoding & ~0xff)
2770 if (Encoding == dwarf::DW_EH_PE_omit)
2773 const unsigned Format = Encoding & 0xf;
2774 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2775 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2776 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2777 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2780 const unsigned Application = Encoding & 0x70;
2781 if (Application != dwarf::DW_EH_PE_absptr &&
2782 Application != dwarf::DW_EH_PE_pcrel)
2788 /// ParseDirectiveCFIPersonalityOrLsda
2789 /// ::= .cfi_personality encoding, [symbol_name]
2790 /// ::= .cfi_lsda encoding, [symbol_name]
2791 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2792 SMLoc DirectiveLoc) {
2793 int64_t Encoding = 0;
2794 if (getParser().ParseAbsoluteExpression(Encoding))
2796 if (Encoding == dwarf::DW_EH_PE_omit)
2799 if (!isValidEncoding(Encoding))
2800 return TokError("unsupported encoding.");
2802 if (getLexer().isNot(AsmToken::Comma))
2803 return TokError("unexpected token in directive");
2807 if (getParser().ParseIdentifier(Name))
2808 return TokError("expected identifier in directive");
2810 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2812 if (IDVal == ".cfi_personality")
2813 getStreamer().EmitCFIPersonality(Sym, Encoding);
2815 assert(IDVal == ".cfi_lsda");
2816 getStreamer().EmitCFILsda(Sym, Encoding);
2821 /// ParseDirectiveCFIRememberState
2822 /// ::= .cfi_remember_state
2823 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2824 SMLoc DirectiveLoc) {
2825 getStreamer().EmitCFIRememberState();
2829 /// ParseDirectiveCFIRestoreState
2830 /// ::= .cfi_remember_state
2831 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2832 SMLoc DirectiveLoc) {
2833 getStreamer().EmitCFIRestoreState();
2837 /// ParseDirectiveCFISameValue
2838 /// ::= .cfi_same_value register
2839 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2840 SMLoc DirectiveLoc) {
2841 int64_t Register = 0;
2843 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2846 getStreamer().EmitCFISameValue(Register);
2851 /// ParseDirectiveCFIRestore
2852 /// ::= .cfi_restore register
2853 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
2854 SMLoc DirectiveLoc) {
2855 int64_t Register = 0;
2856 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2859 getStreamer().EmitCFIRestore(Register);
2864 /// ParseDirectiveCFIEscape
2865 /// ::= .cfi_escape expression[,...]
2866 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
2867 SMLoc DirectiveLoc) {
2870 if (getParser().ParseAbsoluteExpression(CurrValue))
2873 Values.push_back((uint8_t)CurrValue);
2875 while (getLexer().is(AsmToken::Comma)) {
2878 if (getParser().ParseAbsoluteExpression(CurrValue))
2881 Values.push_back((uint8_t)CurrValue);
2884 getStreamer().EmitCFIEscape(Values);
2888 /// ParseDirectiveCFISignalFrame
2889 /// ::= .cfi_signal_frame
2890 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
2891 SMLoc DirectiveLoc) {
2892 if (getLexer().isNot(AsmToken::EndOfStatement))
2893 return Error(getLexer().getLoc(),
2894 "unexpected token in '" + Directive + "' directive");
2896 getStreamer().EmitCFISignalFrame();
2901 /// ParseDirectiveMacrosOnOff
2904 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2905 SMLoc DirectiveLoc) {
2906 if (getLexer().isNot(AsmToken::EndOfStatement))
2907 return Error(getLexer().getLoc(),
2908 "unexpected token in '" + Directive + "' directive");
2910 getParser().MacrosEnabled = Directive == ".macros_on";
2915 /// ParseDirectiveMacro
2916 /// ::= .macro name [parameters]
2917 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2918 SMLoc DirectiveLoc) {
2920 if (getParser().ParseIdentifier(Name))
2921 return TokError("expected identifier in directive");
2923 std::vector<StringRef> Parameters;
2924 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2926 StringRef Parameter;
2927 if (getParser().ParseIdentifier(Parameter))
2928 return TokError("expected identifier in directive");
2929 Parameters.push_back(Parameter);
2931 if (getLexer().isNot(AsmToken::Comma))
2937 if (getLexer().isNot(AsmToken::EndOfStatement))
2938 return TokError("unexpected token in '.macro' directive");
2940 // Eat the end of statement.
2943 AsmToken EndToken, StartToken = getTok();
2945 // Lex the macro definition.
2947 // Check whether we have reached the end of the file.
2948 if (getLexer().is(AsmToken::Eof))
2949 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2951 // Otherwise, check whether we have reach the .endmacro.
2952 if (getLexer().is(AsmToken::Identifier) &&
2953 (getTok().getIdentifier() == ".endm" ||
2954 getTok().getIdentifier() == ".endmacro")) {
2955 EndToken = getTok();
2957 if (getLexer().isNot(AsmToken::EndOfStatement))
2958 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2963 // Otherwise, scan til the end of the statement.
2964 getParser().EatToEndOfStatement();
2967 if (getParser().MacroMap.lookup(Name)) {
2968 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2971 const char *BodyStart = StartToken.getLoc().getPointer();
2972 const char *BodyEnd = EndToken.getLoc().getPointer();
2973 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2974 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
2978 /// ParseDirectiveEndMacro
2981 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2982 SMLoc DirectiveLoc) {
2983 if (getLexer().isNot(AsmToken::EndOfStatement))
2984 return TokError("unexpected token in '" + Directive + "' directive");
2986 // If we are inside a macro instantiation, terminate the current
2988 if (!getParser().ActiveMacros.empty()) {
2989 getParser().HandleMacroExit();
2993 // Otherwise, this .endmacro is a stray entry in the file; well formed
2994 // .endmacro directives are handled during the macro definition parsing.
2995 return TokError("unexpected '" + Directive + "' in file, "
2996 "no current macro definition");
2999 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3000 getParser().CheckForValidSection();
3002 const MCExpr *Value;
3004 if (getParser().ParseExpression(Value))
3007 if (getLexer().isNot(AsmToken::EndOfStatement))
3008 return TokError("unexpected token in directive");
3010 if (DirName[1] == 's')
3011 getStreamer().EmitSLEB128Value(Value);
3013 getStreamer().EmitULEB128Value(Value);
3019 /// \brief Create an MCAsmParser instance.
3020 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3021 MCContext &C, MCStreamer &Out,
3022 const MCAsmInfo &MAI) {
3023 return new AsmParser(SM, C, Out, MAI);