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");
1217 if (!ParsingInlineAsm)
1220 // If we are generating dwarf for assembly source files then gather the
1221 // info to make a dwarf label entry for this label if needed.
1222 if (getContext().getGenDwarfForAssembly())
1223 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1226 // Consume any end of statement token, if present, to avoid spurious
1227 // AddBlankLine calls().
1228 if (Lexer.is(AsmToken::EndOfStatement)) {
1230 if (Lexer.is(AsmToken::Eof))
1237 case AsmToken::Equal:
1238 // identifier '=' ... -> assignment statement
1241 return ParseAssignment(IDVal, true);
1243 default: // Normal instruction or directive.
1247 // If macros are enabled, check to see if this is a macro instantiation.
1249 if (const Macro *M = MacroMap.lookup(IDVal))
1250 return HandleMacroEntry(IDVal, IDLoc, M);
1252 // Otherwise, we have a normal instruction or directive.
1253 if (IDVal[0] == '.' && IDVal != ".") {
1255 // Target hook for parsing target specific directives.
1256 if (!getTargetParser().ParseDirective(ID))
1259 // Assembler features
1260 if (IDVal == ".set" || IDVal == ".equ")
1261 return ParseDirectiveSet(IDVal, true);
1262 if (IDVal == ".equiv")
1263 return ParseDirectiveSet(IDVal, false);
1267 if (IDVal == ".ascii")
1268 return ParseDirectiveAscii(IDVal, false);
1269 if (IDVal == ".asciz" || IDVal == ".string")
1270 return ParseDirectiveAscii(IDVal, true);
1272 if (IDVal == ".byte")
1273 return ParseDirectiveValue(1);
1274 if (IDVal == ".short")
1275 return ParseDirectiveValue(2);
1276 if (IDVal == ".value")
1277 return ParseDirectiveValue(2);
1278 if (IDVal == ".2byte")
1279 return ParseDirectiveValue(2);
1280 if (IDVal == ".long")
1281 return ParseDirectiveValue(4);
1282 if (IDVal == ".int")
1283 return ParseDirectiveValue(4);
1284 if (IDVal == ".4byte")
1285 return ParseDirectiveValue(4);
1286 if (IDVal == ".quad")
1287 return ParseDirectiveValue(8);
1288 if (IDVal == ".8byte")
1289 return ParseDirectiveValue(8);
1290 if (IDVal == ".single" || IDVal == ".float")
1291 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1292 if (IDVal == ".double")
1293 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1295 if (IDVal == ".align") {
1296 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1297 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1299 if (IDVal == ".align32") {
1300 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1301 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1303 if (IDVal == ".balign")
1304 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1305 if (IDVal == ".balignw")
1306 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1307 if (IDVal == ".balignl")
1308 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1309 if (IDVal == ".p2align")
1310 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1311 if (IDVal == ".p2alignw")
1312 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1313 if (IDVal == ".p2alignl")
1314 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1316 if (IDVal == ".bundle_align_mode")
1317 return ParseDirectiveBundleAlignMode();
1318 if (IDVal == ".bundle_lock")
1319 return ParseDirectiveBundleLock();
1320 if (IDVal == ".bundle_unlock")
1321 return ParseDirectiveBundleUnlock();
1323 if (IDVal == ".org")
1324 return ParseDirectiveOrg();
1326 if (IDVal == ".fill")
1327 return ParseDirectiveFill();
1328 if (IDVal == ".space" || IDVal == ".skip")
1329 return ParseDirectiveSpace();
1330 if (IDVal == ".zero")
1331 return ParseDirectiveZero();
1333 // Symbol attribute directives
1335 if (IDVal == ".extern") {
1336 EatToEndOfStatement(); // .extern is the default, ignore it.
1339 if (IDVal == ".globl" || IDVal == ".global")
1340 return ParseDirectiveSymbolAttribute(MCSA_Global);
1341 if (IDVal == ".indirect_symbol")
1342 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1343 if (IDVal == ".lazy_reference")
1344 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1345 if (IDVal == ".no_dead_strip")
1346 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1347 if (IDVal == ".symbol_resolver")
1348 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1349 if (IDVal == ".private_extern")
1350 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1351 if (IDVal == ".reference")
1352 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1353 if (IDVal == ".weak_definition")
1354 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1355 if (IDVal == ".weak_reference")
1356 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1357 if (IDVal == ".weak_def_can_be_hidden")
1358 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1360 if (IDVal == ".comm" || IDVal == ".common")
1361 return ParseDirectiveComm(/*IsLocal=*/false);
1362 if (IDVal == ".lcomm")
1363 return ParseDirectiveComm(/*IsLocal=*/true);
1365 if (IDVal == ".abort")
1366 return ParseDirectiveAbort();
1367 if (IDVal == ".include")
1368 return ParseDirectiveInclude();
1369 if (IDVal == ".incbin")
1370 return ParseDirectiveIncbin();
1372 if (IDVal == ".code16" || IDVal == ".code16gcc")
1373 return TokError(Twine(IDVal) + " not supported yet");
1375 // Macro-like directives
1376 if (IDVal == ".rept")
1377 return ParseDirectiveRept(IDLoc);
1378 if (IDVal == ".irp")
1379 return ParseDirectiveIrp(IDLoc);
1380 if (IDVal == ".irpc")
1381 return ParseDirectiveIrpc(IDLoc);
1382 if (IDVal == ".endr")
1383 return ParseDirectiveEndr(IDLoc);
1385 // Look up the handler in the handler table.
1386 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1387 DirectiveMap.lookup(IDVal);
1389 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1392 return Error(IDLoc, "unknown directive");
1396 if (ParsingInlineAsm && IDVal == "_emit")
1397 return ParseDirectiveEmit(IDLoc, Info);
1399 CheckForValidSection();
1401 // Canonicalize the opcode to lower case.
1402 SmallString<128> OpcodeStr;
1403 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1404 OpcodeStr.push_back(tolower(IDVal[i]));
1406 ParseInstructionInfo IInfo(Info.AsmRewrites);
1407 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1408 IDLoc,Info.ParsedOperands);
1409 Info.ParseError = HadError;
1411 // Dump the parsed representation, if requested.
1412 if (getShowParsedOperands()) {
1413 SmallString<256> Str;
1414 raw_svector_ostream OS(Str);
1415 OS << "parsed instruction: [";
1416 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1419 Info.ParsedOperands[i]->print(OS);
1423 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1426 // If we are generating dwarf for assembly source files and the current
1427 // section is the initial text section then generate a .loc directive for
1429 if (!HadError && getContext().getGenDwarfForAssembly() &&
1430 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
1432 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1434 // If we previously parsed a cpp hash file line comment then make sure the
1435 // current Dwarf File is for the CppHashFilename if not then emit the
1436 // Dwarf File table for it and adjust the line number for the .loc.
1437 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1438 getContext().getMCDwarfFiles();
1439 if (CppHashFilename.size() != 0) {
1440 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1442 getStreamer().EmitDwarfFileDirective(
1443 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1445 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
1446 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1449 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1450 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1451 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1455 // If parsing succeeded, match the instruction.
1458 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1459 Info.ParsedOperands,
1464 // Don't skip the rest of the line, the instruction parser is responsible for
1469 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1470 /// since they may not be able to be tokenized to get to the end of line token.
1471 void AsmParser::EatToEndOfLine() {
1472 if (!Lexer.is(AsmToken::EndOfStatement))
1473 Lexer.LexUntilEndOfLine();
1478 /// ParseCppHashLineFilenameComment as this:
1479 /// ::= # number "filename"
1480 /// or just as a full line comment if it doesn't have a number and a string.
1481 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1482 Lex(); // Eat the hash token.
1484 if (getLexer().isNot(AsmToken::Integer)) {
1485 // Consume the line since in cases it is not a well-formed line directive,
1486 // as if were simply a full line comment.
1491 int64_t LineNumber = getTok().getIntVal();
1494 if (getLexer().isNot(AsmToken::String)) {
1499 StringRef Filename = getTok().getString();
1500 // Get rid of the enclosing quotes.
1501 Filename = Filename.substr(1, Filename.size()-2);
1503 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1505 CppHashFilename = Filename;
1506 CppHashLineNumber = LineNumber;
1507 CppHashBuf = CurBuffer;
1509 // Ignore any trailing characters, they're just comment.
1514 /// DiagHandler - will use the last parsed cpp hash line filename comment
1515 /// for the Filename and LineNo if any in the diagnostic.
1516 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1517 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1518 raw_ostream &OS = errs();
1520 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1521 const SMLoc &DiagLoc = Diag.getLoc();
1522 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1523 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1525 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1526 // before printing the message.
1527 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1528 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1529 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1530 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1533 // If we have not parsed a cpp hash line filename comment or the source
1534 // manager changed or buffer changed (like in a nested include) then just
1535 // print the normal diagnostic using its Filename and LineNo.
1536 if (!Parser->CppHashLineNumber ||
1537 &DiagSrcMgr != &Parser->SrcMgr ||
1538 DiagBuf != CppHashBuf) {
1539 if (Parser->SavedDiagHandler)
1540 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1546 // Use the CppHashFilename and calculate a line number based on the
1547 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1549 const std::string Filename = Parser->CppHashFilename;
1551 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1552 int CppHashLocLineNo =
1553 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1554 int LineNo = Parser->CppHashLineNumber - 1 +
1555 (DiagLocLineNo - CppHashLocLineNo);
1557 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1558 Filename, LineNo, Diag.getColumnNo(),
1559 Diag.getKind(), Diag.getMessage(),
1560 Diag.getLineContents(), Diag.getRanges());
1562 if (Parser->SavedDiagHandler)
1563 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1565 NewDiag.print(0, OS);
1568 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1569 // difference being that that function accepts '@' as part of identifiers and
1570 // we can't do that. AsmLexer.cpp should probably be changed to handle
1571 // '@' as a special case when needed.
1572 static bool isIdentifierChar(char c) {
1573 return isalnum(c) || c == '_' || c == '$' || c == '.';
1576 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1577 const MacroParameters &Parameters,
1578 const MacroArguments &A,
1580 unsigned NParameters = Parameters.size();
1581 if (NParameters != 0 && NParameters != A.size())
1582 return Error(L, "Wrong number of arguments");
1584 // A macro without parameters is handled differently on Darwin:
1585 // gas accepts no arguments and does no substitutions
1586 while (!Body.empty()) {
1587 // Scan for the next substitution.
1588 std::size_t End = Body.size(), Pos = 0;
1589 for (; Pos != End; ++Pos) {
1590 // Check for a substitution or escape.
1592 // This macro has no parameters, look for $0, $1, etc.
1593 if (Body[Pos] != '$' || Pos + 1 == End)
1596 char Next = Body[Pos + 1];
1597 if (Next == '$' || Next == 'n' || isdigit(Next))
1600 // This macro has parameters, look for \foo, \bar, etc.
1601 if (Body[Pos] == '\\' && Pos + 1 != End)
1607 OS << Body.slice(0, Pos);
1609 // Check if we reached the end.
1614 switch (Body[Pos+1]) {
1620 // $n => number of arguments
1625 // $[0-9] => argument
1627 // Missing arguments are ignored.
1628 unsigned Index = Body[Pos+1] - '0';
1629 if (Index >= A.size())
1632 // Otherwise substitute with the token values, with spaces eliminated.
1633 for (MacroArgument::const_iterator it = A[Index].begin(),
1634 ie = A[Index].end(); it != ie; ++it)
1635 OS << it->getString();
1641 unsigned I = Pos + 1;
1642 while (isIdentifierChar(Body[I]) && I + 1 != End)
1645 const char *Begin = Body.data() + Pos +1;
1646 StringRef Argument(Begin, I - (Pos +1));
1648 for (; Index < NParameters; ++Index)
1649 if (Parameters[Index].first == Argument)
1652 if (Index == NParameters) {
1653 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1656 OS << '\\' << Argument;
1660 for (MacroArgument::const_iterator it = A[Index].begin(),
1661 ie = A[Index].end(); it != ie; ++it)
1662 if (it->getKind() == AsmToken::String)
1663 OS << it->getStringContents();
1665 OS << it->getString();
1667 Pos += 1 + Argument.size();
1670 // Update the scan point.
1671 Body = Body.substr(Pos);
1677 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL,
1680 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1685 static bool IsOperator(AsmToken::TokenKind kind)
1691 case AsmToken::Plus:
1692 case AsmToken::Minus:
1693 case AsmToken::Tilde:
1694 case AsmToken::Slash:
1695 case AsmToken::Star:
1697 case AsmToken::Equal:
1698 case AsmToken::EqualEqual:
1699 case AsmToken::Pipe:
1700 case AsmToken::PipePipe:
1701 case AsmToken::Caret:
1703 case AsmToken::AmpAmp:
1704 case AsmToken::Exclaim:
1705 case AsmToken::ExclaimEqual:
1706 case AsmToken::Percent:
1707 case AsmToken::Less:
1708 case AsmToken::LessEqual:
1709 case AsmToken::LessLess:
1710 case AsmToken::LessGreater:
1711 case AsmToken::Greater:
1712 case AsmToken::GreaterEqual:
1713 case AsmToken::GreaterGreater:
1718 /// ParseMacroArgument - Extract AsmTokens for a macro argument.
1719 /// This is used for both default macro parameter values and the
1720 /// arguments in macro invocations
1721 bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1722 AsmToken::TokenKind &ArgumentDelimiter) {
1723 unsigned ParenLevel = 0;
1724 unsigned AddTokens = 0;
1726 // gas accepts arguments separated by whitespace, except on Darwin
1728 Lexer.setSkipSpace(false);
1731 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1732 Lexer.setSkipSpace(true);
1733 return TokError("unexpected token in macro instantiation");
1736 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1737 // Spaces and commas cannot be mixed to delimit parameters
1738 if (ArgumentDelimiter == AsmToken::Eof)
1739 ArgumentDelimiter = AsmToken::Comma;
1740 else if (ArgumentDelimiter != AsmToken::Comma) {
1741 Lexer.setSkipSpace(true);
1742 return TokError("expected ' ' for macro argument separator");
1747 if (Lexer.is(AsmToken::Space)) {
1748 Lex(); // Eat spaces
1750 // Spaces can delimit parameters, but could also be part an expression.
1751 // If the token after a space is an operator, add the token and the next
1752 // one into this argument
1753 if (ArgumentDelimiter == AsmToken::Space ||
1754 ArgumentDelimiter == AsmToken::Eof) {
1755 if (IsOperator(Lexer.getKind())) {
1756 // Check to see whether the token is used as an operator,
1757 // or part of an identifier
1758 const char *NextChar = getTok().getEndLoc().getPointer();
1759 if (*NextChar == ' ')
1763 if (!AddTokens && ParenLevel == 0) {
1764 if (ArgumentDelimiter == AsmToken::Eof &&
1765 !IsOperator(Lexer.getKind()))
1766 ArgumentDelimiter = AsmToken::Space;
1772 // HandleMacroEntry relies on not advancing the lexer here
1773 // to be able to fill in the remaining default parameter values
1774 if (Lexer.is(AsmToken::EndOfStatement))
1777 // Adjust the current parentheses level.
1778 if (Lexer.is(AsmToken::LParen))
1780 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1783 // Append the token to the current argument list.
1784 MA.push_back(getTok());
1790 Lexer.setSkipSpace(true);
1791 if (ParenLevel != 0)
1792 return TokError("unbalanced parentheses in macro argument");
1796 // Parse the macro instantiation arguments.
1797 bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
1798 const unsigned NParameters = M ? M->Parameters.size() : 0;
1799 // Argument delimiter is initially unknown. It will be set by
1800 // ParseMacroArgument()
1801 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1803 // Parse two kinds of macro invocations:
1804 // - macros defined without any parameters accept an arbitrary number of them
1805 // - macros defined with parameters accept at most that many of them
1806 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1810 if (ParseMacroArgument(MA, ArgumentDelimiter))
1813 if (!MA.empty() || !NParameters)
1815 else if (NParameters) {
1816 if (!M->Parameters[Parameter].second.empty())
1817 A.push_back(M->Parameters[Parameter].second);
1820 // At the end of the statement, fill in remaining arguments that have
1821 // default values. If there aren't any, then the next argument is
1822 // required but missing
1823 if (Lexer.is(AsmToken::EndOfStatement)) {
1824 if (NParameters && Parameter < NParameters - 1) {
1825 if (M->Parameters[Parameter + 1].second.empty())
1826 return TokError("macro argument '" +
1827 Twine(M->Parameters[Parameter + 1].first) +
1835 if (Lexer.is(AsmToken::Comma))
1838 return TokError("Too many arguments");
1841 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1843 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1844 // this, although we should protect against infinite loops.
1845 if (ActiveMacros.size() == 20)
1846 return TokError("macros cannot be nested more than 20 levels deep");
1849 if (ParseMacroArguments(M, A))
1852 // Remove any trailing empty arguments. Do this after-the-fact as we have
1853 // to keep empty arguments in the middle of the list or positionality
1854 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1855 while (!A.empty() && A.back().empty())
1858 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1859 // to hold the macro body with substitutions.
1860 SmallString<256> Buf;
1861 StringRef Body = M->Body;
1862 raw_svector_ostream OS(Buf);
1864 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1867 // We include the .endmacro in the buffer as our queue to exit the macro
1869 OS << ".endmacro\n";
1871 MemoryBuffer *Instantiation =
1872 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1874 // Create the macro instantiation object and add to the current macro
1875 // instantiation stack.
1876 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1880 ActiveMacros.push_back(MI);
1882 // Jump to the macro instantiation and prime the lexer.
1883 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1884 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1890 void AsmParser::HandleMacroExit() {
1891 // Jump to the EndOfStatement we should return to, and consume it.
1892 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
1895 // Pop the instantiation entry.
1896 delete ActiveMacros.back();
1897 ActiveMacros.pop_back();
1900 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1901 switch (Value->getKind()) {
1902 case MCExpr::Binary: {
1903 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1904 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1907 case MCExpr::Target:
1908 case MCExpr::Constant:
1910 case MCExpr::SymbolRef: {
1911 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1913 return IsUsedIn(Sym, S.getVariableValue());
1917 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1920 llvm_unreachable("Unknown expr kind!");
1923 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1925 // FIXME: Use better location, we should use proper tokens.
1926 SMLoc EqualLoc = Lexer.getLoc();
1928 const MCExpr *Value;
1929 if (ParseExpression(Value))
1932 // Note: we don't count b as used in "a = b". This is to allow
1936 if (Lexer.isNot(AsmToken::EndOfStatement))
1937 return TokError("unexpected token in assignment");
1939 // Error on assignment to '.'.
1941 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1942 "(use '.space' or '.org').)"));
1945 // Eat the end of statement marker.
1948 // Validate that the LHS is allowed to be a variable (either it has not been
1949 // used as a symbol, or it is an absolute symbol).
1950 MCSymbol *Sym = getContext().LookupSymbol(Name);
1952 // Diagnose assignment to a label.
1954 // FIXME: Diagnostics. Note the location of the definition as a label.
1955 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1956 if (IsUsedIn(Sym, Value))
1957 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1958 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1959 ; // Allow redefinitions of undefined symbols only used in directives.
1960 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1961 ; // Allow redefinitions of variables that haven't yet been used.
1962 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1963 return Error(EqualLoc, "redefinition of '" + Name + "'");
1964 else if (!Sym->isVariable())
1965 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1966 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1967 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1970 // Don't count these checks as uses.
1971 Sym->setUsed(false);
1973 Sym = getContext().GetOrCreateSymbol(Name);
1975 // FIXME: Handle '.'.
1977 // Do the assignment.
1978 Out.EmitAssignment(Sym, Value);
1980 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1986 /// ParseIdentifier:
1989 bool AsmParser::ParseIdentifier(StringRef &Res) {
1990 // The assembler has relaxed rules for accepting identifiers, in particular we
1991 // allow things like '.globl $foo', which would normally be separate
1992 // tokens. At this level, we have already lexed so we cannot (currently)
1993 // handle this as a context dependent token, instead we detect adjacent tokens
1994 // and return the combined identifier.
1995 if (Lexer.is(AsmToken::Dollar)) {
1996 SMLoc DollarLoc = getLexer().getLoc();
1998 // Consume the dollar sign, and check for a following identifier.
2000 if (Lexer.isNot(AsmToken::Identifier))
2003 // We have a '$' followed by an identifier, make sure they are adjacent.
2004 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2007 // Construct the joined identifier and consume the token.
2008 Res = StringRef(DollarLoc.getPointer(),
2009 getTok().getIdentifier().size() + 1);
2014 if (Lexer.isNot(AsmToken::Identifier) &&
2015 Lexer.isNot(AsmToken::String))
2018 Res = getTok().getIdentifier();
2020 Lex(); // Consume the identifier token.
2025 /// ParseDirectiveSet:
2026 /// ::= .equ identifier ',' expression
2027 /// ::= .equiv identifier ',' expression
2028 /// ::= .set identifier ',' expression
2029 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
2032 if (ParseIdentifier(Name))
2033 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2035 if (getLexer().isNot(AsmToken::Comma))
2036 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2039 return ParseAssignment(Name, allow_redef, true);
2042 bool AsmParser::ParseEscapedString(std::string &Data) {
2043 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2046 StringRef Str = getTok().getStringContents();
2047 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2048 if (Str[i] != '\\') {
2053 // Recognize escaped characters. Note that this escape semantics currently
2054 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2057 return TokError("unexpected backslash at end of string");
2059 // Recognize octal sequences.
2060 if ((unsigned) (Str[i] - '0') <= 7) {
2061 // Consume up to three octal characters.
2062 unsigned Value = Str[i] - '0';
2064 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2066 Value = Value * 8 + (Str[i] - '0');
2068 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2070 Value = Value * 8 + (Str[i] - '0');
2075 return TokError("invalid octal escape sequence (out of range)");
2077 Data += (unsigned char) Value;
2081 // Otherwise recognize individual escapes.
2084 // Just reject invalid escape sequences for now.
2085 return TokError("invalid escape sequence (unrecognized character)");
2087 case 'b': Data += '\b'; break;
2088 case 'f': Data += '\f'; break;
2089 case 'n': Data += '\n'; break;
2090 case 'r': Data += '\r'; break;
2091 case 't': Data += '\t'; break;
2092 case '"': Data += '"'; break;
2093 case '\\': Data += '\\'; break;
2100 /// ParseDirectiveAscii:
2101 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2102 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2103 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2104 CheckForValidSection();
2107 if (getLexer().isNot(AsmToken::String))
2108 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2111 if (ParseEscapedString(Data))
2114 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2116 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2120 if (getLexer().is(AsmToken::EndOfStatement))
2123 if (getLexer().isNot(AsmToken::Comma))
2124 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2133 /// ParseDirectiveValue
2134 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2135 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2136 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2137 CheckForValidSection();
2140 const MCExpr *Value;
2141 SMLoc ExprLoc = getLexer().getLoc();
2142 if (ParseExpression(Value))
2145 // Special case constant expressions to match code generator.
2146 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2147 assert(Size <= 8 && "Invalid size");
2148 uint64_t IntValue = MCE->getValue();
2149 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2150 return Error(ExprLoc, "literal value out of range for directive");
2151 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2153 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2155 if (getLexer().is(AsmToken::EndOfStatement))
2158 // FIXME: Improve diagnostic.
2159 if (getLexer().isNot(AsmToken::Comma))
2160 return TokError("unexpected token in directive");
2169 /// ParseDirectiveRealValue
2170 /// ::= (.single | .double) [ expression (, expression)* ]
2171 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2172 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2173 CheckForValidSection();
2176 // We don't truly support arithmetic on floating point expressions, so we
2177 // have to manually parse unary prefixes.
2179 if (getLexer().is(AsmToken::Minus)) {
2182 } else if (getLexer().is(AsmToken::Plus))
2185 if (getLexer().isNot(AsmToken::Integer) &&
2186 getLexer().isNot(AsmToken::Real) &&
2187 getLexer().isNot(AsmToken::Identifier))
2188 return TokError("unexpected token in directive");
2190 // Convert to an APFloat.
2191 APFloat Value(Semantics);
2192 StringRef IDVal = getTok().getString();
2193 if (getLexer().is(AsmToken::Identifier)) {
2194 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2195 Value = APFloat::getInf(Semantics);
2196 else if (!IDVal.compare_lower("nan"))
2197 Value = APFloat::getNaN(Semantics, false, ~0);
2199 return TokError("invalid floating point literal");
2200 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2201 APFloat::opInvalidOp)
2202 return TokError("invalid floating point literal");
2206 // Consume the numeric token.
2209 // Emit the value as an integer.
2210 APInt AsInt = Value.bitcastToAPInt();
2211 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2212 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2214 if (getLexer().is(AsmToken::EndOfStatement))
2217 if (getLexer().isNot(AsmToken::Comma))
2218 return TokError("unexpected token in directive");
2227 /// ParseDirectiveSpace
2228 /// ::= .space expression [ , expression ]
2229 bool AsmParser::ParseDirectiveSpace() {
2230 CheckForValidSection();
2233 if (ParseAbsoluteExpression(NumBytes))
2236 int64_t FillExpr = 0;
2237 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2238 if (getLexer().isNot(AsmToken::Comma))
2239 return TokError("unexpected token in '.space' directive");
2242 if (ParseAbsoluteExpression(FillExpr))
2245 if (getLexer().isNot(AsmToken::EndOfStatement))
2246 return TokError("unexpected token in '.space' directive");
2252 return TokError("invalid number of bytes in '.space' directive");
2254 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
2255 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
2260 /// ParseDirectiveZero
2261 /// ::= .zero expression
2262 bool AsmParser::ParseDirectiveZero() {
2263 CheckForValidSection();
2266 if (ParseAbsoluteExpression(NumBytes))
2270 if (getLexer().is(AsmToken::Comma)) {
2272 if (ParseAbsoluteExpression(Val))
2276 if (getLexer().isNot(AsmToken::EndOfStatement))
2277 return TokError("unexpected token in '.zero' directive");
2281 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2286 /// ParseDirectiveFill
2287 /// ::= .fill expression , expression , expression
2288 bool AsmParser::ParseDirectiveFill() {
2289 CheckForValidSection();
2292 if (ParseAbsoluteExpression(NumValues))
2295 if (getLexer().isNot(AsmToken::Comma))
2296 return TokError("unexpected token in '.fill' directive");
2300 if (ParseAbsoluteExpression(FillSize))
2303 if (getLexer().isNot(AsmToken::Comma))
2304 return TokError("unexpected token in '.fill' directive");
2308 if (ParseAbsoluteExpression(FillExpr))
2311 if (getLexer().isNot(AsmToken::EndOfStatement))
2312 return TokError("unexpected token in '.fill' directive");
2316 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2317 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2319 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2320 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2325 /// ParseDirectiveOrg
2326 /// ::= .org expression [ , expression ]
2327 bool AsmParser::ParseDirectiveOrg() {
2328 CheckForValidSection();
2330 const MCExpr *Offset;
2331 SMLoc Loc = getTok().getLoc();
2332 if (ParseExpression(Offset))
2335 // Parse optional fill expression.
2336 int64_t FillExpr = 0;
2337 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2338 if (getLexer().isNot(AsmToken::Comma))
2339 return TokError("unexpected token in '.org' directive");
2342 if (ParseAbsoluteExpression(FillExpr))
2345 if (getLexer().isNot(AsmToken::EndOfStatement))
2346 return TokError("unexpected token in '.org' directive");
2351 // Only limited forms of relocatable expressions are accepted here, it
2352 // has to be relative to the current section. The streamer will return
2353 // 'true' if the expression wasn't evaluatable.
2354 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2355 return Error(Loc, "expected assembly-time absolute expression");
2360 /// ParseDirectiveAlign
2361 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2362 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2363 CheckForValidSection();
2365 SMLoc AlignmentLoc = getLexer().getLoc();
2367 if (ParseAbsoluteExpression(Alignment))
2371 bool HasFillExpr = false;
2372 int64_t FillExpr = 0;
2373 int64_t MaxBytesToFill = 0;
2374 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2375 if (getLexer().isNot(AsmToken::Comma))
2376 return TokError("unexpected token in directive");
2379 // The fill expression can be omitted while specifying a maximum number of
2380 // alignment bytes, e.g:
2382 if (getLexer().isNot(AsmToken::Comma)) {
2384 if (ParseAbsoluteExpression(FillExpr))
2388 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2389 if (getLexer().isNot(AsmToken::Comma))
2390 return TokError("unexpected token in directive");
2393 MaxBytesLoc = getLexer().getLoc();
2394 if (ParseAbsoluteExpression(MaxBytesToFill))
2397 if (getLexer().isNot(AsmToken::EndOfStatement))
2398 return TokError("unexpected token in directive");
2407 // Compute alignment in bytes.
2409 // FIXME: Diagnose overflow.
2410 if (Alignment >= 32) {
2411 Error(AlignmentLoc, "invalid alignment value");
2415 Alignment = 1ULL << Alignment;
2418 // Diagnose non-sensical max bytes to align.
2419 if (MaxBytesLoc.isValid()) {
2420 if (MaxBytesToFill < 1) {
2421 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2422 "many bytes, ignoring maximum bytes expression");
2426 if (MaxBytesToFill >= Alignment) {
2427 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2433 // Check whether we should use optimal code alignment for this .align
2435 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2436 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2437 ValueSize == 1 && UseCodeAlign) {
2438 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2440 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2441 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2449 /// ParseDirectiveBundleAlignMode
2450 /// ::= {.bundle_align_mode} expression
2451 bool AsmParser::ParseDirectiveBundleAlignMode() {
2452 CheckForValidSection();
2454 // Expect a single argument: an expression that evaluates to a constant
2455 // in the inclusive range 0-30.
2456 SMLoc ExprLoc = getLexer().getLoc();
2457 int64_t AlignSizePow2;
2458 if (ParseAbsoluteExpression(AlignSizePow2))
2460 else if (getLexer().isNot(AsmToken::EndOfStatement))
2461 return TokError("unexpected token after expression in"
2462 " '.bundle_align_mode' directive");
2463 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
2464 return Error(ExprLoc,
2465 "invalid bundle alignment size (expected between 0 and 30)");
2469 // Because of AlignSizePow2's verified range we can safely truncate it to
2471 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
2475 /// ParseDirectiveBundleLock
2476 /// ::= {.bundle_lock} [align_to_end]
2477 bool AsmParser::ParseDirectiveBundleLock() {
2478 CheckForValidSection();
2479 bool AlignToEnd = false;
2481 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2483 SMLoc Loc = getTok().getLoc();
2484 const char *kInvalidOptionError =
2485 "invalid option for '.bundle_lock' directive";
2487 if (ParseIdentifier(Option))
2488 return Error(Loc, kInvalidOptionError);
2490 if (Option != "align_to_end")
2491 return Error(Loc, kInvalidOptionError);
2492 else if (getLexer().isNot(AsmToken::EndOfStatement))
2494 "unexpected token after '.bundle_lock' directive option");
2500 getStreamer().EmitBundleLock(AlignToEnd);
2504 /// ParseDirectiveBundleLock
2505 /// ::= {.bundle_lock}
2506 bool AsmParser::ParseDirectiveBundleUnlock() {
2507 CheckForValidSection();
2509 if (getLexer().isNot(AsmToken::EndOfStatement))
2510 return TokError("unexpected token in '.bundle_unlock' directive");
2513 getStreamer().EmitBundleUnlock();
2517 /// ParseDirectiveSymbolAttribute
2518 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2519 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2520 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2523 SMLoc Loc = getTok().getLoc();
2525 if (ParseIdentifier(Name))
2526 return Error(Loc, "expected identifier in directive");
2528 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2530 // Assembler local symbols don't make any sense here. Complain loudly.
2531 if (Sym->isTemporary())
2532 return Error(Loc, "non-local symbol required in directive");
2534 getStreamer().EmitSymbolAttribute(Sym, Attr);
2536 if (getLexer().is(AsmToken::EndOfStatement))
2539 if (getLexer().isNot(AsmToken::Comma))
2540 return TokError("unexpected token in directive");
2549 /// ParseDirectiveComm
2550 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2551 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2552 CheckForValidSection();
2554 SMLoc IDLoc = getLexer().getLoc();
2556 if (ParseIdentifier(Name))
2557 return TokError("expected identifier in directive");
2559 // Handle the identifier as the key symbol.
2560 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2562 if (getLexer().isNot(AsmToken::Comma))
2563 return TokError("unexpected token in directive");
2567 SMLoc SizeLoc = getLexer().getLoc();
2568 if (ParseAbsoluteExpression(Size))
2571 int64_t Pow2Alignment = 0;
2572 SMLoc Pow2AlignmentLoc;
2573 if (getLexer().is(AsmToken::Comma)) {
2575 Pow2AlignmentLoc = getLexer().getLoc();
2576 if (ParseAbsoluteExpression(Pow2Alignment))
2579 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2580 if (IsLocal && LCOMM == LCOMM::NoAlignment)
2581 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2583 // If this target takes alignments in bytes (not log) validate and convert.
2584 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2585 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
2586 if (!isPowerOf2_64(Pow2Alignment))
2587 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2588 Pow2Alignment = Log2_64(Pow2Alignment);
2592 if (getLexer().isNot(AsmToken::EndOfStatement))
2593 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2597 // NOTE: a size of zero for a .comm should create a undefined symbol
2598 // but a size of .lcomm creates a bss symbol of size zero.
2600 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2601 "be less than zero");
2603 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2604 // may internally end up wanting an alignment in bytes.
2605 // FIXME: Diagnose overflow.
2606 if (Pow2Alignment < 0)
2607 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2608 "alignment, can't be less than zero");
2610 if (!Sym->isUndefined())
2611 return Error(IDLoc, "invalid symbol redefinition");
2613 // Create the Symbol as a common or local common with Size and Pow2Alignment
2615 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2619 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2623 /// ParseDirectiveAbort
2624 /// ::= .abort [... message ...]
2625 bool AsmParser::ParseDirectiveAbort() {
2626 // FIXME: Use loc from directive.
2627 SMLoc Loc = getLexer().getLoc();
2629 StringRef Str = ParseStringToEndOfStatement();
2630 if (getLexer().isNot(AsmToken::EndOfStatement))
2631 return TokError("unexpected token in '.abort' directive");
2636 Error(Loc, ".abort detected. Assembly stopping.");
2638 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2639 // FIXME: Actually abort assembly here.
2644 /// ParseDirectiveInclude
2645 /// ::= .include "filename"
2646 bool AsmParser::ParseDirectiveInclude() {
2647 if (getLexer().isNot(AsmToken::String))
2648 return TokError("expected string in '.include' directive");
2650 std::string Filename = getTok().getString();
2651 SMLoc IncludeLoc = getLexer().getLoc();
2654 if (getLexer().isNot(AsmToken::EndOfStatement))
2655 return TokError("unexpected token in '.include' directive");
2657 // Strip the quotes.
2658 Filename = Filename.substr(1, Filename.size()-2);
2660 // Attempt to switch the lexer to the included file before consuming the end
2661 // of statement to avoid losing it when we switch.
2662 if (EnterIncludeFile(Filename)) {
2663 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2670 /// ParseDirectiveIncbin
2671 /// ::= .incbin "filename"
2672 bool AsmParser::ParseDirectiveIncbin() {
2673 if (getLexer().isNot(AsmToken::String))
2674 return TokError("expected string in '.incbin' directive");
2676 std::string Filename = getTok().getString();
2677 SMLoc IncbinLoc = getLexer().getLoc();
2680 if (getLexer().isNot(AsmToken::EndOfStatement))
2681 return TokError("unexpected token in '.incbin' directive");
2683 // Strip the quotes.
2684 Filename = Filename.substr(1, Filename.size()-2);
2686 // Attempt to process the included file.
2687 if (ProcessIncbinFile(Filename)) {
2688 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2695 /// ParseDirectiveIf
2696 /// ::= .if expression
2697 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2698 TheCondStack.push_back(TheCondState);
2699 TheCondState.TheCond = AsmCond::IfCond;
2700 if (TheCondState.Ignore) {
2701 EatToEndOfStatement();
2704 if (ParseAbsoluteExpression(ExprValue))
2707 if (getLexer().isNot(AsmToken::EndOfStatement))
2708 return TokError("unexpected token in '.if' directive");
2712 TheCondState.CondMet = ExprValue;
2713 TheCondState.Ignore = !TheCondState.CondMet;
2719 /// ParseDirectiveIfb
2721 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2722 TheCondStack.push_back(TheCondState);
2723 TheCondState.TheCond = AsmCond::IfCond;
2725 if (TheCondState.Ignore) {
2726 EatToEndOfStatement();
2728 StringRef Str = ParseStringToEndOfStatement();
2730 if (getLexer().isNot(AsmToken::EndOfStatement))
2731 return TokError("unexpected token in '.ifb' directive");
2735 TheCondState.CondMet = ExpectBlank == Str.empty();
2736 TheCondState.Ignore = !TheCondState.CondMet;
2742 /// ParseDirectiveIfc
2743 /// ::= .ifc string1, string2
2744 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2745 TheCondStack.push_back(TheCondState);
2746 TheCondState.TheCond = AsmCond::IfCond;
2748 if (TheCondState.Ignore) {
2749 EatToEndOfStatement();
2751 StringRef Str1 = ParseStringToComma();
2753 if (getLexer().isNot(AsmToken::Comma))
2754 return TokError("unexpected token in '.ifc' directive");
2758 StringRef Str2 = ParseStringToEndOfStatement();
2760 if (getLexer().isNot(AsmToken::EndOfStatement))
2761 return TokError("unexpected token in '.ifc' directive");
2765 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2766 TheCondState.Ignore = !TheCondState.CondMet;
2772 /// ParseDirectiveIfdef
2773 /// ::= .ifdef symbol
2774 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2776 TheCondStack.push_back(TheCondState);
2777 TheCondState.TheCond = AsmCond::IfCond;
2779 if (TheCondState.Ignore) {
2780 EatToEndOfStatement();
2782 if (ParseIdentifier(Name))
2783 return TokError("expected identifier after '.ifdef'");
2787 MCSymbol *Sym = getContext().LookupSymbol(Name);
2790 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2792 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2793 TheCondState.Ignore = !TheCondState.CondMet;
2799 /// ParseDirectiveElseIf
2800 /// ::= .elseif expression
2801 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2802 if (TheCondState.TheCond != AsmCond::IfCond &&
2803 TheCondState.TheCond != AsmCond::ElseIfCond)
2804 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2806 TheCondState.TheCond = AsmCond::ElseIfCond;
2808 bool LastIgnoreState = false;
2809 if (!TheCondStack.empty())
2810 LastIgnoreState = TheCondStack.back().Ignore;
2811 if (LastIgnoreState || TheCondState.CondMet) {
2812 TheCondState.Ignore = true;
2813 EatToEndOfStatement();
2817 if (ParseAbsoluteExpression(ExprValue))
2820 if (getLexer().isNot(AsmToken::EndOfStatement))
2821 return TokError("unexpected token in '.elseif' directive");
2824 TheCondState.CondMet = ExprValue;
2825 TheCondState.Ignore = !TheCondState.CondMet;
2831 /// ParseDirectiveElse
2833 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2834 if (getLexer().isNot(AsmToken::EndOfStatement))
2835 return TokError("unexpected token in '.else' directive");
2839 if (TheCondState.TheCond != AsmCond::IfCond &&
2840 TheCondState.TheCond != AsmCond::ElseIfCond)
2841 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2843 TheCondState.TheCond = AsmCond::ElseCond;
2844 bool LastIgnoreState = false;
2845 if (!TheCondStack.empty())
2846 LastIgnoreState = TheCondStack.back().Ignore;
2847 if (LastIgnoreState || TheCondState.CondMet)
2848 TheCondState.Ignore = true;
2850 TheCondState.Ignore = false;
2855 /// ParseDirectiveEndIf
2857 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2858 if (getLexer().isNot(AsmToken::EndOfStatement))
2859 return TokError("unexpected token in '.endif' directive");
2863 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2864 TheCondStack.empty())
2865 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2867 if (!TheCondStack.empty()) {
2868 TheCondState = TheCondStack.back();
2869 TheCondStack.pop_back();
2875 /// ParseDirectiveFile
2876 /// ::= .file [number] filename
2877 /// ::= .file number directory filename
2878 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2879 // FIXME: I'm not sure what this is.
2880 int64_t FileNumber = -1;
2881 SMLoc FileNumberLoc = getLexer().getLoc();
2882 if (getLexer().is(AsmToken::Integer)) {
2883 FileNumber = getTok().getIntVal();
2887 return TokError("file number less than one");
2890 if (getLexer().isNot(AsmToken::String))
2891 return TokError("unexpected token in '.file' directive");
2893 // Usually the directory and filename together, otherwise just the directory.
2894 StringRef Path = getTok().getString();
2895 Path = Path.substr(1, Path.size()-2);
2898 StringRef Directory;
2900 if (getLexer().is(AsmToken::String)) {
2901 if (FileNumber == -1)
2902 return TokError("explicit path specified, but no file number");
2903 Filename = getTok().getString();
2904 Filename = Filename.substr(1, Filename.size()-2);
2911 if (getLexer().isNot(AsmToken::EndOfStatement))
2912 return TokError("unexpected token in '.file' directive");
2914 if (FileNumber == -1)
2915 getStreamer().EmitFileDirective(Filename);
2917 if (getContext().getGenDwarfForAssembly() == true)
2918 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2919 "used to generate dwarf debug info for assembly code");
2921 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2922 Error(FileNumberLoc, "file number already allocated");
2928 /// ParseDirectiveLine
2929 /// ::= .line [number]
2930 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2931 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2932 if (getLexer().isNot(AsmToken::Integer))
2933 return TokError("unexpected token in '.line' directive");
2935 int64_t LineNumber = getTok().getIntVal();
2939 // FIXME: Do something with the .line.
2942 if (getLexer().isNot(AsmToken::EndOfStatement))
2943 return TokError("unexpected token in '.line' directive");
2949 /// ParseDirectiveLoc
2950 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2951 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2952 /// The first number is a file number, must have been previously assigned with
2953 /// a .file directive, the second number is the line number and optionally the
2954 /// third number is a column position (zero if not specified). The remaining
2955 /// optional items are .loc sub-directives.
2956 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2958 if (getLexer().isNot(AsmToken::Integer))
2959 return TokError("unexpected token in '.loc' directive");
2960 int64_t FileNumber = getTok().getIntVal();
2962 return TokError("file number less than one in '.loc' directive");
2963 if (!getContext().isValidDwarfFileNumber(FileNumber))
2964 return TokError("unassigned file number in '.loc' directive");
2967 int64_t LineNumber = 0;
2968 if (getLexer().is(AsmToken::Integer)) {
2969 LineNumber = getTok().getIntVal();
2971 return TokError("line number less than one in '.loc' directive");
2975 int64_t ColumnPos = 0;
2976 if (getLexer().is(AsmToken::Integer)) {
2977 ColumnPos = getTok().getIntVal();
2979 return TokError("column position less than zero in '.loc' directive");
2983 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2985 int64_t Discriminator = 0;
2986 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2988 if (getLexer().is(AsmToken::EndOfStatement))
2992 SMLoc Loc = getTok().getLoc();
2993 if (getParser().ParseIdentifier(Name))
2994 return TokError("unexpected token in '.loc' directive");
2996 if (Name == "basic_block")
2997 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2998 else if (Name == "prologue_end")
2999 Flags |= DWARF2_FLAG_PROLOGUE_END;
3000 else if (Name == "epilogue_begin")
3001 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3002 else if (Name == "is_stmt") {
3003 Loc = getTok().getLoc();
3004 const MCExpr *Value;
3005 if (getParser().ParseExpression(Value))
3007 // The expression must be the constant 0 or 1.
3008 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3009 int Value = MCE->getValue();
3011 Flags &= ~DWARF2_FLAG_IS_STMT;
3012 else if (Value == 1)
3013 Flags |= DWARF2_FLAG_IS_STMT;
3015 return Error(Loc, "is_stmt value not 0 or 1");
3018 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3021 else if (Name == "isa") {
3022 Loc = getTok().getLoc();
3023 const MCExpr *Value;
3024 if (getParser().ParseExpression(Value))
3026 // The expression must be a constant greater or equal to 0.
3027 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3028 int Value = MCE->getValue();
3030 return Error(Loc, "isa number less than zero");
3034 return Error(Loc, "isa number not a constant value");
3037 else if (Name == "discriminator") {
3038 if (getParser().ParseAbsoluteExpression(Discriminator))
3042 return Error(Loc, "unknown sub-directive in '.loc' directive");
3045 if (getLexer().is(AsmToken::EndOfStatement))
3050 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3051 Isa, Discriminator, StringRef());
3056 /// ParseDirectiveStabs
3057 /// ::= .stabs string, number, number, number
3058 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
3059 SMLoc DirectiveLoc) {
3060 return TokError("unsupported directive '" + Directive + "'");
3063 /// ParseDirectiveCFISections
3064 /// ::= .cfi_sections section [, section]
3065 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
3066 SMLoc DirectiveLoc) {
3071 if (getParser().ParseIdentifier(Name))
3072 return TokError("Expected an identifier");
3074 if (Name == ".eh_frame")
3076 else if (Name == ".debug_frame")
3079 if (getLexer().is(AsmToken::Comma)) {
3082 if (getParser().ParseIdentifier(Name))
3083 return TokError("Expected an identifier");
3085 if (Name == ".eh_frame")
3087 else if (Name == ".debug_frame")
3091 getStreamer().EmitCFISections(EH, Debug);
3096 /// ParseDirectiveCFIStartProc
3097 /// ::= .cfi_startproc
3098 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
3099 SMLoc DirectiveLoc) {
3100 getStreamer().EmitCFIStartProc();
3104 /// ParseDirectiveCFIEndProc
3105 /// ::= .cfi_endproc
3106 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
3107 getStreamer().EmitCFIEndProc();
3111 /// ParseRegisterOrRegisterNumber - parse register name or number.
3112 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3113 SMLoc DirectiveLoc) {
3116 if (getLexer().isNot(AsmToken::Integer)) {
3117 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3120 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
3122 return getParser().ParseAbsoluteExpression(Register);
3127 /// ParseDirectiveCFIDefCfa
3128 /// ::= .cfi_def_cfa register, offset
3129 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3130 SMLoc DirectiveLoc) {
3131 int64_t Register = 0;
3132 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3135 if (getLexer().isNot(AsmToken::Comma))
3136 return TokError("unexpected token in directive");
3140 if (getParser().ParseAbsoluteExpression(Offset))
3143 getStreamer().EmitCFIDefCfa(Register, Offset);
3147 /// ParseDirectiveCFIDefCfaOffset
3148 /// ::= .cfi_def_cfa_offset offset
3149 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3150 SMLoc DirectiveLoc) {
3152 if (getParser().ParseAbsoluteExpression(Offset))
3155 getStreamer().EmitCFIDefCfaOffset(Offset);
3159 /// ParseDirectiveCFIAdjustCfaOffset
3160 /// ::= .cfi_adjust_cfa_offset adjustment
3161 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3162 SMLoc DirectiveLoc) {
3163 int64_t Adjustment = 0;
3164 if (getParser().ParseAbsoluteExpression(Adjustment))
3167 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3171 /// ParseDirectiveCFIDefCfaRegister
3172 /// ::= .cfi_def_cfa_register register
3173 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3174 SMLoc DirectiveLoc) {
3175 int64_t Register = 0;
3176 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3179 getStreamer().EmitCFIDefCfaRegister(Register);
3183 /// ParseDirectiveCFIOffset
3184 /// ::= .cfi_offset register, offset
3185 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3186 int64_t Register = 0;
3189 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3192 if (getLexer().isNot(AsmToken::Comma))
3193 return TokError("unexpected token in directive");
3196 if (getParser().ParseAbsoluteExpression(Offset))
3199 getStreamer().EmitCFIOffset(Register, Offset);
3203 /// ParseDirectiveCFIRelOffset
3204 /// ::= .cfi_rel_offset register, offset
3205 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3206 SMLoc DirectiveLoc) {
3207 int64_t Register = 0;
3209 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3212 if (getLexer().isNot(AsmToken::Comma))
3213 return TokError("unexpected token in directive");
3217 if (getParser().ParseAbsoluteExpression(Offset))
3220 getStreamer().EmitCFIRelOffset(Register, Offset);
3224 static bool isValidEncoding(int64_t Encoding) {
3225 if (Encoding & ~0xff)
3228 if (Encoding == dwarf::DW_EH_PE_omit)
3231 const unsigned Format = Encoding & 0xf;
3232 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3233 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3234 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3235 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3238 const unsigned Application = Encoding & 0x70;
3239 if (Application != dwarf::DW_EH_PE_absptr &&
3240 Application != dwarf::DW_EH_PE_pcrel)
3246 /// ParseDirectiveCFIPersonalityOrLsda
3247 /// ::= .cfi_personality encoding, [symbol_name]
3248 /// ::= .cfi_lsda encoding, [symbol_name]
3249 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
3250 SMLoc DirectiveLoc) {
3251 int64_t Encoding = 0;
3252 if (getParser().ParseAbsoluteExpression(Encoding))
3254 if (Encoding == dwarf::DW_EH_PE_omit)
3257 if (!isValidEncoding(Encoding))
3258 return TokError("unsupported encoding.");
3260 if (getLexer().isNot(AsmToken::Comma))
3261 return TokError("unexpected token in directive");
3265 if (getParser().ParseIdentifier(Name))
3266 return TokError("expected identifier in directive");
3268 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3270 if (IDVal == ".cfi_personality")
3271 getStreamer().EmitCFIPersonality(Sym, Encoding);
3273 assert(IDVal == ".cfi_lsda");
3274 getStreamer().EmitCFILsda(Sym, Encoding);
3279 /// ParseDirectiveCFIRememberState
3280 /// ::= .cfi_remember_state
3281 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3282 SMLoc DirectiveLoc) {
3283 getStreamer().EmitCFIRememberState();
3287 /// ParseDirectiveCFIRestoreState
3288 /// ::= .cfi_remember_state
3289 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3290 SMLoc DirectiveLoc) {
3291 getStreamer().EmitCFIRestoreState();
3295 /// ParseDirectiveCFISameValue
3296 /// ::= .cfi_same_value register
3297 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3298 SMLoc DirectiveLoc) {
3299 int64_t Register = 0;
3301 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3304 getStreamer().EmitCFISameValue(Register);
3309 /// ParseDirectiveCFIRestore
3310 /// ::= .cfi_restore register
3311 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
3312 SMLoc DirectiveLoc) {
3313 int64_t Register = 0;
3314 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3317 getStreamer().EmitCFIRestore(Register);
3322 /// ParseDirectiveCFIEscape
3323 /// ::= .cfi_escape expression[,...]
3324 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3325 SMLoc DirectiveLoc) {
3328 if (getParser().ParseAbsoluteExpression(CurrValue))
3331 Values.push_back((uint8_t)CurrValue);
3333 while (getLexer().is(AsmToken::Comma)) {
3336 if (getParser().ParseAbsoluteExpression(CurrValue))
3339 Values.push_back((uint8_t)CurrValue);
3342 getStreamer().EmitCFIEscape(Values);
3346 /// ParseDirectiveCFISignalFrame
3347 /// ::= .cfi_signal_frame
3348 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3349 SMLoc DirectiveLoc) {
3350 if (getLexer().isNot(AsmToken::EndOfStatement))
3351 return Error(getLexer().getLoc(),
3352 "unexpected token in '" + Directive + "' directive");
3354 getStreamer().EmitCFISignalFrame();
3359 /// ParseDirectiveCFIUndefined
3360 /// ::= .cfi_undefined register
3361 bool GenericAsmParser::ParseDirectiveCFIUndefined(StringRef Directive,
3362 SMLoc DirectiveLoc) {
3363 int64_t Register = 0;
3365 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3368 getStreamer().EmitCFIUndefined(Register);
3373 /// ParseDirectiveCFIRegister
3374 /// ::= .cfi_register register, register
3375 bool GenericAsmParser::ParseDirectiveCFIRegister(StringRef Directive,
3376 SMLoc DirectiveLoc) {
3377 int64_t Register1 = 0;
3379 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3382 if (getLexer().isNot(AsmToken::Comma))
3383 return TokError("unexpected token in directive");
3386 int64_t Register2 = 0;
3388 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3391 getStreamer().EmitCFIRegister(Register1, Register2);
3396 /// ParseDirectiveMacrosOnOff
3399 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3400 SMLoc DirectiveLoc) {
3401 if (getLexer().isNot(AsmToken::EndOfStatement))
3402 return Error(getLexer().getLoc(),
3403 "unexpected token in '" + Directive + "' directive");
3405 getParser().MacrosEnabled = Directive == ".macros_on";
3410 /// ParseDirectiveMacro
3411 /// ::= .macro name [parameters]
3412 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3413 SMLoc DirectiveLoc) {
3415 if (getParser().ParseIdentifier(Name))
3416 return TokError("expected identifier in '.macro' directive");
3418 MacroParameters Parameters;
3419 // Argument delimiter is initially unknown. It will be set by
3420 // ParseMacroArgument()
3421 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3422 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3424 MacroParameter Parameter;
3425 if (getParser().ParseIdentifier(Parameter.first))
3426 return TokError("expected identifier in '.macro' directive");
3428 if (getLexer().is(AsmToken::Equal)) {
3430 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3434 Parameters.push_back(Parameter);
3436 if (getLexer().is(AsmToken::Comma))
3438 else if (getLexer().is(AsmToken::EndOfStatement))
3443 // Eat the end of statement.
3446 AsmToken EndToken, StartToken = getTok();
3448 // Lex the macro definition.
3450 // Check whether we have reached the end of the file.
3451 if (getLexer().is(AsmToken::Eof))
3452 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3454 // Otherwise, check whether we have reach the .endmacro.
3455 if (getLexer().is(AsmToken::Identifier) &&
3456 (getTok().getIdentifier() == ".endm" ||
3457 getTok().getIdentifier() == ".endmacro")) {
3458 EndToken = getTok();
3460 if (getLexer().isNot(AsmToken::EndOfStatement))
3461 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3466 // Otherwise, scan til the end of the statement.
3467 getParser().EatToEndOfStatement();
3470 if (getParser().MacroMap.lookup(Name)) {
3471 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3474 const char *BodyStart = StartToken.getLoc().getPointer();
3475 const char *BodyEnd = EndToken.getLoc().getPointer();
3476 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3477 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3481 /// ParseDirectiveEndMacro
3484 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3485 SMLoc DirectiveLoc) {
3486 if (getLexer().isNot(AsmToken::EndOfStatement))
3487 return TokError("unexpected token in '" + Directive + "' directive");
3489 // If we are inside a macro instantiation, terminate the current
3491 if (!getParser().ActiveMacros.empty()) {
3492 getParser().HandleMacroExit();
3496 // Otherwise, this .endmacro is a stray entry in the file; well formed
3497 // .endmacro directives are handled during the macro definition parsing.
3498 return TokError("unexpected '" + Directive + "' in file, "
3499 "no current macro definition");
3502 /// ParseDirectivePurgeMacro
3504 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3505 SMLoc DirectiveLoc) {
3507 if (getParser().ParseIdentifier(Name))
3508 return TokError("expected identifier in '.purgem' directive");
3510 if (getLexer().isNot(AsmToken::EndOfStatement))
3511 return TokError("unexpected token in '.purgem' directive");
3513 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3514 if (I == getParser().MacroMap.end())
3515 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3517 // Undefine the macro.
3518 delete I->getValue();
3519 getParser().MacroMap.erase(I);
3523 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3524 getParser().CheckForValidSection();
3526 const MCExpr *Value;
3528 if (getParser().ParseExpression(Value))
3531 if (getLexer().isNot(AsmToken::EndOfStatement))
3532 return TokError("unexpected token in directive");
3534 if (DirName[1] == 's')
3535 getStreamer().EmitSLEB128Value(Value);
3537 getStreamer().EmitULEB128Value(Value);
3542 Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3543 AsmToken EndToken, StartToken = getTok();
3545 unsigned NestLevel = 0;
3547 // Check whether we have reached the end of the file.
3548 if (getLexer().is(AsmToken::Eof)) {
3549 Error(DirectiveLoc, "no matching '.endr' in definition");
3553 if (Lexer.is(AsmToken::Identifier) &&
3554 (getTok().getIdentifier() == ".rept")) {
3558 // Otherwise, check whether we have reached the .endr.
3559 if (Lexer.is(AsmToken::Identifier) &&
3560 getTok().getIdentifier() == ".endr") {
3561 if (NestLevel == 0) {
3562 EndToken = getTok();
3564 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3565 TokError("unexpected token in '.endr' directive");
3573 // Otherwise, scan till the end of the statement.
3574 EatToEndOfStatement();
3577 const char *BodyStart = StartToken.getLoc().getPointer();
3578 const char *BodyEnd = EndToken.getLoc().getPointer();
3579 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3581 // We Are Anonymous.
3583 MacroParameters Parameters;
3584 return new Macro(Name, Body, Parameters);
3587 void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3588 raw_svector_ostream &OS) {
3591 MemoryBuffer *Instantiation =
3592 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3594 // Create the macro instantiation object and add to the current macro
3595 // instantiation stack.
3596 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3600 ActiveMacros.push_back(MI);
3602 // Jump to the macro instantiation and prime the lexer.
3603 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3604 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3608 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3610 if (ParseAbsoluteExpression(Count))
3611 return TokError("unexpected token in '.rept' directive");
3614 return TokError("Count is negative");
3616 if (Lexer.isNot(AsmToken::EndOfStatement))
3617 return TokError("unexpected token in '.rept' directive");
3619 // Eat the end of statement.
3622 // Lex the rept definition.
3623 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3627 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3628 // to hold the macro body with substitutions.
3629 SmallString<256> Buf;
3630 MacroParameters Parameters;
3632 raw_svector_ostream OS(Buf);
3634 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3637 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3642 /// ParseDirectiveIrp
3643 /// ::= .irp symbol,values
3644 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3645 MacroParameters Parameters;
3646 MacroParameter Parameter;
3648 if (ParseIdentifier(Parameter.first))
3649 return TokError("expected identifier in '.irp' directive");
3651 Parameters.push_back(Parameter);
3653 if (Lexer.isNot(AsmToken::Comma))
3654 return TokError("expected comma in '.irp' directive");
3659 if (ParseMacroArguments(0, A))
3662 // Eat the end of statement.
3665 // Lex the irp definition.
3666 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3670 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3671 // to hold the macro body with substitutions.
3672 SmallString<256> Buf;
3673 raw_svector_ostream OS(Buf);
3675 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3676 MacroArguments Args;
3679 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3683 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3688 /// ParseDirectiveIrpc
3689 /// ::= .irpc symbol,values
3690 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3691 MacroParameters Parameters;
3692 MacroParameter Parameter;
3694 if (ParseIdentifier(Parameter.first))
3695 return TokError("expected identifier in '.irpc' directive");
3697 Parameters.push_back(Parameter);
3699 if (Lexer.isNot(AsmToken::Comma))
3700 return TokError("expected comma in '.irpc' directive");
3705 if (ParseMacroArguments(0, A))
3708 if (A.size() != 1 || A.front().size() != 1)
3709 return TokError("unexpected token in '.irpc' directive");
3711 // Eat the end of statement.
3714 // Lex the irpc definition.
3715 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3719 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3720 // to hold the macro body with substitutions.
3721 SmallString<256> Buf;
3722 raw_svector_ostream OS(Buf);
3724 StringRef Values = A.front().front().getString();
3725 std::size_t I, End = Values.size();
3726 for (I = 0; I < End; ++I) {
3728 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3730 MacroArguments Args;
3731 Args.push_back(Arg);
3733 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3737 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3742 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3743 if (ActiveMacros.empty())
3744 return TokError("unmatched '.endr' directive");
3746 // The only .repl that should get here are the ones created by
3747 // InstantiateMacroLikeBody.
3748 assert(getLexer().is(AsmToken::EndOfStatement));
3754 bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3755 const MCExpr *Value;
3756 SMLoc ExprLoc = getLexer().getLoc();
3757 if (ParseExpression(Value))
3759 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3761 return Error(ExprLoc, "unexpected expression in _emit");
3762 uint64_t IntValue = MCE->getValue();
3763 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3764 return Error(ExprLoc, "literal value out of range for directive");
3766 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3770 bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3771 unsigned &NumOutputs, unsigned &NumInputs,
3772 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
3773 SmallVectorImpl<std::string> &Constraints,
3774 SmallVectorImpl<std::string> &Clobbers,
3775 const MCInstrInfo *MII,
3776 const MCInstPrinter *IP,
3777 MCAsmParserSemaCallback &SI) {
3778 SmallVector<void *, 4> InputDecls;
3779 SmallVector<void *, 4> OutputDecls;
3780 SmallVector<bool, 4> InputDeclsAddressOf;
3781 SmallVector<bool, 4> OutputDeclsAddressOf;
3782 SmallVector<std::string, 4> InputConstraints;
3783 SmallVector<std::string, 4> OutputConstraints;
3784 std::set<std::string> ClobberRegs;
3786 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
3791 // While we have input, parse each statement.
3792 unsigned InputIdx = 0;
3793 unsigned OutputIdx = 0;
3794 while (getLexer().isNot(AsmToken::Eof)) {
3795 ParseStatementInfo Info(&AsmStrRewrites);
3796 if (ParseStatement(Info))
3799 if (Info.ParseError)
3802 if (Info.Opcode != ~0U) {
3803 const MCInstrDesc &Desc = MII->get(Info.Opcode);
3805 // Build the list of clobbers, outputs and inputs.
3806 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3807 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
3810 if (Operand->isImm()) {
3811 if (Operand->needAsmRewrite())
3812 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3813 Operand->getStartLoc()));
3817 // Register operand.
3818 if (Operand->isReg() && !Operand->needAddressOf()) {
3819 unsigned NumDefs = Desc.getNumDefs();
3821 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3823 raw_string_ostream OS(Reg);
3824 IP->printRegName(OS, Operand->getReg());
3825 ClobberRegs.insert(StringRef(OS.str()));
3830 // Expr/Input or Output.
3833 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3836 bool isOutput = (i == 1) && Desc.mayStore();
3837 if (Operand->isMem() && Operand->needSizeDirective())
3838 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
3839 Operand->getStartLoc(),
3841 Operand->getMemSize()));
3843 std::string Constraint = "=";
3845 OutputDecls.push_back(OpDecl);
3846 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
3847 Constraint += Operand->getConstraint().str();
3848 OutputConstraints.push_back(Constraint);
3849 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
3850 Operand->getStartLoc(),
3851 Operand->getNameLen()));
3853 InputDecls.push_back(OpDecl);
3854 InputDeclsAddressOf.push_back(Operand->needAddressOf());
3855 InputConstraints.push_back(Operand->getConstraint().str());
3856 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
3857 Operand->getStartLoc(),
3858 Operand->getNameLen()));
3865 // Set the number of Outputs and Inputs.
3866 NumOutputs = OutputDecls.size();
3867 NumInputs = InputDecls.size();
3869 // Set the unique clobbers.
3870 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3871 E = ClobberRegs.end(); I != E; ++I)
3872 Clobbers.push_back(*I);
3874 // Merge the various outputs and inputs. Output are expected first.
3875 if (NumOutputs || NumInputs) {
3876 unsigned NumExprs = NumOutputs + NumInputs;
3877 OpDecls.resize(NumExprs);
3878 Constraints.resize(NumExprs);
3879 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3880 // constraint for addressof. This needs to be cleaned up!
3881 for (unsigned i = 0; i < NumOutputs; ++i) {
3882 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
3883 Constraints[i] = OutputDeclsAddressOf[i] ? "=r" : OutputConstraints[i];
3885 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
3886 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
3887 Constraints[j] = InputDeclsAddressOf[i] ? "r" : InputConstraints[i];
3891 // Build the IR assembly string.
3892 std::string AsmStringIR;
3893 AsmRewriteKind PrevKind = AOK_Imm;
3894 raw_string_ostream OS(AsmStringIR);
3895 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
3896 for (SmallVectorImpl<struct AsmRewrite>::iterator
3897 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3898 const char *Loc = (*I).Loc.getPointer();
3900 AsmRewriteKind Kind = (*I).Kind;
3902 // Emit everything up to the immediate/expression. If the previous rewrite
3903 // was a size directive, then this has already been done.
3904 if (PrevKind != AOK_SizeDirective)
3905 OS << StringRef(Start, Loc - Start);
3908 // Skip the original expression.
3909 if (Kind == AOK_Skip) {
3910 Start = Loc + (*I).Len;
3914 // Rewrite expressions in $N notation.
3932 case AOK_SizeDirective:
3935 case 8: OS << "byte ptr "; break;
3936 case 16: OS << "word ptr "; break;
3937 case 32: OS << "dword ptr "; break;
3938 case 64: OS << "qword ptr "; break;
3939 case 80: OS << "xword ptr "; break;
3940 case 128: OS << "xmmword ptr "; break;
3941 case 256: OS << "ymmword ptr "; break;
3947 case AOK_DotOperator:
3952 // Skip the original expression.
3953 if (Kind != AOK_SizeDirective)
3954 Start = Loc + (*I).Len;
3957 // Emit the remainder of the asm string.
3958 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3959 if (Start != AsmEnd)
3960 OS << StringRef(Start, AsmEnd - Start);
3962 AsmString = OS.str();
3966 /// \brief Create an MCAsmParser instance.
3967 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3968 MCContext &C, MCStreamer &Out,
3969 const MCAsmInfo &MAI) {
3970 return new AsmParser(SM, C, Out, MAI);