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/MCInstPrinter.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCParser/AsmCond.h"
25 #include "llvm/MC/MCParser/AsmLexer.h"
26 #include "llvm/MC/MCParser/MCAsmParser.h"
27 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSectionMachO.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/MC/MCTargetAsmParser.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/raw_ostream.h"
46 FatalAssemblerWarnings("fatal-assembler-warnings",
47 cl::desc("Consider warnings as error"));
49 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
53 /// \brief Helper class for tracking macro definitions.
54 typedef std::vector<AsmToken> MacroArgument;
55 typedef std::vector<MacroArgument> MacroArguments;
56 typedef std::pair<StringRef, MacroArgument> MacroParameter;
57 typedef std::vector<MacroParameter> MacroParameters;
62 MacroParameters Parameters;
65 Macro(StringRef N, StringRef B, const MacroParameters &P) :
66 Name(N), Body(B), Parameters(P) {}
69 /// \brief Helper class for storing information about an active macro
71 struct MacroInstantiation {
72 /// The macro being instantiated.
73 const Macro *TheMacro;
75 /// The macro instantiation with substitutions.
76 MemoryBuffer *Instantiation;
78 /// The location of the instantiation.
79 SMLoc InstantiationLoc;
81 /// The buffer where parsing should resume upon instantiation completion.
84 /// The location where parsing should resume upon instantiation completion.
88 MacroInstantiation(const Macro *M, SMLoc IL, int EB, SMLoc EL,
93 struct ParseStatementInfo {
94 /// ParsedOperands - The parsed operands from the last parsed statement.
95 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
97 /// Opcode - The opcode from the last parsed instruction.
100 /// Error - Was there an error parsing the inline assembly?
103 SmallVectorImpl<AsmRewrite> *AsmRewrites;
105 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
106 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
107 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
109 ~ParseStatementInfo() {
110 // Free any parsed operands.
111 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
112 delete ParsedOperands[i];
113 ParsedOperands.clear();
117 /// \brief The concrete assembly parser instance.
118 class AsmParser : public MCAsmParser {
119 friend class GenericAsmParser;
121 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
122 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
127 const MCAsmInfo &MAI;
129 SourceMgr::DiagHandlerTy SavedDiagHandler;
130 void *SavedDiagContext;
131 MCAsmParserExtension *GenericParser;
132 MCAsmParserExtension *PlatformParser;
134 /// This is the current buffer index we're lexing from as managed by the
135 /// SourceMgr object.
138 AsmCond TheCondState;
139 std::vector<AsmCond> TheCondStack;
141 /// DirectiveMap - This is a table handlers for directives. Each handler is
142 /// invoked after the directive identifier is read and is responsible for
143 /// parsing and validating the rest of the directive. The handler is passed
144 /// in the directive name and the location of the directive keyword.
145 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
147 /// MacroMap - Map of currently defined macros.
148 StringMap<Macro*> MacroMap;
150 /// ActiveMacros - Stack of active macro instantiations.
151 std::vector<MacroInstantiation*> ActiveMacros;
153 /// Boolean tracking whether macro substitution is enabled.
154 unsigned MacrosEnabled : 1;
156 /// Flag tracking whether any errors have been encountered.
157 unsigned HadError : 1;
159 /// The values from the last parsed cpp hash file line comment if any.
160 StringRef CppHashFilename;
161 int64_t CppHashLineNumber;
165 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
166 unsigned AssemblerDialect;
168 /// IsDarwin - is Darwin compatibility enabled?
171 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
172 bool ParsingInlineAsm;
175 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
176 const MCAsmInfo &MAI);
177 virtual ~AsmParser();
179 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
181 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
183 DirectiveHandler Handler) {
184 DirectiveMap[Directive] = std::make_pair(Object, Handler);
188 /// @name MCAsmParser Interface
191 virtual SourceMgr &getSourceManager() { return SrcMgr; }
192 virtual MCAsmLexer &getLexer() { return Lexer; }
193 virtual MCContext &getContext() { return Ctx; }
194 virtual MCStreamer &getStreamer() { return Out; }
195 virtual unsigned getAssemblerDialect() {
196 if (AssemblerDialect == ~0U)
197 return MAI.getAssemblerDialect();
199 return AssemblerDialect;
201 virtual void setAssemblerDialect(unsigned i) {
202 AssemblerDialect = i;
205 virtual bool Warning(SMLoc L, const Twine &Msg,
206 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
207 virtual bool Error(SMLoc L, const Twine &Msg,
208 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
210 virtual const AsmToken &Lex();
212 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
213 bool isParsingInlineAsm() { return ParsingInlineAsm; }
215 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
216 unsigned &NumOutputs, unsigned &NumInputs,
217 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
218 SmallVectorImpl<std::string> &Constraints,
219 SmallVectorImpl<std::string> &Clobbers,
220 const MCInstrInfo *MII,
221 const MCInstPrinter *IP,
222 MCAsmParserSemaCallback &SI);
224 bool ParseExpression(const MCExpr *&Res);
225 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
226 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
227 virtual bool ParseAbsoluteExpression(int64_t &Res);
232 void CheckForValidSection();
234 bool ParseStatement(ParseStatementInfo &Info);
235 void EatToEndOfLine();
236 bool ParseCppHashLineFilenameComment(const SMLoc &L);
238 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
239 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
240 const MacroParameters &Parameters,
241 const MacroArguments &A,
243 void HandleMacroExit();
245 void PrintMacroInstantiations();
246 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
247 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
248 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
250 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
252 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
253 bool EnterIncludeFile(const std::string &Filename);
254 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
255 /// This returns true on failure.
256 bool ProcessIncbinFile(const std::string &Filename);
258 /// \brief Reset the current lexer position to that given by \p Loc. The
259 /// current token is not set; clients should ensure Lex() is called
262 /// \param InBuffer If not -1, should be the known buffer id that contains the
264 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
266 virtual void EatToEndOfStatement();
268 bool ParseMacroArgument(MacroArgument &MA,
269 AsmToken::TokenKind &ArgumentDelimiter);
270 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
272 /// \brief Parse up to the end of statement and a return the contents from the
273 /// current token until the end of the statement; the current token on exit
274 /// will be either the EndOfStatement or EOF.
275 virtual StringRef ParseStringToEndOfStatement();
277 /// \brief Parse until the end of a statement or a comma is encountered,
278 /// return the contents from the current token up to the end or comma.
279 StringRef ParseStringToComma();
281 bool ParseAssignment(StringRef Name, bool allow_redef,
282 bool NoDeadStrip = false);
284 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
285 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
286 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
287 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
289 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
290 /// and set \p Res to the identifier contents.
291 virtual bool ParseIdentifier(StringRef &Res);
293 // Directive Parsing.
295 // ".ascii", ".asciiz", ".string"
296 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
297 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
298 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
299 bool ParseDirectiveFill(); // ".fill"
300 bool ParseDirectiveSpace(); // ".space"
301 bool ParseDirectiveZero(); // ".zero"
302 // ".set", ".equ", ".equiv"
303 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
304 bool ParseDirectiveOrg(); // ".org"
305 // ".align{,32}", ".p2align{,w,l}"
306 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
308 // ".bundle_align_mode"
309 bool ParseDirectiveBundleAlignMode();
311 bool ParseDirectiveBundleLock();
313 bool ParseDirectiveBundleUnlock();
315 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
316 /// accepts a single symbol (which should be a label or an external).
317 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
319 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
321 bool ParseDirectiveAbort(); // ".abort"
322 bool ParseDirectiveInclude(); // ".include"
323 bool ParseDirectiveIncbin(); // ".incbin"
325 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
326 // ".ifb" or ".ifnb", depending on ExpectBlank.
327 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
328 // ".ifc" or ".ifnc", depending on ExpectEqual.
329 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
330 // ".ifdef" or ".ifndef", depending on expect_defined
331 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
332 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
333 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
334 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
336 /// ParseEscapedString - Parse the current token as a string which may include
337 /// escaped characters and return the string contents.
338 bool ParseEscapedString(std::string &Data);
340 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
341 MCSymbolRefExpr::VariantKind Variant);
343 // Macro-like directives
344 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
345 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
346 raw_svector_ostream &OS);
347 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
348 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
349 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
350 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
353 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
356 /// \brief Generic implementations of directive handling, etc. which is shared
357 /// (or the default, at least) for all assembler parser.
358 class GenericAsmParser : public MCAsmParserExtension {
359 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
360 void AddDirectiveHandler(StringRef Directive) {
361 getParser().AddDirectiveHandler(this, Directive,
362 HandleDirective<GenericAsmParser, Handler>);
365 GenericAsmParser() {}
367 AsmParser &getParser() {
368 return (AsmParser&) this->MCAsmParserExtension::getParser();
371 virtual void Initialize(MCAsmParser &Parser) {
372 // Call the base implementation.
373 this->MCAsmParserExtension::Initialize(Parser);
375 // Debugging directives.
376 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
377 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
378 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
379 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
382 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
384 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
386 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
388 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
390 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
391 ".cfi_def_cfa_offset");
392 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
393 ".cfi_adjust_cfa_offset");
394 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
395 ".cfi_def_cfa_register");
396 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
398 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
401 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
403 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
405 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
407 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
409 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
411 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
413 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
415 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
417 &GenericAsmParser::ParseDirectiveCFIUndefined>(".cfi_undefined");
419 &GenericAsmParser::ParseDirectiveCFIRegister>(".cfi_register");
422 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
424 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
426 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
427 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
428 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
429 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
431 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
432 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
435 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
437 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
438 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
439 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
440 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
441 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
442 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
443 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
444 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
445 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
446 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
447 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
448 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
449 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
450 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
451 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
452 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
453 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
454 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
455 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
456 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
457 bool ParseDirectiveCFIUndefined(StringRef, SMLoc DirectiveLoc);
458 bool ParseDirectiveCFIRegister(StringRef, SMLoc DirectiveLoc);
460 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
461 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
462 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
463 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
465 bool ParseDirectiveLEB128(StringRef, SMLoc);
472 extern MCAsmParserExtension *createDarwinAsmParser();
473 extern MCAsmParserExtension *createELFAsmParser();
474 extern MCAsmParserExtension *createCOFFAsmParser();
478 enum { DEFAULT_ADDRSPACE = 0 };
480 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
481 MCStreamer &_Out, const MCAsmInfo &_MAI)
482 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
483 GenericParser(new GenericAsmParser), PlatformParser(0),
484 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
485 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
486 // Save the old handler.
487 SavedDiagHandler = SrcMgr.getDiagHandler();
488 SavedDiagContext = SrcMgr.getDiagContext();
489 // Set our own handler which calls the saved handler.
490 SrcMgr.setDiagHandler(DiagHandler, this);
491 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
493 // Initialize the generic parser.
494 GenericParser->Initialize(*this);
496 // Initialize the platform / file format parser.
498 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
500 if (_MAI.hasMicrosoftFastStdCallMangling()) {
501 PlatformParser = createCOFFAsmParser();
502 PlatformParser->Initialize(*this);
503 } else if (_MAI.hasSubsectionsViaSymbols()) {
504 PlatformParser = createDarwinAsmParser();
505 PlatformParser->Initialize(*this);
508 PlatformParser = createELFAsmParser();
509 PlatformParser->Initialize(*this);
513 AsmParser::~AsmParser() {
514 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
516 // Destroy any macros.
517 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
518 ie = MacroMap.end(); it != ie; ++it)
519 delete it->getValue();
521 delete PlatformParser;
522 delete GenericParser;
525 void AsmParser::PrintMacroInstantiations() {
526 // Print the active macro instantiation stack.
527 for (std::vector<MacroInstantiation*>::const_reverse_iterator
528 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
529 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
530 "while in macro instantiation");
533 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
534 if (FatalAssemblerWarnings)
535 return Error(L, Msg, Ranges);
536 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
537 PrintMacroInstantiations();
541 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
543 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
544 PrintMacroInstantiations();
548 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
549 std::string IncludedFile;
550 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
556 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
561 /// Process the specified .incbin file by seaching for it in the include paths
562 /// then just emitting the byte contents of the file to the streamer. This
563 /// returns true on failure.
564 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
565 std::string IncludedFile;
566 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
570 // Pick up the bytes from the file and emit them.
571 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
576 void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
577 if (InBuffer != -1) {
578 CurBuffer = InBuffer;
580 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
582 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
585 const AsmToken &AsmParser::Lex() {
586 const AsmToken *tok = &Lexer.Lex();
588 if (tok->is(AsmToken::Eof)) {
589 // If this is the end of an included file, pop the parent file off the
591 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
592 if (ParentIncludeLoc != SMLoc()) {
593 JumpToLoc(ParentIncludeLoc);
598 if (tok->is(AsmToken::Error))
599 Error(Lexer.getErrLoc(), Lexer.getErr());
604 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
605 // Create the initial section, if requested.
606 if (!NoInitialTextSection)
613 AsmCond StartingCondState = TheCondState;
615 // If we are generating dwarf for assembly source files save the initial text
616 // section and generate a .file directive.
617 if (getContext().getGenDwarfForAssembly()) {
618 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
619 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
620 getStreamer().EmitLabel(SectionStartSym);
621 getContext().setGenDwarfSectionStartSym(SectionStartSym);
622 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
624 getContext().getMainFileName());
627 // While we have input, parse each statement.
628 while (Lexer.isNot(AsmToken::Eof)) {
629 ParseStatementInfo Info;
630 if (!ParseStatement(Info)) continue;
632 // We had an error, validate that one was emitted and recover by skipping to
634 assert(HadError && "Parse statement returned an error, but none emitted!");
635 EatToEndOfStatement();
638 if (TheCondState.TheCond != StartingCondState.TheCond ||
639 TheCondState.Ignore != StartingCondState.Ignore)
640 return TokError("unmatched .ifs or .elses");
642 // Check to see there are no empty DwarfFile slots.
643 const std::vector<MCDwarfFile *> &MCDwarfFiles =
644 getContext().getMCDwarfFiles();
645 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
646 if (!MCDwarfFiles[i])
647 TokError("unassigned file number: " + Twine(i) + " for .file directives");
650 // Check to see that all assembler local symbols were actually defined.
651 // Targets that don't do subsections via symbols may not want this, though,
652 // so conservatively exclude them. Only do this if we're finalizing, though,
653 // as otherwise we won't necessarilly have seen everything yet.
654 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
655 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
656 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
659 MCSymbol *Sym = i->getValue();
660 // Variable symbols may not be marked as defined, so check those
661 // explicitly. If we know it's a variable, we have a definition for
662 // the purposes of this check.
663 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
664 // FIXME: We would really like to refer back to where the symbol was
665 // first referenced for a source location. We need to add something
666 // to track that. Currently, we just point to the end of the file.
667 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
668 "assembler local symbol '" + Sym->getName() +
674 // Finalize the output stream if there are no errors and if the client wants
676 if (!HadError && !NoFinalize)
682 void AsmParser::CheckForValidSection() {
683 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
684 TokError("expected section directive before assembly directive");
685 Out.SwitchSection(Ctx.getMachOSection(
687 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
688 0, SectionKind::getText()));
692 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
693 void AsmParser::EatToEndOfStatement() {
694 while (Lexer.isNot(AsmToken::EndOfStatement) &&
695 Lexer.isNot(AsmToken::Eof))
699 if (Lexer.is(AsmToken::EndOfStatement))
703 StringRef AsmParser::ParseStringToEndOfStatement() {
704 const char *Start = getTok().getLoc().getPointer();
706 while (Lexer.isNot(AsmToken::EndOfStatement) &&
707 Lexer.isNot(AsmToken::Eof))
710 const char *End = getTok().getLoc().getPointer();
711 return StringRef(Start, End - Start);
714 StringRef AsmParser::ParseStringToComma() {
715 const char *Start = getTok().getLoc().getPointer();
717 while (Lexer.isNot(AsmToken::EndOfStatement) &&
718 Lexer.isNot(AsmToken::Comma) &&
719 Lexer.isNot(AsmToken::Eof))
722 const char *End = getTok().getLoc().getPointer();
723 return StringRef(Start, End - Start);
726 /// ParseParenExpr - Parse a paren expression and return it.
727 /// NOTE: This assumes the leading '(' has already been consumed.
729 /// parenexpr ::= expr)
731 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
732 if (ParseExpression(Res)) return true;
733 if (Lexer.isNot(AsmToken::RParen))
734 return TokError("expected ')' in parentheses expression");
735 EndLoc = Lexer.getTok().getEndLoc();
740 /// ParseBracketExpr - Parse a bracket expression and return it.
741 /// NOTE: This assumes the leading '[' has already been consumed.
743 /// bracketexpr ::= expr]
745 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
746 if (ParseExpression(Res)) return true;
747 if (Lexer.isNot(AsmToken::RBrac))
748 return TokError("expected ']' in brackets expression");
749 EndLoc = Lexer.getTok().getEndLoc();
754 /// ParsePrimaryExpr - Parse a primary expression and return it.
755 /// primaryexpr ::= (parenexpr
756 /// primaryexpr ::= symbol
757 /// primaryexpr ::= number
758 /// primaryexpr ::= '.'
759 /// primaryexpr ::= ~,+,- primaryexpr
760 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
761 switch (Lexer.getKind()) {
763 return TokError("unknown token in expression");
764 // If we have an error assume that we've already handled it.
765 case AsmToken::Error:
767 case AsmToken::Exclaim:
768 Lex(); // Eat the operator.
769 if (ParsePrimaryExpr(Res, EndLoc))
771 Res = MCUnaryExpr::CreateLNot(Res, getContext());
773 case AsmToken::Dollar:
774 case AsmToken::String:
775 case AsmToken::Identifier: {
776 StringRef Identifier;
777 if (ParseIdentifier(Identifier))
780 EndLoc = SMLoc::getFromPointer(Identifier.end());
782 // This is a symbol reference.
783 std::pair<StringRef, StringRef> Split = Identifier.split('@');
784 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
786 // Lookup the symbol variant if used.
787 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
788 if (Split.first.size() != Identifier.size()) {
789 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
790 if (Variant == MCSymbolRefExpr::VK_Invalid) {
791 Variant = MCSymbolRefExpr::VK_None;
792 return TokError("invalid variant '" + Split.second + "'");
796 // If this is an absolute variable reference, substitute it now to preserve
797 // semantics in the face of reassignment.
798 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
800 return Error(EndLoc, "unexpected modifier on variable reference");
802 Res = Sym->getVariableValue();
806 // Otherwise create a symbol ref.
807 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
810 case AsmToken::Integer: {
811 SMLoc Loc = getTok().getLoc();
812 int64_t IntVal = getTok().getIntVal();
813 Res = MCConstantExpr::Create(IntVal, getContext());
814 EndLoc = Lexer.getTok().getEndLoc();
816 // Look for 'b' or 'f' following an Integer as a directional label
817 if (Lexer.getKind() == AsmToken::Identifier) {
818 StringRef IDVal = getTok().getString();
819 if (IDVal == "f" || IDVal == "b"){
820 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
821 IDVal == "f" ? 1 : 0);
822 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
824 if (IDVal == "b" && Sym->isUndefined())
825 return Error(Loc, "invalid reference to undefined symbol");
826 EndLoc = Lexer.getTok().getEndLoc();
827 Lex(); // Eat identifier.
832 case AsmToken::Real: {
833 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
834 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
835 Res = MCConstantExpr::Create(IntVal, getContext());
836 EndLoc = Lexer.getTok().getEndLoc();
840 case AsmToken::Dot: {
841 // This is a '.' reference, which references the current PC. Emit a
842 // temporary label to the streamer and refer to it.
843 MCSymbol *Sym = Ctx.CreateTempSymbol();
845 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
846 EndLoc = Lexer.getTok().getEndLoc();
847 Lex(); // Eat identifier.
850 case AsmToken::LParen:
851 Lex(); // Eat the '('.
852 return ParseParenExpr(Res, EndLoc);
853 case AsmToken::LBrac:
854 if (!PlatformParser->HasBracketExpressions())
855 return TokError("brackets expression not supported on this target");
856 Lex(); // Eat the '['.
857 return ParseBracketExpr(Res, EndLoc);
858 case AsmToken::Minus:
859 Lex(); // Eat the operator.
860 if (ParsePrimaryExpr(Res, EndLoc))
862 Res = MCUnaryExpr::CreateMinus(Res, getContext());
865 Lex(); // Eat the operator.
866 if (ParsePrimaryExpr(Res, EndLoc))
868 Res = MCUnaryExpr::CreatePlus(Res, getContext());
870 case AsmToken::Tilde:
871 Lex(); // Eat the operator.
872 if (ParsePrimaryExpr(Res, EndLoc))
874 Res = MCUnaryExpr::CreateNot(Res, getContext());
879 bool AsmParser::ParseExpression(const MCExpr *&Res) {
881 return ParseExpression(Res, EndLoc);
885 AsmParser::ApplyModifierToExpr(const MCExpr *E,
886 MCSymbolRefExpr::VariantKind Variant) {
887 // Recurse over the given expression, rebuilding it to apply the given variant
888 // if there is exactly one symbol.
889 switch (E->getKind()) {
891 case MCExpr::Constant:
894 case MCExpr::SymbolRef: {
895 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
897 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
898 TokError("invalid variant on expression '" +
899 getTok().getIdentifier() + "' (already modified)");
903 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
906 case MCExpr::Unary: {
907 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
908 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
911 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
914 case MCExpr::Binary: {
915 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
916 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
917 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
922 if (!LHS) LHS = BE->getLHS();
923 if (!RHS) RHS = BE->getRHS();
925 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
929 llvm_unreachable("Invalid expression kind!");
932 /// ParseExpression - Parse an expression and return it.
934 /// expr ::= expr &&,|| expr -> lowest.
935 /// expr ::= expr |,^,&,! expr
936 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
937 /// expr ::= expr <<,>> expr
938 /// expr ::= expr +,- expr
939 /// expr ::= expr *,/,% expr -> highest.
940 /// expr ::= primaryexpr
942 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
943 // Parse the expression.
945 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
948 // As a special case, we support 'a op b @ modifier' by rewriting the
949 // expression to include the modifier. This is inefficient, but in general we
950 // expect users to use 'a@modifier op b'.
951 if (Lexer.getKind() == AsmToken::At) {
954 if (Lexer.isNot(AsmToken::Identifier))
955 return TokError("unexpected symbol modifier following '@'");
957 MCSymbolRefExpr::VariantKind Variant =
958 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
959 if (Variant == MCSymbolRefExpr::VK_Invalid)
960 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
962 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
964 return TokError("invalid modifier '" + getTok().getIdentifier() +
965 "' (no symbols present)");
972 // Try to constant fold it up front, if possible.
974 if (Res->EvaluateAsAbsolute(Value))
975 Res = MCConstantExpr::Create(Value, getContext());
980 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
982 return ParseParenExpr(Res, EndLoc) ||
983 ParseBinOpRHS(1, Res, EndLoc);
986 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
989 SMLoc StartLoc = Lexer.getLoc();
990 if (ParseExpression(Expr))
993 if (!Expr->EvaluateAsAbsolute(Res))
994 return Error(StartLoc, "expected absolute expression");
999 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1000 MCBinaryExpr::Opcode &Kind) {
1003 return 0; // not a binop.
1005 // Lowest Precedence: &&, ||
1006 case AsmToken::AmpAmp:
1007 Kind = MCBinaryExpr::LAnd;
1009 case AsmToken::PipePipe:
1010 Kind = MCBinaryExpr::LOr;
1014 // Low Precedence: |, &, ^
1016 // FIXME: gas seems to support '!' as an infix operator?
1017 case AsmToken::Pipe:
1018 Kind = MCBinaryExpr::Or;
1020 case AsmToken::Caret:
1021 Kind = MCBinaryExpr::Xor;
1024 Kind = MCBinaryExpr::And;
1027 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1028 case AsmToken::EqualEqual:
1029 Kind = MCBinaryExpr::EQ;
1031 case AsmToken::ExclaimEqual:
1032 case AsmToken::LessGreater:
1033 Kind = MCBinaryExpr::NE;
1035 case AsmToken::Less:
1036 Kind = MCBinaryExpr::LT;
1038 case AsmToken::LessEqual:
1039 Kind = MCBinaryExpr::LTE;
1041 case AsmToken::Greater:
1042 Kind = MCBinaryExpr::GT;
1044 case AsmToken::GreaterEqual:
1045 Kind = MCBinaryExpr::GTE;
1048 // Intermediate Precedence: <<, >>
1049 case AsmToken::LessLess:
1050 Kind = MCBinaryExpr::Shl;
1052 case AsmToken::GreaterGreater:
1053 Kind = MCBinaryExpr::Shr;
1056 // High Intermediate Precedence: +, -
1057 case AsmToken::Plus:
1058 Kind = MCBinaryExpr::Add;
1060 case AsmToken::Minus:
1061 Kind = MCBinaryExpr::Sub;
1064 // Highest Precedence: *, /, %
1065 case AsmToken::Star:
1066 Kind = MCBinaryExpr::Mul;
1068 case AsmToken::Slash:
1069 Kind = MCBinaryExpr::Div;
1071 case AsmToken::Percent:
1072 Kind = MCBinaryExpr::Mod;
1078 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1079 /// Res contains the LHS of the expression on input.
1080 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1083 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1084 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1086 // If the next token is lower precedence than we are allowed to eat, return
1087 // successfully with what we ate already.
1088 if (TokPrec < Precedence)
1093 // Eat the next primary expression.
1095 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1097 // If BinOp binds less tightly with RHS than the operator after RHS, let
1098 // the pending operator take RHS as its LHS.
1099 MCBinaryExpr::Opcode Dummy;
1100 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1101 if (TokPrec < NextTokPrec) {
1102 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1105 // Merge LHS and RHS according to operator.
1106 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1111 /// ::= EndOfStatement
1112 /// ::= Label* Directive ...Operands... EndOfStatement
1113 /// ::= Label* Identifier OperandList* EndOfStatement
1114 bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
1115 if (Lexer.is(AsmToken::EndOfStatement)) {
1121 // Statements always start with an identifier or are a full line comment.
1122 AsmToken ID = getTok();
1123 SMLoc IDLoc = ID.getLoc();
1125 int64_t LocalLabelVal = -1;
1126 // A full line comment is a '#' as the first token.
1127 if (Lexer.is(AsmToken::Hash))
1128 return ParseCppHashLineFilenameComment(IDLoc);
1130 // Allow an integer followed by a ':' as a directional local label.
1131 if (Lexer.is(AsmToken::Integer)) {
1132 LocalLabelVal = getTok().getIntVal();
1133 if (LocalLabelVal < 0) {
1134 if (!TheCondState.Ignore)
1135 return TokError("unexpected token at start of statement");
1139 IDVal = getTok().getString();
1140 Lex(); // Consume the integer token to be used as an identifier token.
1141 if (Lexer.getKind() != AsmToken::Colon) {
1142 if (!TheCondState.Ignore)
1143 return TokError("unexpected token at start of statement");
1147 } else if (Lexer.is(AsmToken::Dot)) {
1148 // Treat '.' as a valid identifier in this context.
1152 } else if (ParseIdentifier(IDVal)) {
1153 if (!TheCondState.Ignore)
1154 return TokError("unexpected token at start of statement");
1159 // Handle conditional assembly here before checking for skipping. We
1160 // have to do this so that .endif isn't skipped in a ".if 0" block for
1163 return ParseDirectiveIf(IDLoc);
1164 if (IDVal == ".ifb")
1165 return ParseDirectiveIfb(IDLoc, true);
1166 if (IDVal == ".ifnb")
1167 return ParseDirectiveIfb(IDLoc, false);
1168 if (IDVal == ".ifc")
1169 return ParseDirectiveIfc(IDLoc, true);
1170 if (IDVal == ".ifnc")
1171 return ParseDirectiveIfc(IDLoc, false);
1172 if (IDVal == ".ifdef")
1173 return ParseDirectiveIfdef(IDLoc, true);
1174 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1175 return ParseDirectiveIfdef(IDLoc, false);
1176 if (IDVal == ".elseif")
1177 return ParseDirectiveElseIf(IDLoc);
1178 if (IDVal == ".else")
1179 return ParseDirectiveElse(IDLoc);
1180 if (IDVal == ".endif")
1181 return ParseDirectiveEndIf(IDLoc);
1183 // If we are in a ".if 0" block, ignore this statement.
1184 if (TheCondState.Ignore) {
1185 EatToEndOfStatement();
1189 // FIXME: Recurse on local labels?
1191 // See what kind of statement we have.
1192 switch (Lexer.getKind()) {
1193 case AsmToken::Colon: {
1194 CheckForValidSection();
1196 // identifier ':' -> Label.
1199 // Diagnose attempt to use '.' as a label.
1201 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1203 // Diagnose attempt to use a variable as a label.
1205 // FIXME: Diagnostics. Note the location of the definition as a label.
1206 // FIXME: This doesn't diagnose assignment to a symbol which has been
1207 // implicitly marked as external.
1209 if (LocalLabelVal == -1)
1210 Sym = getContext().GetOrCreateSymbol(IDVal);
1212 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1213 if (!Sym->isUndefined() || Sym->isVariable())
1214 return Error(IDLoc, "invalid symbol redefinition");
1219 // If we are generating dwarf for assembly source files then gather the
1220 // info to make a dwarf label entry for this label if needed.
1221 if (getContext().getGenDwarfForAssembly())
1222 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1225 // Consume any end of statement token, if present, to avoid spurious
1226 // AddBlankLine calls().
1227 if (Lexer.is(AsmToken::EndOfStatement)) {
1229 if (Lexer.is(AsmToken::Eof))
1236 case AsmToken::Equal:
1237 // identifier '=' ... -> assignment statement
1240 return ParseAssignment(IDVal, true);
1242 default: // Normal instruction or directive.
1246 // If macros are enabled, check to see if this is a macro instantiation.
1248 if (const Macro *M = MacroMap.lookup(IDVal))
1249 return HandleMacroEntry(IDVal, IDLoc, M);
1251 // Otherwise, we have a normal instruction or directive.
1252 if (IDVal[0] == '.' && IDVal != ".") {
1254 // Target hook for parsing target specific directives.
1255 if (!getTargetParser().ParseDirective(ID))
1258 // Assembler features
1259 if (IDVal == ".set" || IDVal == ".equ")
1260 return ParseDirectiveSet(IDVal, true);
1261 if (IDVal == ".equiv")
1262 return ParseDirectiveSet(IDVal, false);
1266 if (IDVal == ".ascii")
1267 return ParseDirectiveAscii(IDVal, false);
1268 if (IDVal == ".asciz" || IDVal == ".string")
1269 return ParseDirectiveAscii(IDVal, true);
1271 if (IDVal == ".byte")
1272 return ParseDirectiveValue(1);
1273 if (IDVal == ".short")
1274 return ParseDirectiveValue(2);
1275 if (IDVal == ".value")
1276 return ParseDirectiveValue(2);
1277 if (IDVal == ".2byte")
1278 return ParseDirectiveValue(2);
1279 if (IDVal == ".long")
1280 return ParseDirectiveValue(4);
1281 if (IDVal == ".int")
1282 return ParseDirectiveValue(4);
1283 if (IDVal == ".4byte")
1284 return ParseDirectiveValue(4);
1285 if (IDVal == ".quad")
1286 return ParseDirectiveValue(8);
1287 if (IDVal == ".8byte")
1288 return ParseDirectiveValue(8);
1289 if (IDVal == ".single" || IDVal == ".float")
1290 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1291 if (IDVal == ".double")
1292 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1294 if (IDVal == ".align") {
1295 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1296 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1298 if (IDVal == ".align32") {
1299 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1300 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1302 if (IDVal == ".balign")
1303 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1304 if (IDVal == ".balignw")
1305 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1306 if (IDVal == ".balignl")
1307 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1308 if (IDVal == ".p2align")
1309 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1310 if (IDVal == ".p2alignw")
1311 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1312 if (IDVal == ".p2alignl")
1313 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1315 if (IDVal == ".bundle_align_mode")
1316 return ParseDirectiveBundleAlignMode();
1317 if (IDVal == ".bundle_lock")
1318 return ParseDirectiveBundleLock();
1319 if (IDVal == ".bundle_unlock")
1320 return ParseDirectiveBundleUnlock();
1322 if (IDVal == ".org")
1323 return ParseDirectiveOrg();
1325 if (IDVal == ".fill")
1326 return ParseDirectiveFill();
1327 if (IDVal == ".space" || IDVal == ".skip")
1328 return ParseDirectiveSpace();
1329 if (IDVal == ".zero")
1330 return ParseDirectiveZero();
1332 // Symbol attribute directives
1334 if (IDVal == ".extern") {
1335 EatToEndOfStatement(); // .extern is the default, ignore it.
1338 if (IDVal == ".globl" || IDVal == ".global")
1339 return ParseDirectiveSymbolAttribute(MCSA_Global);
1340 if (IDVal == ".indirect_symbol")
1341 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1342 if (IDVal == ".lazy_reference")
1343 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1344 if (IDVal == ".no_dead_strip")
1345 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1346 if (IDVal == ".symbol_resolver")
1347 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1348 if (IDVal == ".private_extern")
1349 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1350 if (IDVal == ".reference")
1351 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1352 if (IDVal == ".weak_definition")
1353 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1354 if (IDVal == ".weak_reference")
1355 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1356 if (IDVal == ".weak_def_can_be_hidden")
1357 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1359 if (IDVal == ".comm" || IDVal == ".common")
1360 return ParseDirectiveComm(/*IsLocal=*/false);
1361 if (IDVal == ".lcomm")
1362 return ParseDirectiveComm(/*IsLocal=*/true);
1364 if (IDVal == ".abort")
1365 return ParseDirectiveAbort();
1366 if (IDVal == ".include")
1367 return ParseDirectiveInclude();
1368 if (IDVal == ".incbin")
1369 return ParseDirectiveIncbin();
1371 if (IDVal == ".code16" || IDVal == ".code16gcc")
1372 return TokError(Twine(IDVal) + " not supported yet");
1374 // Macro-like directives
1375 if (IDVal == ".rept")
1376 return ParseDirectiveRept(IDLoc);
1377 if (IDVal == ".irp")
1378 return ParseDirectiveIrp(IDLoc);
1379 if (IDVal == ".irpc")
1380 return ParseDirectiveIrpc(IDLoc);
1381 if (IDVal == ".endr")
1382 return ParseDirectiveEndr(IDLoc);
1384 // Look up the handler in the handler table.
1385 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1386 DirectiveMap.lookup(IDVal);
1388 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1391 return Error(IDLoc, "unknown directive");
1395 if (ParsingInlineAsm && IDVal == "_emit")
1396 return ParseDirectiveEmit(IDLoc, Info);
1398 CheckForValidSection();
1400 // Canonicalize the opcode to lower case.
1401 SmallString<128> OpcodeStr;
1402 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1403 OpcodeStr.push_back(tolower(IDVal[i]));
1405 ParseInstructionInfo IInfo(Info.AsmRewrites);
1406 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1407 IDLoc,Info.ParsedOperands);
1408 Info.ParseError = HadError;
1410 // Dump the parsed representation, if requested.
1411 if (getShowParsedOperands()) {
1412 SmallString<256> Str;
1413 raw_svector_ostream OS(Str);
1414 OS << "parsed instruction: [";
1415 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1418 Info.ParsedOperands[i]->print(OS);
1422 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1425 // If we are generating dwarf for assembly source files and the current
1426 // section is the initial text section then generate a .loc directive for
1428 if (!HadError && getContext().getGenDwarfForAssembly() &&
1429 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
1431 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1433 // If we previously parsed a cpp hash file line comment then make sure the
1434 // current Dwarf File is for the CppHashFilename if not then emit the
1435 // Dwarf File table for it and adjust the line number for the .loc.
1436 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1437 getContext().getMCDwarfFiles();
1438 if (CppHashFilename.size() != 0) {
1439 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1441 getStreamer().EmitDwarfFileDirective(
1442 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1444 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
1445 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1448 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1449 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1450 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1454 // If parsing succeeded, match the instruction.
1457 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1458 Info.ParsedOperands,
1463 // Don't skip the rest of the line, the instruction parser is responsible for
1468 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1469 /// since they may not be able to be tokenized to get to the end of line token.
1470 void AsmParser::EatToEndOfLine() {
1471 if (!Lexer.is(AsmToken::EndOfStatement))
1472 Lexer.LexUntilEndOfLine();
1477 /// ParseCppHashLineFilenameComment as this:
1478 /// ::= # number "filename"
1479 /// or just as a full line comment if it doesn't have a number and a string.
1480 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1481 Lex(); // Eat the hash token.
1483 if (getLexer().isNot(AsmToken::Integer)) {
1484 // Consume the line since in cases it is not a well-formed line directive,
1485 // as if were simply a full line comment.
1490 int64_t LineNumber = getTok().getIntVal();
1493 if (getLexer().isNot(AsmToken::String)) {
1498 StringRef Filename = getTok().getString();
1499 // Get rid of the enclosing quotes.
1500 Filename = Filename.substr(1, Filename.size()-2);
1502 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1504 CppHashFilename = Filename;
1505 CppHashLineNumber = LineNumber;
1506 CppHashBuf = CurBuffer;
1508 // Ignore any trailing characters, they're just comment.
1513 /// DiagHandler - will use the last parsed cpp hash line filename comment
1514 /// for the Filename and LineNo if any in the diagnostic.
1515 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1516 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1517 raw_ostream &OS = errs();
1519 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1520 const SMLoc &DiagLoc = Diag.getLoc();
1521 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1522 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1524 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1525 // before printing the message.
1526 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1527 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1528 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1529 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1532 // If we have not parsed a cpp hash line filename comment or the source
1533 // manager changed or buffer changed (like in a nested include) then just
1534 // print the normal diagnostic using its Filename and LineNo.
1535 if (!Parser->CppHashLineNumber ||
1536 &DiagSrcMgr != &Parser->SrcMgr ||
1537 DiagBuf != CppHashBuf) {
1538 if (Parser->SavedDiagHandler)
1539 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1545 // Use the CppHashFilename and calculate a line number based on the
1546 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1548 const std::string Filename = Parser->CppHashFilename;
1550 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1551 int CppHashLocLineNo =
1552 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1553 int LineNo = Parser->CppHashLineNumber - 1 +
1554 (DiagLocLineNo - CppHashLocLineNo);
1556 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1557 Filename, LineNo, Diag.getColumnNo(),
1558 Diag.getKind(), Diag.getMessage(),
1559 Diag.getLineContents(), Diag.getRanges());
1561 if (Parser->SavedDiagHandler)
1562 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1564 NewDiag.print(0, OS);
1567 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1568 // difference being that that function accepts '@' as part of identifiers and
1569 // we can't do that. AsmLexer.cpp should probably be changed to handle
1570 // '@' as a special case when needed.
1571 static bool isIdentifierChar(char c) {
1572 return isalnum(c) || c == '_' || c == '$' || c == '.';
1575 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1576 const MacroParameters &Parameters,
1577 const MacroArguments &A,
1579 unsigned NParameters = Parameters.size();
1580 if (NParameters != 0 && NParameters != A.size())
1581 return Error(L, "Wrong number of arguments");
1583 // A macro without parameters is handled differently on Darwin:
1584 // gas accepts no arguments and does no substitutions
1585 while (!Body.empty()) {
1586 // Scan for the next substitution.
1587 std::size_t End = Body.size(), Pos = 0;
1588 for (; Pos != End; ++Pos) {
1589 // Check for a substitution or escape.
1591 // This macro has no parameters, look for $0, $1, etc.
1592 if (Body[Pos] != '$' || Pos + 1 == End)
1595 char Next = Body[Pos + 1];
1596 if (Next == '$' || Next == 'n' || isdigit(Next))
1599 // This macro has parameters, look for \foo, \bar, etc.
1600 if (Body[Pos] == '\\' && Pos + 1 != End)
1606 OS << Body.slice(0, Pos);
1608 // Check if we reached the end.
1613 switch (Body[Pos+1]) {
1619 // $n => number of arguments
1624 // $[0-9] => argument
1626 // Missing arguments are ignored.
1627 unsigned Index = Body[Pos+1] - '0';
1628 if (Index >= A.size())
1631 // Otherwise substitute with the token values, with spaces eliminated.
1632 for (MacroArgument::const_iterator it = A[Index].begin(),
1633 ie = A[Index].end(); it != ie; ++it)
1634 OS << it->getString();
1640 unsigned I = Pos + 1;
1641 while (isIdentifierChar(Body[I]) && I + 1 != End)
1644 const char *Begin = Body.data() + Pos +1;
1645 StringRef Argument(Begin, I - (Pos +1));
1647 for (; Index < NParameters; ++Index)
1648 if (Parameters[Index].first == Argument)
1651 if (Index == NParameters) {
1652 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1655 OS << '\\' << Argument;
1659 for (MacroArgument::const_iterator it = A[Index].begin(),
1660 ie = A[Index].end(); it != ie; ++it)
1661 if (it->getKind() == AsmToken::String)
1662 OS << it->getStringContents();
1664 OS << it->getString();
1666 Pos += 1 + Argument.size();
1669 // Update the scan point.
1670 Body = Body.substr(Pos);
1676 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL,
1679 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1684 static bool IsOperator(AsmToken::TokenKind kind)
1690 case AsmToken::Plus:
1691 case AsmToken::Minus:
1692 case AsmToken::Tilde:
1693 case AsmToken::Slash:
1694 case AsmToken::Star:
1696 case AsmToken::Equal:
1697 case AsmToken::EqualEqual:
1698 case AsmToken::Pipe:
1699 case AsmToken::PipePipe:
1700 case AsmToken::Caret:
1702 case AsmToken::AmpAmp:
1703 case AsmToken::Exclaim:
1704 case AsmToken::ExclaimEqual:
1705 case AsmToken::Percent:
1706 case AsmToken::Less:
1707 case AsmToken::LessEqual:
1708 case AsmToken::LessLess:
1709 case AsmToken::LessGreater:
1710 case AsmToken::Greater:
1711 case AsmToken::GreaterEqual:
1712 case AsmToken::GreaterGreater:
1717 /// ParseMacroArgument - Extract AsmTokens for a macro argument.
1718 /// This is used for both default macro parameter values and the
1719 /// arguments in macro invocations
1720 bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1721 AsmToken::TokenKind &ArgumentDelimiter) {
1722 unsigned ParenLevel = 0;
1723 unsigned AddTokens = 0;
1725 // gas accepts arguments separated by whitespace, except on Darwin
1727 Lexer.setSkipSpace(false);
1730 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1731 Lexer.setSkipSpace(true);
1732 return TokError("unexpected token in macro instantiation");
1735 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1736 // Spaces and commas cannot be mixed to delimit parameters
1737 if (ArgumentDelimiter == AsmToken::Eof)
1738 ArgumentDelimiter = AsmToken::Comma;
1739 else if (ArgumentDelimiter != AsmToken::Comma) {
1740 Lexer.setSkipSpace(true);
1741 return TokError("expected ' ' for macro argument separator");
1746 if (Lexer.is(AsmToken::Space)) {
1747 Lex(); // Eat spaces
1749 // Spaces can delimit parameters, but could also be part an expression.
1750 // If the token after a space is an operator, add the token and the next
1751 // one into this argument
1752 if (ArgumentDelimiter == AsmToken::Space ||
1753 ArgumentDelimiter == AsmToken::Eof) {
1754 if (IsOperator(Lexer.getKind())) {
1755 // Check to see whether the token is used as an operator,
1756 // or part of an identifier
1757 const char *NextChar = getTok().getEndLoc().getPointer();
1758 if (*NextChar == ' ')
1762 if (!AddTokens && ParenLevel == 0) {
1763 if (ArgumentDelimiter == AsmToken::Eof &&
1764 !IsOperator(Lexer.getKind()))
1765 ArgumentDelimiter = AsmToken::Space;
1771 // HandleMacroEntry relies on not advancing the lexer here
1772 // to be able to fill in the remaining default parameter values
1773 if (Lexer.is(AsmToken::EndOfStatement))
1776 // Adjust the current parentheses level.
1777 if (Lexer.is(AsmToken::LParen))
1779 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1782 // Append the token to the current argument list.
1783 MA.push_back(getTok());
1789 Lexer.setSkipSpace(true);
1790 if (ParenLevel != 0)
1791 return TokError("unbalanced parentheses in macro argument");
1795 // Parse the macro instantiation arguments.
1796 bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
1797 const unsigned NParameters = M ? M->Parameters.size() : 0;
1798 // Argument delimiter is initially unknown. It will be set by
1799 // ParseMacroArgument()
1800 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1802 // Parse two kinds of macro invocations:
1803 // - macros defined without any parameters accept an arbitrary number of them
1804 // - macros defined with parameters accept at most that many of them
1805 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1809 if (ParseMacroArgument(MA, ArgumentDelimiter))
1812 if (!MA.empty() || !NParameters)
1814 else if (NParameters) {
1815 if (!M->Parameters[Parameter].second.empty())
1816 A.push_back(M->Parameters[Parameter].second);
1819 // At the end of the statement, fill in remaining arguments that have
1820 // default values. If there aren't any, then the next argument is
1821 // required but missing
1822 if (Lexer.is(AsmToken::EndOfStatement)) {
1823 if (NParameters && Parameter < NParameters - 1) {
1824 if (M->Parameters[Parameter + 1].second.empty())
1825 return TokError("macro argument '" +
1826 Twine(M->Parameters[Parameter + 1].first) +
1834 if (Lexer.is(AsmToken::Comma))
1837 return TokError("Too many arguments");
1840 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1842 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1843 // this, although we should protect against infinite loops.
1844 if (ActiveMacros.size() == 20)
1845 return TokError("macros cannot be nested more than 20 levels deep");
1848 if (ParseMacroArguments(M, A))
1851 // Remove any trailing empty arguments. Do this after-the-fact as we have
1852 // to keep empty arguments in the middle of the list or positionality
1853 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1854 while (!A.empty() && A.back().empty())
1857 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1858 // to hold the macro body with substitutions.
1859 SmallString<256> Buf;
1860 StringRef Body = M->Body;
1861 raw_svector_ostream OS(Buf);
1863 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1866 // We include the .endmacro in the buffer as our queue to exit the macro
1868 OS << ".endmacro\n";
1870 MemoryBuffer *Instantiation =
1871 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1873 // Create the macro instantiation object and add to the current macro
1874 // instantiation stack.
1875 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1879 ActiveMacros.push_back(MI);
1881 // Jump to the macro instantiation and prime the lexer.
1882 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1883 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1889 void AsmParser::HandleMacroExit() {
1890 // Jump to the EndOfStatement we should return to, and consume it.
1891 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
1894 // Pop the instantiation entry.
1895 delete ActiveMacros.back();
1896 ActiveMacros.pop_back();
1899 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1900 switch (Value->getKind()) {
1901 case MCExpr::Binary: {
1902 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1903 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1906 case MCExpr::Target:
1907 case MCExpr::Constant:
1909 case MCExpr::SymbolRef: {
1910 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1912 return IsUsedIn(Sym, S.getVariableValue());
1916 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1919 llvm_unreachable("Unknown expr kind!");
1922 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1924 // FIXME: Use better location, we should use proper tokens.
1925 SMLoc EqualLoc = Lexer.getLoc();
1927 const MCExpr *Value;
1928 if (ParseExpression(Value))
1931 // Note: we don't count b as used in "a = b". This is to allow
1935 if (Lexer.isNot(AsmToken::EndOfStatement))
1936 return TokError("unexpected token in assignment");
1938 // Error on assignment to '.'.
1940 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1941 "(use '.space' or '.org').)"));
1944 // Eat the end of statement marker.
1947 // Validate that the LHS is allowed to be a variable (either it has not been
1948 // used as a symbol, or it is an absolute symbol).
1949 MCSymbol *Sym = getContext().LookupSymbol(Name);
1951 // Diagnose assignment to a label.
1953 // FIXME: Diagnostics. Note the location of the definition as a label.
1954 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1955 if (IsUsedIn(Sym, Value))
1956 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1957 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1958 ; // Allow redefinitions of undefined symbols only used in directives.
1959 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1960 ; // Allow redefinitions of variables that haven't yet been used.
1961 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1962 return Error(EqualLoc, "redefinition of '" + Name + "'");
1963 else if (!Sym->isVariable())
1964 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1965 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1966 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1969 // Don't count these checks as uses.
1970 Sym->setUsed(false);
1972 Sym = getContext().GetOrCreateSymbol(Name);
1974 // FIXME: Handle '.'.
1976 // Do the assignment.
1977 Out.EmitAssignment(Sym, Value);
1979 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1985 /// ParseIdentifier:
1988 bool AsmParser::ParseIdentifier(StringRef &Res) {
1989 // The assembler has relaxed rules for accepting identifiers, in particular we
1990 // allow things like '.globl $foo', which would normally be separate
1991 // tokens. At this level, we have already lexed so we cannot (currently)
1992 // handle this as a context dependent token, instead we detect adjacent tokens
1993 // and return the combined identifier.
1994 if (Lexer.is(AsmToken::Dollar)) {
1995 SMLoc DollarLoc = getLexer().getLoc();
1997 // Consume the dollar sign, and check for a following identifier.
1999 if (Lexer.isNot(AsmToken::Identifier))
2002 // We have a '$' followed by an identifier, make sure they are adjacent.
2003 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2006 // Construct the joined identifier and consume the token.
2007 Res = StringRef(DollarLoc.getPointer(),
2008 getTok().getIdentifier().size() + 1);
2013 if (Lexer.isNot(AsmToken::Identifier) &&
2014 Lexer.isNot(AsmToken::String))
2017 Res = getTok().getIdentifier();
2019 Lex(); // Consume the identifier token.
2024 /// ParseDirectiveSet:
2025 /// ::= .equ identifier ',' expression
2026 /// ::= .equiv identifier ',' expression
2027 /// ::= .set identifier ',' expression
2028 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
2031 if (ParseIdentifier(Name))
2032 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2034 if (getLexer().isNot(AsmToken::Comma))
2035 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2038 return ParseAssignment(Name, allow_redef, true);
2041 bool AsmParser::ParseEscapedString(std::string &Data) {
2042 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2045 StringRef Str = getTok().getStringContents();
2046 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2047 if (Str[i] != '\\') {
2052 // Recognize escaped characters. Note that this escape semantics currently
2053 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2056 return TokError("unexpected backslash at end of string");
2058 // Recognize octal sequences.
2059 if ((unsigned) (Str[i] - '0') <= 7) {
2060 // Consume up to three octal characters.
2061 unsigned Value = Str[i] - '0';
2063 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2065 Value = Value * 8 + (Str[i] - '0');
2067 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2069 Value = Value * 8 + (Str[i] - '0');
2074 return TokError("invalid octal escape sequence (out of range)");
2076 Data += (unsigned char) Value;
2080 // Otherwise recognize individual escapes.
2083 // Just reject invalid escape sequences for now.
2084 return TokError("invalid escape sequence (unrecognized character)");
2086 case 'b': Data += '\b'; break;
2087 case 'f': Data += '\f'; break;
2088 case 'n': Data += '\n'; break;
2089 case 'r': Data += '\r'; break;
2090 case 't': Data += '\t'; break;
2091 case '"': Data += '"'; break;
2092 case '\\': Data += '\\'; break;
2099 /// ParseDirectiveAscii:
2100 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2101 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2102 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2103 CheckForValidSection();
2106 if (getLexer().isNot(AsmToken::String))
2107 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2110 if (ParseEscapedString(Data))
2113 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2115 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2119 if (getLexer().is(AsmToken::EndOfStatement))
2122 if (getLexer().isNot(AsmToken::Comma))
2123 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2132 /// ParseDirectiveValue
2133 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2134 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2135 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2136 CheckForValidSection();
2139 const MCExpr *Value;
2140 SMLoc ExprLoc = getLexer().getLoc();
2141 if (ParseExpression(Value))
2144 // Special case constant expressions to match code generator.
2145 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2146 assert(Size <= 8 && "Invalid size");
2147 uint64_t IntValue = MCE->getValue();
2148 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2149 return Error(ExprLoc, "literal value out of range for directive");
2150 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2152 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2154 if (getLexer().is(AsmToken::EndOfStatement))
2157 // FIXME: Improve diagnostic.
2158 if (getLexer().isNot(AsmToken::Comma))
2159 return TokError("unexpected token in directive");
2168 /// ParseDirectiveRealValue
2169 /// ::= (.single | .double) [ expression (, expression)* ]
2170 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2171 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2172 CheckForValidSection();
2175 // We don't truly support arithmetic on floating point expressions, so we
2176 // have to manually parse unary prefixes.
2178 if (getLexer().is(AsmToken::Minus)) {
2181 } else if (getLexer().is(AsmToken::Plus))
2184 if (getLexer().isNot(AsmToken::Integer) &&
2185 getLexer().isNot(AsmToken::Real) &&
2186 getLexer().isNot(AsmToken::Identifier))
2187 return TokError("unexpected token in directive");
2189 // Convert to an APFloat.
2190 APFloat Value(Semantics);
2191 StringRef IDVal = getTok().getString();
2192 if (getLexer().is(AsmToken::Identifier)) {
2193 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2194 Value = APFloat::getInf(Semantics);
2195 else if (!IDVal.compare_lower("nan"))
2196 Value = APFloat::getNaN(Semantics, false, ~0);
2198 return TokError("invalid floating point literal");
2199 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2200 APFloat::opInvalidOp)
2201 return TokError("invalid floating point literal");
2205 // Consume the numeric token.
2208 // Emit the value as an integer.
2209 APInt AsInt = Value.bitcastToAPInt();
2210 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2211 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2213 if (getLexer().is(AsmToken::EndOfStatement))
2216 if (getLexer().isNot(AsmToken::Comma))
2217 return TokError("unexpected token in directive");
2226 /// ParseDirectiveSpace
2227 /// ::= .space expression [ , expression ]
2228 bool AsmParser::ParseDirectiveSpace() {
2229 CheckForValidSection();
2232 if (ParseAbsoluteExpression(NumBytes))
2235 int64_t FillExpr = 0;
2236 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2237 if (getLexer().isNot(AsmToken::Comma))
2238 return TokError("unexpected token in '.space' directive");
2241 if (ParseAbsoluteExpression(FillExpr))
2244 if (getLexer().isNot(AsmToken::EndOfStatement))
2245 return TokError("unexpected token in '.space' directive");
2251 return TokError("invalid number of bytes in '.space' directive");
2253 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
2254 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
2259 /// ParseDirectiveZero
2260 /// ::= .zero expression
2261 bool AsmParser::ParseDirectiveZero() {
2262 CheckForValidSection();
2265 if (ParseAbsoluteExpression(NumBytes))
2269 if (getLexer().is(AsmToken::Comma)) {
2271 if (ParseAbsoluteExpression(Val))
2275 if (getLexer().isNot(AsmToken::EndOfStatement))
2276 return TokError("unexpected token in '.zero' directive");
2280 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2285 /// ParseDirectiveFill
2286 /// ::= .fill expression , expression , expression
2287 bool AsmParser::ParseDirectiveFill() {
2288 CheckForValidSection();
2291 if (ParseAbsoluteExpression(NumValues))
2294 if (getLexer().isNot(AsmToken::Comma))
2295 return TokError("unexpected token in '.fill' directive");
2299 if (ParseAbsoluteExpression(FillSize))
2302 if (getLexer().isNot(AsmToken::Comma))
2303 return TokError("unexpected token in '.fill' directive");
2307 if (ParseAbsoluteExpression(FillExpr))
2310 if (getLexer().isNot(AsmToken::EndOfStatement))
2311 return TokError("unexpected token in '.fill' directive");
2315 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2316 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2318 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2319 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2324 /// ParseDirectiveOrg
2325 /// ::= .org expression [ , expression ]
2326 bool AsmParser::ParseDirectiveOrg() {
2327 CheckForValidSection();
2329 const MCExpr *Offset;
2330 SMLoc Loc = getTok().getLoc();
2331 if (ParseExpression(Offset))
2334 // Parse optional fill expression.
2335 int64_t FillExpr = 0;
2336 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2337 if (getLexer().isNot(AsmToken::Comma))
2338 return TokError("unexpected token in '.org' directive");
2341 if (ParseAbsoluteExpression(FillExpr))
2344 if (getLexer().isNot(AsmToken::EndOfStatement))
2345 return TokError("unexpected token in '.org' directive");
2350 // Only limited forms of relocatable expressions are accepted here, it
2351 // has to be relative to the current section. The streamer will return
2352 // 'true' if the expression wasn't evaluatable.
2353 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2354 return Error(Loc, "expected assembly-time absolute expression");
2359 /// ParseDirectiveAlign
2360 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2361 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2362 CheckForValidSection();
2364 SMLoc AlignmentLoc = getLexer().getLoc();
2366 if (ParseAbsoluteExpression(Alignment))
2370 bool HasFillExpr = false;
2371 int64_t FillExpr = 0;
2372 int64_t MaxBytesToFill = 0;
2373 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2374 if (getLexer().isNot(AsmToken::Comma))
2375 return TokError("unexpected token in directive");
2378 // The fill expression can be omitted while specifying a maximum number of
2379 // alignment bytes, e.g:
2381 if (getLexer().isNot(AsmToken::Comma)) {
2383 if (ParseAbsoluteExpression(FillExpr))
2387 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2388 if (getLexer().isNot(AsmToken::Comma))
2389 return TokError("unexpected token in directive");
2392 MaxBytesLoc = getLexer().getLoc();
2393 if (ParseAbsoluteExpression(MaxBytesToFill))
2396 if (getLexer().isNot(AsmToken::EndOfStatement))
2397 return TokError("unexpected token in directive");
2406 // Compute alignment in bytes.
2408 // FIXME: Diagnose overflow.
2409 if (Alignment >= 32) {
2410 Error(AlignmentLoc, "invalid alignment value");
2414 Alignment = 1ULL << Alignment;
2417 // Diagnose non-sensical max bytes to align.
2418 if (MaxBytesLoc.isValid()) {
2419 if (MaxBytesToFill < 1) {
2420 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2421 "many bytes, ignoring maximum bytes expression");
2425 if (MaxBytesToFill >= Alignment) {
2426 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2432 // Check whether we should use optimal code alignment for this .align
2434 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2435 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2436 ValueSize == 1 && UseCodeAlign) {
2437 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2439 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2440 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2448 /// ParseDirectiveBundleAlignMode
2449 /// ::= {.bundle_align_mode} expression
2450 bool AsmParser::ParseDirectiveBundleAlignMode() {
2451 CheckForValidSection();
2453 // Expect a single argument: an expression that evaluates to a constant
2454 // in the inclusive range 0-30.
2455 SMLoc ExprLoc = getLexer().getLoc();
2456 int64_t AlignSizePow2;
2457 if (ParseAbsoluteExpression(AlignSizePow2))
2459 else if (getLexer().isNot(AsmToken::EndOfStatement))
2460 return TokError("unexpected token after expression in"
2461 " '.bundle_align_mode' directive");
2462 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
2463 return Error(ExprLoc,
2464 "invalid bundle alignment size (expected between 0 and 30)");
2468 // Because of AlignSizePow2's verified range we can safely truncate it to
2470 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
2474 /// ParseDirectiveBundleLock
2475 /// ::= {.bundle_lock}
2476 bool AsmParser::ParseDirectiveBundleLock() {
2477 CheckForValidSection();
2479 if (getLexer().isNot(AsmToken::EndOfStatement))
2480 return TokError("unexpected token in '.bundle_lock' directive");
2483 getStreamer().EmitBundleLock();
2487 /// ParseDirectiveBundleLock
2488 /// ::= {.bundle_lock}
2489 bool AsmParser::ParseDirectiveBundleUnlock() {
2490 CheckForValidSection();
2492 if (getLexer().isNot(AsmToken::EndOfStatement))
2493 return TokError("unexpected token in '.bundle_unlock' directive");
2496 getStreamer().EmitBundleUnlock();
2500 /// ParseDirectiveSymbolAttribute
2501 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2502 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2503 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2506 SMLoc Loc = getTok().getLoc();
2508 if (ParseIdentifier(Name))
2509 return Error(Loc, "expected identifier in directive");
2511 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2513 // Assembler local symbols don't make any sense here. Complain loudly.
2514 if (Sym->isTemporary())
2515 return Error(Loc, "non-local symbol required in directive");
2517 getStreamer().EmitSymbolAttribute(Sym, Attr);
2519 if (getLexer().is(AsmToken::EndOfStatement))
2522 if (getLexer().isNot(AsmToken::Comma))
2523 return TokError("unexpected token in directive");
2532 /// ParseDirectiveComm
2533 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2534 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2535 CheckForValidSection();
2537 SMLoc IDLoc = getLexer().getLoc();
2539 if (ParseIdentifier(Name))
2540 return TokError("expected identifier in directive");
2542 // Handle the identifier as the key symbol.
2543 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2545 if (getLexer().isNot(AsmToken::Comma))
2546 return TokError("unexpected token in directive");
2550 SMLoc SizeLoc = getLexer().getLoc();
2551 if (ParseAbsoluteExpression(Size))
2554 int64_t Pow2Alignment = 0;
2555 SMLoc Pow2AlignmentLoc;
2556 if (getLexer().is(AsmToken::Comma)) {
2558 Pow2AlignmentLoc = getLexer().getLoc();
2559 if (ParseAbsoluteExpression(Pow2Alignment))
2562 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2563 if (IsLocal && LCOMM == LCOMM::NoAlignment)
2564 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2566 // If this target takes alignments in bytes (not log) validate and convert.
2567 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2568 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
2569 if (!isPowerOf2_64(Pow2Alignment))
2570 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2571 Pow2Alignment = Log2_64(Pow2Alignment);
2575 if (getLexer().isNot(AsmToken::EndOfStatement))
2576 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2580 // NOTE: a size of zero for a .comm should create a undefined symbol
2581 // but a size of .lcomm creates a bss symbol of size zero.
2583 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2584 "be less than zero");
2586 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2587 // may internally end up wanting an alignment in bytes.
2588 // FIXME: Diagnose overflow.
2589 if (Pow2Alignment < 0)
2590 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2591 "alignment, can't be less than zero");
2593 if (!Sym->isUndefined())
2594 return Error(IDLoc, "invalid symbol redefinition");
2596 // Create the Symbol as a common or local common with Size and Pow2Alignment
2598 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2602 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2606 /// ParseDirectiveAbort
2607 /// ::= .abort [... message ...]
2608 bool AsmParser::ParseDirectiveAbort() {
2609 // FIXME: Use loc from directive.
2610 SMLoc Loc = getLexer().getLoc();
2612 StringRef Str = ParseStringToEndOfStatement();
2613 if (getLexer().isNot(AsmToken::EndOfStatement))
2614 return TokError("unexpected token in '.abort' directive");
2619 Error(Loc, ".abort detected. Assembly stopping.");
2621 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2622 // FIXME: Actually abort assembly here.
2627 /// ParseDirectiveInclude
2628 /// ::= .include "filename"
2629 bool AsmParser::ParseDirectiveInclude() {
2630 if (getLexer().isNot(AsmToken::String))
2631 return TokError("expected string in '.include' directive");
2633 std::string Filename = getTok().getString();
2634 SMLoc IncludeLoc = getLexer().getLoc();
2637 if (getLexer().isNot(AsmToken::EndOfStatement))
2638 return TokError("unexpected token in '.include' directive");
2640 // Strip the quotes.
2641 Filename = Filename.substr(1, Filename.size()-2);
2643 // Attempt to switch the lexer to the included file before consuming the end
2644 // of statement to avoid losing it when we switch.
2645 if (EnterIncludeFile(Filename)) {
2646 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2653 /// ParseDirectiveIncbin
2654 /// ::= .incbin "filename"
2655 bool AsmParser::ParseDirectiveIncbin() {
2656 if (getLexer().isNot(AsmToken::String))
2657 return TokError("expected string in '.incbin' directive");
2659 std::string Filename = getTok().getString();
2660 SMLoc IncbinLoc = getLexer().getLoc();
2663 if (getLexer().isNot(AsmToken::EndOfStatement))
2664 return TokError("unexpected token in '.incbin' directive");
2666 // Strip the quotes.
2667 Filename = Filename.substr(1, Filename.size()-2);
2669 // Attempt to process the included file.
2670 if (ProcessIncbinFile(Filename)) {
2671 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2678 /// ParseDirectiveIf
2679 /// ::= .if expression
2680 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2681 TheCondStack.push_back(TheCondState);
2682 TheCondState.TheCond = AsmCond::IfCond;
2683 if (TheCondState.Ignore) {
2684 EatToEndOfStatement();
2687 if (ParseAbsoluteExpression(ExprValue))
2690 if (getLexer().isNot(AsmToken::EndOfStatement))
2691 return TokError("unexpected token in '.if' directive");
2695 TheCondState.CondMet = ExprValue;
2696 TheCondState.Ignore = !TheCondState.CondMet;
2702 /// ParseDirectiveIfb
2704 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2705 TheCondStack.push_back(TheCondState);
2706 TheCondState.TheCond = AsmCond::IfCond;
2708 if (TheCondState.Ignore) {
2709 EatToEndOfStatement();
2711 StringRef Str = ParseStringToEndOfStatement();
2713 if (getLexer().isNot(AsmToken::EndOfStatement))
2714 return TokError("unexpected token in '.ifb' directive");
2718 TheCondState.CondMet = ExpectBlank == Str.empty();
2719 TheCondState.Ignore = !TheCondState.CondMet;
2725 /// ParseDirectiveIfc
2726 /// ::= .ifc string1, string2
2727 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2728 TheCondStack.push_back(TheCondState);
2729 TheCondState.TheCond = AsmCond::IfCond;
2731 if (TheCondState.Ignore) {
2732 EatToEndOfStatement();
2734 StringRef Str1 = ParseStringToComma();
2736 if (getLexer().isNot(AsmToken::Comma))
2737 return TokError("unexpected token in '.ifc' directive");
2741 StringRef Str2 = ParseStringToEndOfStatement();
2743 if (getLexer().isNot(AsmToken::EndOfStatement))
2744 return TokError("unexpected token in '.ifc' directive");
2748 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2749 TheCondState.Ignore = !TheCondState.CondMet;
2755 /// ParseDirectiveIfdef
2756 /// ::= .ifdef symbol
2757 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2759 TheCondStack.push_back(TheCondState);
2760 TheCondState.TheCond = AsmCond::IfCond;
2762 if (TheCondState.Ignore) {
2763 EatToEndOfStatement();
2765 if (ParseIdentifier(Name))
2766 return TokError("expected identifier after '.ifdef'");
2770 MCSymbol *Sym = getContext().LookupSymbol(Name);
2773 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2775 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2776 TheCondState.Ignore = !TheCondState.CondMet;
2782 /// ParseDirectiveElseIf
2783 /// ::= .elseif expression
2784 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2785 if (TheCondState.TheCond != AsmCond::IfCond &&
2786 TheCondState.TheCond != AsmCond::ElseIfCond)
2787 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2789 TheCondState.TheCond = AsmCond::ElseIfCond;
2791 bool LastIgnoreState = false;
2792 if (!TheCondStack.empty())
2793 LastIgnoreState = TheCondStack.back().Ignore;
2794 if (LastIgnoreState || TheCondState.CondMet) {
2795 TheCondState.Ignore = true;
2796 EatToEndOfStatement();
2800 if (ParseAbsoluteExpression(ExprValue))
2803 if (getLexer().isNot(AsmToken::EndOfStatement))
2804 return TokError("unexpected token in '.elseif' directive");
2807 TheCondState.CondMet = ExprValue;
2808 TheCondState.Ignore = !TheCondState.CondMet;
2814 /// ParseDirectiveElse
2816 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2817 if (getLexer().isNot(AsmToken::EndOfStatement))
2818 return TokError("unexpected token in '.else' directive");
2822 if (TheCondState.TheCond != AsmCond::IfCond &&
2823 TheCondState.TheCond != AsmCond::ElseIfCond)
2824 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2826 TheCondState.TheCond = AsmCond::ElseCond;
2827 bool LastIgnoreState = false;
2828 if (!TheCondStack.empty())
2829 LastIgnoreState = TheCondStack.back().Ignore;
2830 if (LastIgnoreState || TheCondState.CondMet)
2831 TheCondState.Ignore = true;
2833 TheCondState.Ignore = false;
2838 /// ParseDirectiveEndIf
2840 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2841 if (getLexer().isNot(AsmToken::EndOfStatement))
2842 return TokError("unexpected token in '.endif' directive");
2846 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2847 TheCondStack.empty())
2848 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2850 if (!TheCondStack.empty()) {
2851 TheCondState = TheCondStack.back();
2852 TheCondStack.pop_back();
2858 /// ParseDirectiveFile
2859 /// ::= .file [number] filename
2860 /// ::= .file number directory filename
2861 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2862 // FIXME: I'm not sure what this is.
2863 int64_t FileNumber = -1;
2864 SMLoc FileNumberLoc = getLexer().getLoc();
2865 if (getLexer().is(AsmToken::Integer)) {
2866 FileNumber = getTok().getIntVal();
2870 return TokError("file number less than one");
2873 if (getLexer().isNot(AsmToken::String))
2874 return TokError("unexpected token in '.file' directive");
2876 // Usually the directory and filename together, otherwise just the directory.
2877 StringRef Path = getTok().getString();
2878 Path = Path.substr(1, Path.size()-2);
2881 StringRef Directory;
2883 if (getLexer().is(AsmToken::String)) {
2884 if (FileNumber == -1)
2885 return TokError("explicit path specified, but no file number");
2886 Filename = getTok().getString();
2887 Filename = Filename.substr(1, Filename.size()-2);
2894 if (getLexer().isNot(AsmToken::EndOfStatement))
2895 return TokError("unexpected token in '.file' directive");
2897 if (FileNumber == -1)
2898 getStreamer().EmitFileDirective(Filename);
2900 if (getContext().getGenDwarfForAssembly() == true)
2901 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2902 "used to generate dwarf debug info for assembly code");
2904 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2905 Error(FileNumberLoc, "file number already allocated");
2911 /// ParseDirectiveLine
2912 /// ::= .line [number]
2913 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2914 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2915 if (getLexer().isNot(AsmToken::Integer))
2916 return TokError("unexpected token in '.line' directive");
2918 int64_t LineNumber = getTok().getIntVal();
2922 // FIXME: Do something with the .line.
2925 if (getLexer().isNot(AsmToken::EndOfStatement))
2926 return TokError("unexpected token in '.line' directive");
2932 /// ParseDirectiveLoc
2933 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2934 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2935 /// The first number is a file number, must have been previously assigned with
2936 /// a .file directive, the second number is the line number and optionally the
2937 /// third number is a column position (zero if not specified). The remaining
2938 /// optional items are .loc sub-directives.
2939 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2941 if (getLexer().isNot(AsmToken::Integer))
2942 return TokError("unexpected token in '.loc' directive");
2943 int64_t FileNumber = getTok().getIntVal();
2945 return TokError("file number less than one in '.loc' directive");
2946 if (!getContext().isValidDwarfFileNumber(FileNumber))
2947 return TokError("unassigned file number in '.loc' directive");
2950 int64_t LineNumber = 0;
2951 if (getLexer().is(AsmToken::Integer)) {
2952 LineNumber = getTok().getIntVal();
2954 return TokError("line number less than one in '.loc' directive");
2958 int64_t ColumnPos = 0;
2959 if (getLexer().is(AsmToken::Integer)) {
2960 ColumnPos = getTok().getIntVal();
2962 return TokError("column position less than zero in '.loc' directive");
2966 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2968 int64_t Discriminator = 0;
2969 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2971 if (getLexer().is(AsmToken::EndOfStatement))
2975 SMLoc Loc = getTok().getLoc();
2976 if (getParser().ParseIdentifier(Name))
2977 return TokError("unexpected token in '.loc' directive");
2979 if (Name == "basic_block")
2980 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2981 else if (Name == "prologue_end")
2982 Flags |= DWARF2_FLAG_PROLOGUE_END;
2983 else if (Name == "epilogue_begin")
2984 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2985 else if (Name == "is_stmt") {
2986 Loc = getTok().getLoc();
2987 const MCExpr *Value;
2988 if (getParser().ParseExpression(Value))
2990 // The expression must be the constant 0 or 1.
2991 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2992 int Value = MCE->getValue();
2994 Flags &= ~DWARF2_FLAG_IS_STMT;
2995 else if (Value == 1)
2996 Flags |= DWARF2_FLAG_IS_STMT;
2998 return Error(Loc, "is_stmt value not 0 or 1");
3001 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3004 else if (Name == "isa") {
3005 Loc = getTok().getLoc();
3006 const MCExpr *Value;
3007 if (getParser().ParseExpression(Value))
3009 // The expression must be a constant greater or equal to 0.
3010 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3011 int Value = MCE->getValue();
3013 return Error(Loc, "isa number less than zero");
3017 return Error(Loc, "isa number not a constant value");
3020 else if (Name == "discriminator") {
3021 if (getParser().ParseAbsoluteExpression(Discriminator))
3025 return Error(Loc, "unknown sub-directive in '.loc' directive");
3028 if (getLexer().is(AsmToken::EndOfStatement))
3033 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3034 Isa, Discriminator, StringRef());
3039 /// ParseDirectiveStabs
3040 /// ::= .stabs string, number, number, number
3041 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
3042 SMLoc DirectiveLoc) {
3043 return TokError("unsupported directive '" + Directive + "'");
3046 /// ParseDirectiveCFISections
3047 /// ::= .cfi_sections section [, section]
3048 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
3049 SMLoc DirectiveLoc) {
3054 if (getParser().ParseIdentifier(Name))
3055 return TokError("Expected an identifier");
3057 if (Name == ".eh_frame")
3059 else if (Name == ".debug_frame")
3062 if (getLexer().is(AsmToken::Comma)) {
3065 if (getParser().ParseIdentifier(Name))
3066 return TokError("Expected an identifier");
3068 if (Name == ".eh_frame")
3070 else if (Name == ".debug_frame")
3074 getStreamer().EmitCFISections(EH, Debug);
3079 /// ParseDirectiveCFIStartProc
3080 /// ::= .cfi_startproc
3081 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
3082 SMLoc DirectiveLoc) {
3083 getStreamer().EmitCFIStartProc();
3087 /// ParseDirectiveCFIEndProc
3088 /// ::= .cfi_endproc
3089 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
3090 getStreamer().EmitCFIEndProc();
3094 /// ParseRegisterOrRegisterNumber - parse register name or number.
3095 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3096 SMLoc DirectiveLoc) {
3099 if (getLexer().isNot(AsmToken::Integer)) {
3100 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3103 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
3105 return getParser().ParseAbsoluteExpression(Register);
3110 /// ParseDirectiveCFIDefCfa
3111 /// ::= .cfi_def_cfa register, offset
3112 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3113 SMLoc DirectiveLoc) {
3114 int64_t Register = 0;
3115 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3118 if (getLexer().isNot(AsmToken::Comma))
3119 return TokError("unexpected token in directive");
3123 if (getParser().ParseAbsoluteExpression(Offset))
3126 getStreamer().EmitCFIDefCfa(Register, Offset);
3130 /// ParseDirectiveCFIDefCfaOffset
3131 /// ::= .cfi_def_cfa_offset offset
3132 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3133 SMLoc DirectiveLoc) {
3135 if (getParser().ParseAbsoluteExpression(Offset))
3138 getStreamer().EmitCFIDefCfaOffset(Offset);
3142 /// ParseDirectiveCFIAdjustCfaOffset
3143 /// ::= .cfi_adjust_cfa_offset adjustment
3144 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3145 SMLoc DirectiveLoc) {
3146 int64_t Adjustment = 0;
3147 if (getParser().ParseAbsoluteExpression(Adjustment))
3150 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3154 /// ParseDirectiveCFIDefCfaRegister
3155 /// ::= .cfi_def_cfa_register register
3156 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3157 SMLoc DirectiveLoc) {
3158 int64_t Register = 0;
3159 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3162 getStreamer().EmitCFIDefCfaRegister(Register);
3166 /// ParseDirectiveCFIOffset
3167 /// ::= .cfi_offset register, offset
3168 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3169 int64_t Register = 0;
3172 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3175 if (getLexer().isNot(AsmToken::Comma))
3176 return TokError("unexpected token in directive");
3179 if (getParser().ParseAbsoluteExpression(Offset))
3182 getStreamer().EmitCFIOffset(Register, Offset);
3186 /// ParseDirectiveCFIRelOffset
3187 /// ::= .cfi_rel_offset register, offset
3188 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3189 SMLoc DirectiveLoc) {
3190 int64_t Register = 0;
3192 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3195 if (getLexer().isNot(AsmToken::Comma))
3196 return TokError("unexpected token in directive");
3200 if (getParser().ParseAbsoluteExpression(Offset))
3203 getStreamer().EmitCFIRelOffset(Register, Offset);
3207 static bool isValidEncoding(int64_t Encoding) {
3208 if (Encoding & ~0xff)
3211 if (Encoding == dwarf::DW_EH_PE_omit)
3214 const unsigned Format = Encoding & 0xf;
3215 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3216 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3217 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3218 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3221 const unsigned Application = Encoding & 0x70;
3222 if (Application != dwarf::DW_EH_PE_absptr &&
3223 Application != dwarf::DW_EH_PE_pcrel)
3229 /// ParseDirectiveCFIPersonalityOrLsda
3230 /// ::= .cfi_personality encoding, [symbol_name]
3231 /// ::= .cfi_lsda encoding, [symbol_name]
3232 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
3233 SMLoc DirectiveLoc) {
3234 int64_t Encoding = 0;
3235 if (getParser().ParseAbsoluteExpression(Encoding))
3237 if (Encoding == dwarf::DW_EH_PE_omit)
3240 if (!isValidEncoding(Encoding))
3241 return TokError("unsupported encoding.");
3243 if (getLexer().isNot(AsmToken::Comma))
3244 return TokError("unexpected token in directive");
3248 if (getParser().ParseIdentifier(Name))
3249 return TokError("expected identifier in directive");
3251 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3253 if (IDVal == ".cfi_personality")
3254 getStreamer().EmitCFIPersonality(Sym, Encoding);
3256 assert(IDVal == ".cfi_lsda");
3257 getStreamer().EmitCFILsda(Sym, Encoding);
3262 /// ParseDirectiveCFIRememberState
3263 /// ::= .cfi_remember_state
3264 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3265 SMLoc DirectiveLoc) {
3266 getStreamer().EmitCFIRememberState();
3270 /// ParseDirectiveCFIRestoreState
3271 /// ::= .cfi_remember_state
3272 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3273 SMLoc DirectiveLoc) {
3274 getStreamer().EmitCFIRestoreState();
3278 /// ParseDirectiveCFISameValue
3279 /// ::= .cfi_same_value register
3280 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3281 SMLoc DirectiveLoc) {
3282 int64_t Register = 0;
3284 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3287 getStreamer().EmitCFISameValue(Register);
3292 /// ParseDirectiveCFIRestore
3293 /// ::= .cfi_restore register
3294 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
3295 SMLoc DirectiveLoc) {
3296 int64_t Register = 0;
3297 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3300 getStreamer().EmitCFIRestore(Register);
3305 /// ParseDirectiveCFIEscape
3306 /// ::= .cfi_escape expression[,...]
3307 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3308 SMLoc DirectiveLoc) {
3311 if (getParser().ParseAbsoluteExpression(CurrValue))
3314 Values.push_back((uint8_t)CurrValue);
3316 while (getLexer().is(AsmToken::Comma)) {
3319 if (getParser().ParseAbsoluteExpression(CurrValue))
3322 Values.push_back((uint8_t)CurrValue);
3325 getStreamer().EmitCFIEscape(Values);
3329 /// ParseDirectiveCFISignalFrame
3330 /// ::= .cfi_signal_frame
3331 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3332 SMLoc DirectiveLoc) {
3333 if (getLexer().isNot(AsmToken::EndOfStatement))
3334 return Error(getLexer().getLoc(),
3335 "unexpected token in '" + Directive + "' directive");
3337 getStreamer().EmitCFISignalFrame();
3342 /// ParseDirectiveCFIUndefined
3343 /// ::= .cfi_undefined register
3344 bool GenericAsmParser::ParseDirectiveCFIUndefined(StringRef Directive,
3345 SMLoc DirectiveLoc) {
3346 int64_t Register = 0;
3348 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3351 getStreamer().EmitCFIUndefined(Register);
3356 /// ParseDirectiveCFIRegister
3357 /// ::= .cfi_register register, register
3358 bool GenericAsmParser::ParseDirectiveCFIRegister(StringRef Directive,
3359 SMLoc DirectiveLoc) {
3360 int64_t Register1 = 0;
3362 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3365 if (getLexer().isNot(AsmToken::Comma))
3366 return TokError("unexpected token in directive");
3369 int64_t Register2 = 0;
3371 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3374 getStreamer().EmitCFIRegister(Register1, Register2);
3379 /// ParseDirectiveMacrosOnOff
3382 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3383 SMLoc DirectiveLoc) {
3384 if (getLexer().isNot(AsmToken::EndOfStatement))
3385 return Error(getLexer().getLoc(),
3386 "unexpected token in '" + Directive + "' directive");
3388 getParser().MacrosEnabled = Directive == ".macros_on";
3393 /// ParseDirectiveMacro
3394 /// ::= .macro name [parameters]
3395 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3396 SMLoc DirectiveLoc) {
3398 if (getParser().ParseIdentifier(Name))
3399 return TokError("expected identifier in '.macro' directive");
3401 MacroParameters Parameters;
3402 // Argument delimiter is initially unknown. It will be set by
3403 // ParseMacroArgument()
3404 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3405 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3407 MacroParameter Parameter;
3408 if (getParser().ParseIdentifier(Parameter.first))
3409 return TokError("expected identifier in '.macro' directive");
3411 if (getLexer().is(AsmToken::Equal)) {
3413 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3417 Parameters.push_back(Parameter);
3419 if (getLexer().is(AsmToken::Comma))
3421 else if (getLexer().is(AsmToken::EndOfStatement))
3426 // Eat the end of statement.
3429 AsmToken EndToken, StartToken = getTok();
3431 // Lex the macro definition.
3433 // Check whether we have reached the end of the file.
3434 if (getLexer().is(AsmToken::Eof))
3435 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3437 // Otherwise, check whether we have reach the .endmacro.
3438 if (getLexer().is(AsmToken::Identifier) &&
3439 (getTok().getIdentifier() == ".endm" ||
3440 getTok().getIdentifier() == ".endmacro")) {
3441 EndToken = getTok();
3443 if (getLexer().isNot(AsmToken::EndOfStatement))
3444 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3449 // Otherwise, scan til the end of the statement.
3450 getParser().EatToEndOfStatement();
3453 if (getParser().MacroMap.lookup(Name)) {
3454 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3457 const char *BodyStart = StartToken.getLoc().getPointer();
3458 const char *BodyEnd = EndToken.getLoc().getPointer();
3459 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3460 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3464 /// ParseDirectiveEndMacro
3467 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3468 SMLoc DirectiveLoc) {
3469 if (getLexer().isNot(AsmToken::EndOfStatement))
3470 return TokError("unexpected token in '" + Directive + "' directive");
3472 // If we are inside a macro instantiation, terminate the current
3474 if (!getParser().ActiveMacros.empty()) {
3475 getParser().HandleMacroExit();
3479 // Otherwise, this .endmacro is a stray entry in the file; well formed
3480 // .endmacro directives are handled during the macro definition parsing.
3481 return TokError("unexpected '" + Directive + "' in file, "
3482 "no current macro definition");
3485 /// ParseDirectivePurgeMacro
3487 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3488 SMLoc DirectiveLoc) {
3490 if (getParser().ParseIdentifier(Name))
3491 return TokError("expected identifier in '.purgem' directive");
3493 if (getLexer().isNot(AsmToken::EndOfStatement))
3494 return TokError("unexpected token in '.purgem' directive");
3496 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3497 if (I == getParser().MacroMap.end())
3498 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3500 // Undefine the macro.
3501 delete I->getValue();
3502 getParser().MacroMap.erase(I);
3506 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3507 getParser().CheckForValidSection();
3509 const MCExpr *Value;
3511 if (getParser().ParseExpression(Value))
3514 if (getLexer().isNot(AsmToken::EndOfStatement))
3515 return TokError("unexpected token in directive");
3517 if (DirName[1] == 's')
3518 getStreamer().EmitSLEB128Value(Value);
3520 getStreamer().EmitULEB128Value(Value);
3525 Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3526 AsmToken EndToken, StartToken = getTok();
3528 unsigned NestLevel = 0;
3530 // Check whether we have reached the end of the file.
3531 if (getLexer().is(AsmToken::Eof)) {
3532 Error(DirectiveLoc, "no matching '.endr' in definition");
3536 if (Lexer.is(AsmToken::Identifier) &&
3537 (getTok().getIdentifier() == ".rept")) {
3541 // Otherwise, check whether we have reached the .endr.
3542 if (Lexer.is(AsmToken::Identifier) &&
3543 getTok().getIdentifier() == ".endr") {
3544 if (NestLevel == 0) {
3545 EndToken = getTok();
3547 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3548 TokError("unexpected token in '.endr' directive");
3556 // Otherwise, scan till the end of the statement.
3557 EatToEndOfStatement();
3560 const char *BodyStart = StartToken.getLoc().getPointer();
3561 const char *BodyEnd = EndToken.getLoc().getPointer();
3562 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3564 // We Are Anonymous.
3566 MacroParameters Parameters;
3567 return new Macro(Name, Body, Parameters);
3570 void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3571 raw_svector_ostream &OS) {
3574 MemoryBuffer *Instantiation =
3575 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3577 // Create the macro instantiation object and add to the current macro
3578 // instantiation stack.
3579 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3583 ActiveMacros.push_back(MI);
3585 // Jump to the macro instantiation and prime the lexer.
3586 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3587 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3591 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3593 if (ParseAbsoluteExpression(Count))
3594 return TokError("unexpected token in '.rept' directive");
3597 return TokError("Count is negative");
3599 if (Lexer.isNot(AsmToken::EndOfStatement))
3600 return TokError("unexpected token in '.rept' directive");
3602 // Eat the end of statement.
3605 // Lex the rept definition.
3606 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3610 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3611 // to hold the macro body with substitutions.
3612 SmallString<256> Buf;
3613 MacroParameters Parameters;
3615 raw_svector_ostream OS(Buf);
3617 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3620 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3625 /// ParseDirectiveIrp
3626 /// ::= .irp symbol,values
3627 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3628 MacroParameters Parameters;
3629 MacroParameter Parameter;
3631 if (ParseIdentifier(Parameter.first))
3632 return TokError("expected identifier in '.irp' directive");
3634 Parameters.push_back(Parameter);
3636 if (Lexer.isNot(AsmToken::Comma))
3637 return TokError("expected comma in '.irp' directive");
3642 if (ParseMacroArguments(0, A))
3645 // Eat the end of statement.
3648 // Lex the irp definition.
3649 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3653 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3654 // to hold the macro body with substitutions.
3655 SmallString<256> Buf;
3656 raw_svector_ostream OS(Buf);
3658 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3659 MacroArguments Args;
3662 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3666 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3671 /// ParseDirectiveIrpc
3672 /// ::= .irpc symbol,values
3673 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3674 MacroParameters Parameters;
3675 MacroParameter Parameter;
3677 if (ParseIdentifier(Parameter.first))
3678 return TokError("expected identifier in '.irpc' directive");
3680 Parameters.push_back(Parameter);
3682 if (Lexer.isNot(AsmToken::Comma))
3683 return TokError("expected comma in '.irpc' directive");
3688 if (ParseMacroArguments(0, A))
3691 if (A.size() != 1 || A.front().size() != 1)
3692 return TokError("unexpected token in '.irpc' directive");
3694 // Eat the end of statement.
3697 // Lex the irpc definition.
3698 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3702 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3703 // to hold the macro body with substitutions.
3704 SmallString<256> Buf;
3705 raw_svector_ostream OS(Buf);
3707 StringRef Values = A.front().front().getString();
3708 std::size_t I, End = Values.size();
3709 for (I = 0; I < End; ++I) {
3711 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3713 MacroArguments Args;
3714 Args.push_back(Arg);
3716 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3720 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3725 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3726 if (ActiveMacros.empty())
3727 return TokError("unmatched '.endr' directive");
3729 // The only .repl that should get here are the ones created by
3730 // InstantiateMacroLikeBody.
3731 assert(getLexer().is(AsmToken::EndOfStatement));
3737 bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3738 const MCExpr *Value;
3739 SMLoc ExprLoc = getLexer().getLoc();
3740 if (ParseExpression(Value))
3742 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3744 return Error(ExprLoc, "unexpected expression in _emit");
3745 uint64_t IntValue = MCE->getValue();
3746 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3747 return Error(ExprLoc, "literal value out of range for directive");
3749 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3753 bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3754 unsigned &NumOutputs, unsigned &NumInputs,
3755 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
3756 SmallVectorImpl<std::string> &Constraints,
3757 SmallVectorImpl<std::string> &Clobbers,
3758 const MCInstrInfo *MII,
3759 const MCInstPrinter *IP,
3760 MCAsmParserSemaCallback &SI) {
3761 SmallVector<void *, 4> InputDecls;
3762 SmallVector<void *, 4> OutputDecls;
3763 SmallVector<bool, 4> InputDeclsOffsetOf;
3764 SmallVector<bool, 4> OutputDeclsOffsetOf;
3765 SmallVector<std::string, 4> InputConstraints;
3766 SmallVector<std::string, 4> OutputConstraints;
3767 std::set<std::string> ClobberRegs;
3769 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
3774 // While we have input, parse each statement.
3775 unsigned InputIdx = 0;
3776 unsigned OutputIdx = 0;
3777 while (getLexer().isNot(AsmToken::Eof)) {
3778 ParseStatementInfo Info(&AsmStrRewrites);
3779 if (ParseStatement(Info))
3782 if (Info.ParseError)
3785 if (Info.Opcode != ~0U) {
3786 const MCInstrDesc &Desc = MII->get(Info.Opcode);
3788 // Build the list of clobbers, outputs and inputs.
3789 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3790 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
3793 if (Operand->isImm()) {
3794 if (Operand->needAsmRewrite())
3795 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3796 Operand->getStartLoc()));
3800 // Register operand.
3801 if (Operand->isReg() && !Operand->isOffsetOf()) {
3802 unsigned NumDefs = Desc.getNumDefs();
3804 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3806 raw_string_ostream OS(Reg);
3807 IP->printRegName(OS, Operand->getReg());
3808 ClobberRegs.insert(StringRef(OS.str()));
3813 // Expr/Input or Output.
3815 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3818 bool isOutput = (i == 1) && Desc.mayStore();
3819 if (!Operand->isOffsetOf() && Operand->needSizeDirective())
3820 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
3821 Operand->getStartLoc(),
3823 Operand->getMemSize()));
3825 std::string Constraint = "=";
3827 OutputDecls.push_back(OpDecl);
3828 OutputDeclsOffsetOf.push_back(Operand->isOffsetOf());
3829 Constraint += Operand->getConstraint().str();
3830 OutputConstraints.push_back(Constraint);
3831 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
3832 Operand->getStartLoc(),
3833 Operand->getNameLen()));
3835 InputDecls.push_back(OpDecl);
3836 InputDeclsOffsetOf.push_back(Operand->isOffsetOf());
3837 InputConstraints.push_back(Operand->getConstraint().str());
3838 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
3839 Operand->getStartLoc(),
3840 Operand->getNameLen()));
3847 // Set the number of Outputs and Inputs.
3848 NumOutputs = OutputDecls.size();
3849 NumInputs = InputDecls.size();
3851 // Set the unique clobbers.
3852 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3853 E = ClobberRegs.end(); I != E; ++I)
3854 Clobbers.push_back(*I);
3856 // Merge the various outputs and inputs. Output are expected first.
3857 if (NumOutputs || NumInputs) {
3858 unsigned NumExprs = NumOutputs + NumInputs;
3859 OpDecls.resize(NumExprs);
3860 Constraints.resize(NumExprs);
3861 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3862 // constraint for offsetof. This needs to be cleaned up!
3863 for (unsigned i = 0; i < NumOutputs; ++i) {
3864 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsOffsetOf[i]);
3865 Constraints[i] = OutputDeclsOffsetOf[i] ? "=r" : OutputConstraints[i];
3867 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
3868 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsOffsetOf[i]);
3869 Constraints[j] = InputDeclsOffsetOf[i] ? "r" : InputConstraints[i];
3873 // Build the IR assembly string.
3874 std::string AsmStringIR;
3875 AsmRewriteKind PrevKind = AOK_Imm;
3876 raw_string_ostream OS(AsmStringIR);
3877 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
3878 for (SmallVectorImpl<struct AsmRewrite>::iterator
3879 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3880 const char *Loc = (*I).Loc.getPointer();
3882 AsmRewriteKind Kind = (*I).Kind;
3884 // Emit everything up to the immediate/expression. If the previous rewrite
3885 // was a size directive, then this has already been done.
3886 if (PrevKind != AOK_SizeDirective)
3887 OS << StringRef(Start, Loc - Start);
3890 // Skip the original expression.
3891 if (Kind == AOK_Skip) {
3892 Start = Loc + (*I).Len;
3896 // Rewrite expressions in $N notation.
3914 case AOK_SizeDirective:
3917 case 8: OS << "byte ptr "; break;
3918 case 16: OS << "word ptr "; break;
3919 case 32: OS << "dword ptr "; break;
3920 case 64: OS << "qword ptr "; break;
3921 case 80: OS << "xword ptr "; break;
3922 case 128: OS << "xmmword ptr "; break;
3923 case 256: OS << "ymmword ptr "; break;
3929 case AOK_DotOperator:
3934 // Skip the original expression.
3935 if (Kind != AOK_SizeDirective)
3936 Start = Loc + (*I).Len;
3939 // Emit the remainder of the asm string.
3940 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3941 if (Start != AsmEnd)
3942 OS << StringRef(Start, AsmEnd - Start);
3944 AsmString = OS.str();
3948 /// \brief Create an MCAsmParser instance.
3949 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3950 MCContext &C, MCStreamer &Out,
3951 const MCAsmInfo &MAI) {
3952 return new AsmParser(SM, C, Out, MAI);