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.getLoc();
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.getLoc();
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 EndLoc = Lexer.getLoc();
778 StringRef Identifier;
779 if (ParseIdentifier(Identifier))
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.getLoc();
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.getLoc();
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());
839 case AsmToken::Dot: {
840 // This is a '.' reference, which references the current PC. Emit a
841 // temporary label to the streamer and refer to it.
842 MCSymbol *Sym = Ctx.CreateTempSymbol();
844 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
845 EndLoc = Lexer.getLoc();
846 Lex(); // Eat identifier.
849 case AsmToken::LParen:
850 Lex(); // Eat the '('.
851 return ParseParenExpr(Res, EndLoc);
852 case AsmToken::LBrac:
853 if (!PlatformParser->HasBracketExpressions())
854 return TokError("brackets expression not supported on this target");
855 Lex(); // Eat the '['.
856 return ParseBracketExpr(Res, EndLoc);
857 case AsmToken::Minus:
858 Lex(); // Eat the operator.
859 if (ParsePrimaryExpr(Res, EndLoc))
861 Res = MCUnaryExpr::CreateMinus(Res, getContext());
864 Lex(); // Eat the operator.
865 if (ParsePrimaryExpr(Res, EndLoc))
867 Res = MCUnaryExpr::CreatePlus(Res, getContext());
869 case AsmToken::Tilde:
870 Lex(); // Eat the operator.
871 if (ParsePrimaryExpr(Res, EndLoc))
873 Res = MCUnaryExpr::CreateNot(Res, getContext());
878 bool AsmParser::ParseExpression(const MCExpr *&Res) {
880 return ParseExpression(Res, EndLoc);
884 AsmParser::ApplyModifierToExpr(const MCExpr *E,
885 MCSymbolRefExpr::VariantKind Variant) {
886 // Recurse over the given expression, rebuilding it to apply the given variant
887 // if there is exactly one symbol.
888 switch (E->getKind()) {
890 case MCExpr::Constant:
893 case MCExpr::SymbolRef: {
894 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
896 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
897 TokError("invalid variant on expression '" +
898 getTok().getIdentifier() + "' (already modified)");
902 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
905 case MCExpr::Unary: {
906 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
907 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
910 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
913 case MCExpr::Binary: {
914 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
915 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
916 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
921 if (!LHS) LHS = BE->getLHS();
922 if (!RHS) RHS = BE->getRHS();
924 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
928 llvm_unreachable("Invalid expression kind!");
931 /// ParseExpression - Parse an expression and return it.
933 /// expr ::= expr &&,|| expr -> lowest.
934 /// expr ::= expr |,^,&,! expr
935 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
936 /// expr ::= expr <<,>> expr
937 /// expr ::= expr +,- expr
938 /// expr ::= expr *,/,% expr -> highest.
939 /// expr ::= primaryexpr
941 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
942 // Parse the expression.
944 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
947 // As a special case, we support 'a op b @ modifier' by rewriting the
948 // expression to include the modifier. This is inefficient, but in general we
949 // expect users to use 'a@modifier op b'.
950 if (Lexer.getKind() == AsmToken::At) {
953 if (Lexer.isNot(AsmToken::Identifier))
954 return TokError("unexpected symbol modifier following '@'");
956 MCSymbolRefExpr::VariantKind Variant =
957 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
958 if (Variant == MCSymbolRefExpr::VK_Invalid)
959 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
961 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
963 return TokError("invalid modifier '" + getTok().getIdentifier() +
964 "' (no symbols present)");
971 // Try to constant fold it up front, if possible.
973 if (Res->EvaluateAsAbsolute(Value))
974 Res = MCConstantExpr::Create(Value, getContext());
979 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
981 return ParseParenExpr(Res, EndLoc) ||
982 ParseBinOpRHS(1, Res, EndLoc);
985 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
988 SMLoc StartLoc = Lexer.getLoc();
989 if (ParseExpression(Expr))
992 if (!Expr->EvaluateAsAbsolute(Res))
993 return Error(StartLoc, "expected absolute expression");
998 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
999 MCBinaryExpr::Opcode &Kind) {
1002 return 0; // not a binop.
1004 // Lowest Precedence: &&, ||
1005 case AsmToken::AmpAmp:
1006 Kind = MCBinaryExpr::LAnd;
1008 case AsmToken::PipePipe:
1009 Kind = MCBinaryExpr::LOr;
1013 // Low Precedence: |, &, ^
1015 // FIXME: gas seems to support '!' as an infix operator?
1016 case AsmToken::Pipe:
1017 Kind = MCBinaryExpr::Or;
1019 case AsmToken::Caret:
1020 Kind = MCBinaryExpr::Xor;
1023 Kind = MCBinaryExpr::And;
1026 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1027 case AsmToken::EqualEqual:
1028 Kind = MCBinaryExpr::EQ;
1030 case AsmToken::ExclaimEqual:
1031 case AsmToken::LessGreater:
1032 Kind = MCBinaryExpr::NE;
1034 case AsmToken::Less:
1035 Kind = MCBinaryExpr::LT;
1037 case AsmToken::LessEqual:
1038 Kind = MCBinaryExpr::LTE;
1040 case AsmToken::Greater:
1041 Kind = MCBinaryExpr::GT;
1043 case AsmToken::GreaterEqual:
1044 Kind = MCBinaryExpr::GTE;
1047 // Intermediate Precedence: <<, >>
1048 case AsmToken::LessLess:
1049 Kind = MCBinaryExpr::Shl;
1051 case AsmToken::GreaterGreater:
1052 Kind = MCBinaryExpr::Shr;
1055 // High Intermediate Precedence: +, -
1056 case AsmToken::Plus:
1057 Kind = MCBinaryExpr::Add;
1059 case AsmToken::Minus:
1060 Kind = MCBinaryExpr::Sub;
1063 // Highest Precedence: *, /, %
1064 case AsmToken::Star:
1065 Kind = MCBinaryExpr::Mul;
1067 case AsmToken::Slash:
1068 Kind = MCBinaryExpr::Div;
1070 case AsmToken::Percent:
1071 Kind = MCBinaryExpr::Mod;
1077 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1078 /// Res contains the LHS of the expression on input.
1079 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1082 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1083 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1085 // If the next token is lower precedence than we are allowed to eat, return
1086 // successfully with what we ate already.
1087 if (TokPrec < Precedence)
1092 // Eat the next primary expression.
1094 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1096 // If BinOp binds less tightly with RHS than the operator after RHS, let
1097 // the pending operator take RHS as its LHS.
1098 MCBinaryExpr::Opcode Dummy;
1099 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1100 if (TokPrec < NextTokPrec) {
1101 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1104 // Merge LHS and RHS according to operator.
1105 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1110 /// ::= EndOfStatement
1111 /// ::= Label* Directive ...Operands... EndOfStatement
1112 /// ::= Label* Identifier OperandList* EndOfStatement
1113 bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
1114 if (Lexer.is(AsmToken::EndOfStatement)) {
1120 // Statements always start with an identifier or are a full line comment.
1121 AsmToken ID = getTok();
1122 SMLoc IDLoc = ID.getLoc();
1124 int64_t LocalLabelVal = -1;
1125 // A full line comment is a '#' as the first token.
1126 if (Lexer.is(AsmToken::Hash))
1127 return ParseCppHashLineFilenameComment(IDLoc);
1129 // Allow an integer followed by a ':' as a directional local label.
1130 if (Lexer.is(AsmToken::Integer)) {
1131 LocalLabelVal = getTok().getIntVal();
1132 if (LocalLabelVal < 0) {
1133 if (!TheCondState.Ignore)
1134 return TokError("unexpected token at start of statement");
1138 IDVal = getTok().getString();
1139 Lex(); // Consume the integer token to be used as an identifier token.
1140 if (Lexer.getKind() != AsmToken::Colon) {
1141 if (!TheCondState.Ignore)
1142 return TokError("unexpected token at start of statement");
1146 } else if (Lexer.is(AsmToken::Dot)) {
1147 // Treat '.' as a valid identifier in this context.
1151 } else if (ParseIdentifier(IDVal)) {
1152 if (!TheCondState.Ignore)
1153 return TokError("unexpected token at start of statement");
1158 // Handle conditional assembly here before checking for skipping. We
1159 // have to do this so that .endif isn't skipped in a ".if 0" block for
1162 return ParseDirectiveIf(IDLoc);
1163 if (IDVal == ".ifb")
1164 return ParseDirectiveIfb(IDLoc, true);
1165 if (IDVal == ".ifnb")
1166 return ParseDirectiveIfb(IDLoc, false);
1167 if (IDVal == ".ifc")
1168 return ParseDirectiveIfc(IDLoc, true);
1169 if (IDVal == ".ifnc")
1170 return ParseDirectiveIfc(IDLoc, false);
1171 if (IDVal == ".ifdef")
1172 return ParseDirectiveIfdef(IDLoc, true);
1173 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1174 return ParseDirectiveIfdef(IDLoc, false);
1175 if (IDVal == ".elseif")
1176 return ParseDirectiveElseIf(IDLoc);
1177 if (IDVal == ".else")
1178 return ParseDirectiveElse(IDLoc);
1179 if (IDVal == ".endif")
1180 return ParseDirectiveEndIf(IDLoc);
1182 // If we are in a ".if 0" block, ignore this statement.
1183 if (TheCondState.Ignore) {
1184 EatToEndOfStatement();
1188 // FIXME: Recurse on local labels?
1190 // See what kind of statement we have.
1191 switch (Lexer.getKind()) {
1192 case AsmToken::Colon: {
1193 CheckForValidSection();
1195 // identifier ':' -> Label.
1198 // Diagnose attempt to use '.' as a label.
1200 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1202 // Diagnose attempt to use a variable as a label.
1204 // FIXME: Diagnostics. Note the location of the definition as a label.
1205 // FIXME: This doesn't diagnose assignment to a symbol which has been
1206 // implicitly marked as external.
1208 if (LocalLabelVal == -1)
1209 Sym = getContext().GetOrCreateSymbol(IDVal);
1211 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1212 if (!Sym->isUndefined() || Sym->isVariable())
1213 return Error(IDLoc, "invalid symbol redefinition");
1218 // If we are generating dwarf for assembly source files then gather the
1219 // info to make a dwarf label entry for this label if needed.
1220 if (getContext().getGenDwarfForAssembly())
1221 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1224 // Consume any end of statement token, if present, to avoid spurious
1225 // AddBlankLine calls().
1226 if (Lexer.is(AsmToken::EndOfStatement)) {
1228 if (Lexer.is(AsmToken::Eof))
1235 case AsmToken::Equal:
1236 // identifier '=' ... -> assignment statement
1239 return ParseAssignment(IDVal, true);
1241 default: // Normal instruction or directive.
1245 // If macros are enabled, check to see if this is a macro instantiation.
1247 if (const Macro *M = MacroMap.lookup(IDVal))
1248 return HandleMacroEntry(IDVal, IDLoc, M);
1250 // Otherwise, we have a normal instruction or directive.
1251 if (IDVal[0] == '.' && IDVal != ".") {
1253 // Target hook for parsing target specific directives.
1254 if (!getTargetParser().ParseDirective(ID))
1257 // Assembler features
1258 if (IDVal == ".set" || IDVal == ".equ")
1259 return ParseDirectiveSet(IDVal, true);
1260 if (IDVal == ".equiv")
1261 return ParseDirectiveSet(IDVal, false);
1265 if (IDVal == ".ascii")
1266 return ParseDirectiveAscii(IDVal, false);
1267 if (IDVal == ".asciz" || IDVal == ".string")
1268 return ParseDirectiveAscii(IDVal, true);
1270 if (IDVal == ".byte")
1271 return ParseDirectiveValue(1);
1272 if (IDVal == ".short")
1273 return ParseDirectiveValue(2);
1274 if (IDVal == ".value")
1275 return ParseDirectiveValue(2);
1276 if (IDVal == ".2byte")
1277 return ParseDirectiveValue(2);
1278 if (IDVal == ".long")
1279 return ParseDirectiveValue(4);
1280 if (IDVal == ".int")
1281 return ParseDirectiveValue(4);
1282 if (IDVal == ".4byte")
1283 return ParseDirectiveValue(4);
1284 if (IDVal == ".quad")
1285 return ParseDirectiveValue(8);
1286 if (IDVal == ".8byte")
1287 return ParseDirectiveValue(8);
1288 if (IDVal == ".single" || IDVal == ".float")
1289 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1290 if (IDVal == ".double")
1291 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1293 if (IDVal == ".align") {
1294 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1295 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1297 if (IDVal == ".align32") {
1298 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1299 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1301 if (IDVal == ".balign")
1302 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1303 if (IDVal == ".balignw")
1304 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1305 if (IDVal == ".balignl")
1306 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1307 if (IDVal == ".p2align")
1308 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1309 if (IDVal == ".p2alignw")
1310 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1311 if (IDVal == ".p2alignl")
1312 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1314 if (IDVal == ".bundle_align_mode")
1315 return ParseDirectiveBundleAlignMode();
1316 if (IDVal == ".bundle_lock")
1317 return ParseDirectiveBundleLock();
1318 if (IDVal == ".bundle_unlock")
1319 return ParseDirectiveBundleUnlock();
1321 if (IDVal == ".org")
1322 return ParseDirectiveOrg();
1324 if (IDVal == ".fill")
1325 return ParseDirectiveFill();
1326 if (IDVal == ".space" || IDVal == ".skip")
1327 return ParseDirectiveSpace();
1328 if (IDVal == ".zero")
1329 return ParseDirectiveZero();
1331 // Symbol attribute directives
1333 if (IDVal == ".extern") {
1334 EatToEndOfStatement(); // .extern is the default, ignore it.
1337 if (IDVal == ".globl" || IDVal == ".global")
1338 return ParseDirectiveSymbolAttribute(MCSA_Global);
1339 if (IDVal == ".indirect_symbol")
1340 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1341 if (IDVal == ".lazy_reference")
1342 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1343 if (IDVal == ".no_dead_strip")
1344 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1345 if (IDVal == ".symbol_resolver")
1346 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1347 if (IDVal == ".private_extern")
1348 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1349 if (IDVal == ".reference")
1350 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1351 if (IDVal == ".weak_definition")
1352 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1353 if (IDVal == ".weak_reference")
1354 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1355 if (IDVal == ".weak_def_can_be_hidden")
1356 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1358 if (IDVal == ".comm" || IDVal == ".common")
1359 return ParseDirectiveComm(/*IsLocal=*/false);
1360 if (IDVal == ".lcomm")
1361 return ParseDirectiveComm(/*IsLocal=*/true);
1363 if (IDVal == ".abort")
1364 return ParseDirectiveAbort();
1365 if (IDVal == ".include")
1366 return ParseDirectiveInclude();
1367 if (IDVal == ".incbin")
1368 return ParseDirectiveIncbin();
1370 if (IDVal == ".code16" || IDVal == ".code16gcc")
1371 return TokError(Twine(IDVal) + " not supported yet");
1373 // Macro-like directives
1374 if (IDVal == ".rept")
1375 return ParseDirectiveRept(IDLoc);
1376 if (IDVal == ".irp")
1377 return ParseDirectiveIrp(IDLoc);
1378 if (IDVal == ".irpc")
1379 return ParseDirectiveIrpc(IDLoc);
1380 if (IDVal == ".endr")
1381 return ParseDirectiveEndr(IDLoc);
1383 // Look up the handler in the handler table.
1384 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1385 DirectiveMap.lookup(IDVal);
1387 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1390 return Error(IDLoc, "unknown directive");
1394 if (ParsingInlineAsm && IDVal == "_emit")
1395 return ParseDirectiveEmit(IDLoc, Info);
1397 CheckForValidSection();
1399 // Canonicalize the opcode to lower case.
1400 SmallString<128> OpcodeStr;
1401 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1402 OpcodeStr.push_back(tolower(IDVal[i]));
1404 ParseInstructionInfo IInfo(Info.AsmRewrites);
1405 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1406 IDLoc,Info.ParsedOperands);
1407 Info.ParseError = HadError;
1409 // Dump the parsed representation, if requested.
1410 if (getShowParsedOperands()) {
1411 SmallString<256> Str;
1412 raw_svector_ostream OS(Str);
1413 OS << "parsed instruction: [";
1414 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1417 Info.ParsedOperands[i]->print(OS);
1421 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1424 // If we are generating dwarf for assembly source files and the current
1425 // section is the initial text section then generate a .loc directive for
1427 if (!HadError && getContext().getGenDwarfForAssembly() &&
1428 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
1430 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1432 // If we previously parsed a cpp hash file line comment then make sure the
1433 // current Dwarf File is for the CppHashFilename if not then emit the
1434 // Dwarf File table for it and adjust the line number for the .loc.
1435 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1436 getContext().getMCDwarfFiles();
1437 if (CppHashFilename.size() != 0) {
1438 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1440 getStreamer().EmitDwarfFileDirective(
1441 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1443 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
1444 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1447 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1448 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1449 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1453 // If parsing succeeded, match the instruction.
1456 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1457 Info.ParsedOperands,
1462 // Don't skip the rest of the line, the instruction parser is responsible for
1467 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1468 /// since they may not be able to be tokenized to get to the end of line token.
1469 void AsmParser::EatToEndOfLine() {
1470 if (!Lexer.is(AsmToken::EndOfStatement))
1471 Lexer.LexUntilEndOfLine();
1476 /// ParseCppHashLineFilenameComment as this:
1477 /// ::= # number "filename"
1478 /// or just as a full line comment if it doesn't have a number and a string.
1479 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1480 Lex(); // Eat the hash token.
1482 if (getLexer().isNot(AsmToken::Integer)) {
1483 // Consume the line since in cases it is not a well-formed line directive,
1484 // as if were simply a full line comment.
1489 int64_t LineNumber = getTok().getIntVal();
1492 if (getLexer().isNot(AsmToken::String)) {
1497 StringRef Filename = getTok().getString();
1498 // Get rid of the enclosing quotes.
1499 Filename = Filename.substr(1, Filename.size()-2);
1501 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1503 CppHashFilename = Filename;
1504 CppHashLineNumber = LineNumber;
1505 CppHashBuf = CurBuffer;
1507 // Ignore any trailing characters, they're just comment.
1512 /// DiagHandler - will use the last parsed cpp hash line filename comment
1513 /// for the Filename and LineNo if any in the diagnostic.
1514 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1515 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1516 raw_ostream &OS = errs();
1518 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1519 const SMLoc &DiagLoc = Diag.getLoc();
1520 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1521 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1523 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1524 // before printing the message.
1525 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1526 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1527 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1528 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1531 // If we have not parsed a cpp hash line filename comment or the source
1532 // manager changed or buffer changed (like in a nested include) then just
1533 // print the normal diagnostic using its Filename and LineNo.
1534 if (!Parser->CppHashLineNumber ||
1535 &DiagSrcMgr != &Parser->SrcMgr ||
1536 DiagBuf != CppHashBuf) {
1537 if (Parser->SavedDiagHandler)
1538 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1544 // Use the CppHashFilename and calculate a line number based on the
1545 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1547 const std::string Filename = Parser->CppHashFilename;
1549 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1550 int CppHashLocLineNo =
1551 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1552 int LineNo = Parser->CppHashLineNumber - 1 +
1553 (DiagLocLineNo - CppHashLocLineNo);
1555 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1556 Filename, LineNo, Diag.getColumnNo(),
1557 Diag.getKind(), Diag.getMessage(),
1558 Diag.getLineContents(), Diag.getRanges());
1560 if (Parser->SavedDiagHandler)
1561 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1563 NewDiag.print(0, OS);
1566 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1567 // difference being that that function accepts '@' as part of identifiers and
1568 // we can't do that. AsmLexer.cpp should probably be changed to handle
1569 // '@' as a special case when needed.
1570 static bool isIdentifierChar(char c) {
1571 return isalnum(c) || c == '_' || c == '$' || c == '.';
1574 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1575 const MacroParameters &Parameters,
1576 const MacroArguments &A,
1578 unsigned NParameters = Parameters.size();
1579 if (NParameters != 0 && NParameters != A.size())
1580 return Error(L, "Wrong number of arguments");
1582 // A macro without parameters is handled differently on Darwin:
1583 // gas accepts no arguments and does no substitutions
1584 while (!Body.empty()) {
1585 // Scan for the next substitution.
1586 std::size_t End = Body.size(), Pos = 0;
1587 for (; Pos != End; ++Pos) {
1588 // Check for a substitution or escape.
1590 // This macro has no parameters, look for $0, $1, etc.
1591 if (Body[Pos] != '$' || Pos + 1 == End)
1594 char Next = Body[Pos + 1];
1595 if (Next == '$' || Next == 'n' || isdigit(Next))
1598 // This macro has parameters, look for \foo, \bar, etc.
1599 if (Body[Pos] == '\\' && Pos + 1 != End)
1605 OS << Body.slice(0, Pos);
1607 // Check if we reached the end.
1612 switch (Body[Pos+1]) {
1618 // $n => number of arguments
1623 // $[0-9] => argument
1625 // Missing arguments are ignored.
1626 unsigned Index = Body[Pos+1] - '0';
1627 if (Index >= A.size())
1630 // Otherwise substitute with the token values, with spaces eliminated.
1631 for (MacroArgument::const_iterator it = A[Index].begin(),
1632 ie = A[Index].end(); it != ie; ++it)
1633 OS << it->getString();
1639 unsigned I = Pos + 1;
1640 while (isIdentifierChar(Body[I]) && I + 1 != End)
1643 const char *Begin = Body.data() + Pos +1;
1644 StringRef Argument(Begin, I - (Pos +1));
1646 for (; Index < NParameters; ++Index)
1647 if (Parameters[Index].first == Argument)
1650 if (Index == NParameters) {
1651 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1654 OS << '\\' << Argument;
1658 for (MacroArgument::const_iterator it = A[Index].begin(),
1659 ie = A[Index].end(); it != ie; ++it)
1660 if (it->getKind() == AsmToken::String)
1661 OS << it->getStringContents();
1663 OS << it->getString();
1665 Pos += 1 + Argument.size();
1668 // Update the scan point.
1669 Body = Body.substr(Pos);
1675 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL,
1678 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1683 static bool IsOperator(AsmToken::TokenKind kind)
1689 case AsmToken::Plus:
1690 case AsmToken::Minus:
1691 case AsmToken::Tilde:
1692 case AsmToken::Slash:
1693 case AsmToken::Star:
1695 case AsmToken::Equal:
1696 case AsmToken::EqualEqual:
1697 case AsmToken::Pipe:
1698 case AsmToken::PipePipe:
1699 case AsmToken::Caret:
1701 case AsmToken::AmpAmp:
1702 case AsmToken::Exclaim:
1703 case AsmToken::ExclaimEqual:
1704 case AsmToken::Percent:
1705 case AsmToken::Less:
1706 case AsmToken::LessEqual:
1707 case AsmToken::LessLess:
1708 case AsmToken::LessGreater:
1709 case AsmToken::Greater:
1710 case AsmToken::GreaterEqual:
1711 case AsmToken::GreaterGreater:
1716 /// ParseMacroArgument - Extract AsmTokens for a macro argument.
1717 /// This is used for both default macro parameter values and the
1718 /// arguments in macro invocations
1719 bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1720 AsmToken::TokenKind &ArgumentDelimiter) {
1721 unsigned ParenLevel = 0;
1722 unsigned AddTokens = 0;
1724 // gas accepts arguments separated by whitespace, except on Darwin
1726 Lexer.setSkipSpace(false);
1729 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1730 Lexer.setSkipSpace(true);
1731 return TokError("unexpected token in macro instantiation");
1734 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1735 // Spaces and commas cannot be mixed to delimit parameters
1736 if (ArgumentDelimiter == AsmToken::Eof)
1737 ArgumentDelimiter = AsmToken::Comma;
1738 else if (ArgumentDelimiter != AsmToken::Comma) {
1739 Lexer.setSkipSpace(true);
1740 return TokError("expected ' ' for macro argument separator");
1745 if (Lexer.is(AsmToken::Space)) {
1746 Lex(); // Eat spaces
1748 // Spaces can delimit parameters, but could also be part an expression.
1749 // If the token after a space is an operator, add the token and the next
1750 // one into this argument
1751 if (ArgumentDelimiter == AsmToken::Space ||
1752 ArgumentDelimiter == AsmToken::Eof) {
1753 if (IsOperator(Lexer.getKind())) {
1754 // Check to see whether the token is used as an operator,
1755 // or part of an identifier
1756 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1757 if (*NextChar == ' ')
1761 if (!AddTokens && ParenLevel == 0) {
1762 if (ArgumentDelimiter == AsmToken::Eof &&
1763 !IsOperator(Lexer.getKind()))
1764 ArgumentDelimiter = AsmToken::Space;
1770 // HandleMacroEntry relies on not advancing the lexer here
1771 // to be able to fill in the remaining default parameter values
1772 if (Lexer.is(AsmToken::EndOfStatement))
1775 // Adjust the current parentheses level.
1776 if (Lexer.is(AsmToken::LParen))
1778 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1781 // Append the token to the current argument list.
1782 MA.push_back(getTok());
1788 Lexer.setSkipSpace(true);
1789 if (ParenLevel != 0)
1790 return TokError("unbalanced parentheses in macro argument");
1794 // Parse the macro instantiation arguments.
1795 bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
1796 const unsigned NParameters = M ? M->Parameters.size() : 0;
1797 // Argument delimiter is initially unknown. It will be set by
1798 // ParseMacroArgument()
1799 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1801 // Parse two kinds of macro invocations:
1802 // - macros defined without any parameters accept an arbitrary number of them
1803 // - macros defined with parameters accept at most that many of them
1804 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1808 if (ParseMacroArgument(MA, ArgumentDelimiter))
1811 if (!MA.empty() || !NParameters)
1813 else if (NParameters) {
1814 if (!M->Parameters[Parameter].second.empty())
1815 A.push_back(M->Parameters[Parameter].second);
1818 // At the end of the statement, fill in remaining arguments that have
1819 // default values. If there aren't any, then the next argument is
1820 // required but missing
1821 if (Lexer.is(AsmToken::EndOfStatement)) {
1822 if (NParameters && Parameter < NParameters - 1) {
1823 if (M->Parameters[Parameter + 1].second.empty())
1824 return TokError("macro argument '" +
1825 Twine(M->Parameters[Parameter + 1].first) +
1833 if (Lexer.is(AsmToken::Comma))
1836 return TokError("Too many arguments");
1839 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1841 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1842 // this, although we should protect against infinite loops.
1843 if (ActiveMacros.size() == 20)
1844 return TokError("macros cannot be nested more than 20 levels deep");
1847 if (ParseMacroArguments(M, A))
1850 // Remove any trailing empty arguments. Do this after-the-fact as we have
1851 // to keep empty arguments in the middle of the list or positionality
1852 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1853 while (!A.empty() && A.back().empty())
1856 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1857 // to hold the macro body with substitutions.
1858 SmallString<256> Buf;
1859 StringRef Body = M->Body;
1860 raw_svector_ostream OS(Buf);
1862 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1865 // We include the .endmacro in the buffer as our queue to exit the macro
1867 OS << ".endmacro\n";
1869 MemoryBuffer *Instantiation =
1870 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1872 // Create the macro instantiation object and add to the current macro
1873 // instantiation stack.
1874 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1878 ActiveMacros.push_back(MI);
1880 // Jump to the macro instantiation and prime the lexer.
1881 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1882 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1888 void AsmParser::HandleMacroExit() {
1889 // Jump to the EndOfStatement we should return to, and consume it.
1890 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
1893 // Pop the instantiation entry.
1894 delete ActiveMacros.back();
1895 ActiveMacros.pop_back();
1898 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1899 switch (Value->getKind()) {
1900 case MCExpr::Binary: {
1901 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1902 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1905 case MCExpr::Target:
1906 case MCExpr::Constant:
1908 case MCExpr::SymbolRef: {
1909 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1911 return IsUsedIn(Sym, S.getVariableValue());
1915 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1918 llvm_unreachable("Unknown expr kind!");
1921 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1923 // FIXME: Use better location, we should use proper tokens.
1924 SMLoc EqualLoc = Lexer.getLoc();
1926 const MCExpr *Value;
1927 if (ParseExpression(Value))
1930 // Note: we don't count b as used in "a = b". This is to allow
1934 if (Lexer.isNot(AsmToken::EndOfStatement))
1935 return TokError("unexpected token in assignment");
1937 // Error on assignment to '.'.
1939 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1940 "(use '.space' or '.org').)"));
1943 // Eat the end of statement marker.
1946 // Validate that the LHS is allowed to be a variable (either it has not been
1947 // used as a symbol, or it is an absolute symbol).
1948 MCSymbol *Sym = getContext().LookupSymbol(Name);
1950 // Diagnose assignment to a label.
1952 // FIXME: Diagnostics. Note the location of the definition as a label.
1953 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1954 if (IsUsedIn(Sym, Value))
1955 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1956 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1957 ; // Allow redefinitions of undefined symbols only used in directives.
1958 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1959 ; // Allow redefinitions of variables that haven't yet been used.
1960 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1961 return Error(EqualLoc, "redefinition of '" + Name + "'");
1962 else if (!Sym->isVariable())
1963 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1964 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1965 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1968 // Don't count these checks as uses.
1969 Sym->setUsed(false);
1971 Sym = getContext().GetOrCreateSymbol(Name);
1973 // FIXME: Handle '.'.
1975 // Do the assignment.
1976 Out.EmitAssignment(Sym, Value);
1978 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1984 /// ParseIdentifier:
1987 bool AsmParser::ParseIdentifier(StringRef &Res) {
1988 // The assembler has relaxed rules for accepting identifiers, in particular we
1989 // allow things like '.globl $foo', which would normally be separate
1990 // tokens. At this level, we have already lexed so we cannot (currently)
1991 // handle this as a context dependent token, instead we detect adjacent tokens
1992 // and return the combined identifier.
1993 if (Lexer.is(AsmToken::Dollar)) {
1994 SMLoc DollarLoc = getLexer().getLoc();
1996 // Consume the dollar sign, and check for a following identifier.
1998 if (Lexer.isNot(AsmToken::Identifier))
2001 // We have a '$' followed by an identifier, make sure they are adjacent.
2002 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2005 // Construct the joined identifier and consume the token.
2006 Res = StringRef(DollarLoc.getPointer(),
2007 getTok().getIdentifier().size() + 1);
2012 if (Lexer.isNot(AsmToken::Identifier) &&
2013 Lexer.isNot(AsmToken::String))
2016 Res = getTok().getIdentifier();
2018 Lex(); // Consume the identifier token.
2023 /// ParseDirectiveSet:
2024 /// ::= .equ identifier ',' expression
2025 /// ::= .equiv identifier ',' expression
2026 /// ::= .set identifier ',' expression
2027 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
2030 if (ParseIdentifier(Name))
2031 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2033 if (getLexer().isNot(AsmToken::Comma))
2034 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2037 return ParseAssignment(Name, allow_redef, true);
2040 bool AsmParser::ParseEscapedString(std::string &Data) {
2041 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2044 StringRef Str = getTok().getStringContents();
2045 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2046 if (Str[i] != '\\') {
2051 // Recognize escaped characters. Note that this escape semantics currently
2052 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2055 return TokError("unexpected backslash at end of string");
2057 // Recognize octal sequences.
2058 if ((unsigned) (Str[i] - '0') <= 7) {
2059 // Consume up to three octal characters.
2060 unsigned Value = Str[i] - '0';
2062 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2064 Value = Value * 8 + (Str[i] - '0');
2066 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2068 Value = Value * 8 + (Str[i] - '0');
2073 return TokError("invalid octal escape sequence (out of range)");
2075 Data += (unsigned char) Value;
2079 // Otherwise recognize individual escapes.
2082 // Just reject invalid escape sequences for now.
2083 return TokError("invalid escape sequence (unrecognized character)");
2085 case 'b': Data += '\b'; break;
2086 case 'f': Data += '\f'; break;
2087 case 'n': Data += '\n'; break;
2088 case 'r': Data += '\r'; break;
2089 case 't': Data += '\t'; break;
2090 case '"': Data += '"'; break;
2091 case '\\': Data += '\\'; break;
2098 /// ParseDirectiveAscii:
2099 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2100 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2101 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2102 CheckForValidSection();
2105 if (getLexer().isNot(AsmToken::String))
2106 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2109 if (ParseEscapedString(Data))
2112 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2114 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2118 if (getLexer().is(AsmToken::EndOfStatement))
2121 if (getLexer().isNot(AsmToken::Comma))
2122 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2131 /// ParseDirectiveValue
2132 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2133 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2134 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2135 CheckForValidSection();
2138 const MCExpr *Value;
2139 SMLoc ExprLoc = getLexer().getLoc();
2140 if (ParseExpression(Value))
2143 // Special case constant expressions to match code generator.
2144 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2145 assert(Size <= 8 && "Invalid size");
2146 uint64_t IntValue = MCE->getValue();
2147 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2148 return Error(ExprLoc, "literal value out of range for directive");
2149 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2151 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2153 if (getLexer().is(AsmToken::EndOfStatement))
2156 // FIXME: Improve diagnostic.
2157 if (getLexer().isNot(AsmToken::Comma))
2158 return TokError("unexpected token in directive");
2167 /// ParseDirectiveRealValue
2168 /// ::= (.single | .double) [ expression (, expression)* ]
2169 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2170 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2171 CheckForValidSection();
2174 // We don't truly support arithmetic on floating point expressions, so we
2175 // have to manually parse unary prefixes.
2177 if (getLexer().is(AsmToken::Minus)) {
2180 } else if (getLexer().is(AsmToken::Plus))
2183 if (getLexer().isNot(AsmToken::Integer) &&
2184 getLexer().isNot(AsmToken::Real) &&
2185 getLexer().isNot(AsmToken::Identifier))
2186 return TokError("unexpected token in directive");
2188 // Convert to an APFloat.
2189 APFloat Value(Semantics);
2190 StringRef IDVal = getTok().getString();
2191 if (getLexer().is(AsmToken::Identifier)) {
2192 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2193 Value = APFloat::getInf(Semantics);
2194 else if (!IDVal.compare_lower("nan"))
2195 Value = APFloat::getNaN(Semantics, false, ~0);
2197 return TokError("invalid floating point literal");
2198 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2199 APFloat::opInvalidOp)
2200 return TokError("invalid floating point literal");
2204 // Consume the numeric token.
2207 // Emit the value as an integer.
2208 APInt AsInt = Value.bitcastToAPInt();
2209 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2210 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2212 if (getLexer().is(AsmToken::EndOfStatement))
2215 if (getLexer().isNot(AsmToken::Comma))
2216 return TokError("unexpected token in directive");
2225 /// ParseDirectiveSpace
2226 /// ::= .space expression [ , expression ]
2227 bool AsmParser::ParseDirectiveSpace() {
2228 CheckForValidSection();
2231 if (ParseAbsoluteExpression(NumBytes))
2234 int64_t FillExpr = 0;
2235 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2236 if (getLexer().isNot(AsmToken::Comma))
2237 return TokError("unexpected token in '.space' directive");
2240 if (ParseAbsoluteExpression(FillExpr))
2243 if (getLexer().isNot(AsmToken::EndOfStatement))
2244 return TokError("unexpected token in '.space' directive");
2250 return TokError("invalid number of bytes in '.space' directive");
2252 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
2253 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
2258 /// ParseDirectiveZero
2259 /// ::= .zero expression
2260 bool AsmParser::ParseDirectiveZero() {
2261 CheckForValidSection();
2264 if (ParseAbsoluteExpression(NumBytes))
2268 if (getLexer().is(AsmToken::Comma)) {
2270 if (ParseAbsoluteExpression(Val))
2274 if (getLexer().isNot(AsmToken::EndOfStatement))
2275 return TokError("unexpected token in '.zero' directive");
2279 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2284 /// ParseDirectiveFill
2285 /// ::= .fill expression , expression , expression
2286 bool AsmParser::ParseDirectiveFill() {
2287 CheckForValidSection();
2290 if (ParseAbsoluteExpression(NumValues))
2293 if (getLexer().isNot(AsmToken::Comma))
2294 return TokError("unexpected token in '.fill' directive");
2298 if (ParseAbsoluteExpression(FillSize))
2301 if (getLexer().isNot(AsmToken::Comma))
2302 return TokError("unexpected token in '.fill' directive");
2306 if (ParseAbsoluteExpression(FillExpr))
2309 if (getLexer().isNot(AsmToken::EndOfStatement))
2310 return TokError("unexpected token in '.fill' directive");
2314 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2315 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2317 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2318 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2323 /// ParseDirectiveOrg
2324 /// ::= .org expression [ , expression ]
2325 bool AsmParser::ParseDirectiveOrg() {
2326 CheckForValidSection();
2328 const MCExpr *Offset;
2329 SMLoc Loc = getTok().getLoc();
2330 if (ParseExpression(Offset))
2333 // Parse optional fill expression.
2334 int64_t FillExpr = 0;
2335 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2336 if (getLexer().isNot(AsmToken::Comma))
2337 return TokError("unexpected token in '.org' directive");
2340 if (ParseAbsoluteExpression(FillExpr))
2343 if (getLexer().isNot(AsmToken::EndOfStatement))
2344 return TokError("unexpected token in '.org' directive");
2349 // Only limited forms of relocatable expressions are accepted here, it
2350 // has to be relative to the current section. The streamer will return
2351 // 'true' if the expression wasn't evaluatable.
2352 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2353 return Error(Loc, "expected assembly-time absolute expression");
2358 /// ParseDirectiveAlign
2359 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2360 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2361 CheckForValidSection();
2363 SMLoc AlignmentLoc = getLexer().getLoc();
2365 if (ParseAbsoluteExpression(Alignment))
2369 bool HasFillExpr = false;
2370 int64_t FillExpr = 0;
2371 int64_t MaxBytesToFill = 0;
2372 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2373 if (getLexer().isNot(AsmToken::Comma))
2374 return TokError("unexpected token in directive");
2377 // The fill expression can be omitted while specifying a maximum number of
2378 // alignment bytes, e.g:
2380 if (getLexer().isNot(AsmToken::Comma)) {
2382 if (ParseAbsoluteExpression(FillExpr))
2386 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2387 if (getLexer().isNot(AsmToken::Comma))
2388 return TokError("unexpected token in directive");
2391 MaxBytesLoc = getLexer().getLoc();
2392 if (ParseAbsoluteExpression(MaxBytesToFill))
2395 if (getLexer().isNot(AsmToken::EndOfStatement))
2396 return TokError("unexpected token in directive");
2405 // Compute alignment in bytes.
2407 // FIXME: Diagnose overflow.
2408 if (Alignment >= 32) {
2409 Error(AlignmentLoc, "invalid alignment value");
2413 Alignment = 1ULL << Alignment;
2416 // Diagnose non-sensical max bytes to align.
2417 if (MaxBytesLoc.isValid()) {
2418 if (MaxBytesToFill < 1) {
2419 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2420 "many bytes, ignoring maximum bytes expression");
2424 if (MaxBytesToFill >= Alignment) {
2425 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2431 // Check whether we should use optimal code alignment for this .align
2433 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2434 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2435 ValueSize == 1 && UseCodeAlign) {
2436 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2438 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2439 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2447 /// ParseDirectiveBundleAlignMode
2448 /// ::= {.bundle_align_mode} expression
2449 bool AsmParser::ParseDirectiveBundleAlignMode() {
2450 CheckForValidSection();
2452 // Expect a single argument: an expression that evaluates to a constant
2453 // in the inclusive range 0-30.
2454 SMLoc ExprLoc = getLexer().getLoc();
2455 int64_t AlignSizePow2;
2456 if (ParseAbsoluteExpression(AlignSizePow2))
2458 else if (getLexer().isNot(AsmToken::EndOfStatement))
2459 return TokError("unexpected token after expression in"
2460 " '.bundle_align_mode' directive");
2461 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
2462 return Error(ExprLoc,
2463 "invalid bundle alignment size (expected between 0 and 30)");
2467 // Because of AlignSizePow2's verified range we can safely truncate it to
2469 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
2473 /// ParseDirectiveBundleLock
2474 /// ::= {.bundle_lock}
2475 bool AsmParser::ParseDirectiveBundleLock() {
2476 CheckForValidSection();
2478 if (getLexer().isNot(AsmToken::EndOfStatement))
2479 return TokError("unexpected token in '.bundle_lock' directive");
2482 getStreamer().EmitBundleLock();
2486 /// ParseDirectiveBundleLock
2487 /// ::= {.bundle_lock}
2488 bool AsmParser::ParseDirectiveBundleUnlock() {
2489 CheckForValidSection();
2491 if (getLexer().isNot(AsmToken::EndOfStatement))
2492 return TokError("unexpected token in '.bundle_unlock' directive");
2495 getStreamer().EmitBundleUnlock();
2499 /// ParseDirectiveSymbolAttribute
2500 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2501 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2502 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2505 SMLoc Loc = getTok().getLoc();
2507 if (ParseIdentifier(Name))
2508 return Error(Loc, "expected identifier in directive");
2510 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2512 // Assembler local symbols don't make any sense here. Complain loudly.
2513 if (Sym->isTemporary())
2514 return Error(Loc, "non-local symbol required in directive");
2516 getStreamer().EmitSymbolAttribute(Sym, Attr);
2518 if (getLexer().is(AsmToken::EndOfStatement))
2521 if (getLexer().isNot(AsmToken::Comma))
2522 return TokError("unexpected token in directive");
2531 /// ParseDirectiveComm
2532 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2533 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2534 CheckForValidSection();
2536 SMLoc IDLoc = getLexer().getLoc();
2538 if (ParseIdentifier(Name))
2539 return TokError("expected identifier in directive");
2541 // Handle the identifier as the key symbol.
2542 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2544 if (getLexer().isNot(AsmToken::Comma))
2545 return TokError("unexpected token in directive");
2549 SMLoc SizeLoc = getLexer().getLoc();
2550 if (ParseAbsoluteExpression(Size))
2553 int64_t Pow2Alignment = 0;
2554 SMLoc Pow2AlignmentLoc;
2555 if (getLexer().is(AsmToken::Comma)) {
2557 Pow2AlignmentLoc = getLexer().getLoc();
2558 if (ParseAbsoluteExpression(Pow2Alignment))
2561 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2562 if (IsLocal && LCOMM == LCOMM::NoAlignment)
2563 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2565 // If this target takes alignments in bytes (not log) validate and convert.
2566 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2567 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
2568 if (!isPowerOf2_64(Pow2Alignment))
2569 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2570 Pow2Alignment = Log2_64(Pow2Alignment);
2574 if (getLexer().isNot(AsmToken::EndOfStatement))
2575 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2579 // NOTE: a size of zero for a .comm should create a undefined symbol
2580 // but a size of .lcomm creates a bss symbol of size zero.
2582 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2583 "be less than zero");
2585 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2586 // may internally end up wanting an alignment in bytes.
2587 // FIXME: Diagnose overflow.
2588 if (Pow2Alignment < 0)
2589 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2590 "alignment, can't be less than zero");
2592 if (!Sym->isUndefined())
2593 return Error(IDLoc, "invalid symbol redefinition");
2595 // Create the Symbol as a common or local common with Size and Pow2Alignment
2597 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2601 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2605 /// ParseDirectiveAbort
2606 /// ::= .abort [... message ...]
2607 bool AsmParser::ParseDirectiveAbort() {
2608 // FIXME: Use loc from directive.
2609 SMLoc Loc = getLexer().getLoc();
2611 StringRef Str = ParseStringToEndOfStatement();
2612 if (getLexer().isNot(AsmToken::EndOfStatement))
2613 return TokError("unexpected token in '.abort' directive");
2618 Error(Loc, ".abort detected. Assembly stopping.");
2620 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2621 // FIXME: Actually abort assembly here.
2626 /// ParseDirectiveInclude
2627 /// ::= .include "filename"
2628 bool AsmParser::ParseDirectiveInclude() {
2629 if (getLexer().isNot(AsmToken::String))
2630 return TokError("expected string in '.include' directive");
2632 std::string Filename = getTok().getString();
2633 SMLoc IncludeLoc = getLexer().getLoc();
2636 if (getLexer().isNot(AsmToken::EndOfStatement))
2637 return TokError("unexpected token in '.include' directive");
2639 // Strip the quotes.
2640 Filename = Filename.substr(1, Filename.size()-2);
2642 // Attempt to switch the lexer to the included file before consuming the end
2643 // of statement to avoid losing it when we switch.
2644 if (EnterIncludeFile(Filename)) {
2645 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2652 /// ParseDirectiveIncbin
2653 /// ::= .incbin "filename"
2654 bool AsmParser::ParseDirectiveIncbin() {
2655 if (getLexer().isNot(AsmToken::String))
2656 return TokError("expected string in '.incbin' directive");
2658 std::string Filename = getTok().getString();
2659 SMLoc IncbinLoc = getLexer().getLoc();
2662 if (getLexer().isNot(AsmToken::EndOfStatement))
2663 return TokError("unexpected token in '.incbin' directive");
2665 // Strip the quotes.
2666 Filename = Filename.substr(1, Filename.size()-2);
2668 // Attempt to process the included file.
2669 if (ProcessIncbinFile(Filename)) {
2670 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2677 /// ParseDirectiveIf
2678 /// ::= .if expression
2679 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2680 TheCondStack.push_back(TheCondState);
2681 TheCondState.TheCond = AsmCond::IfCond;
2682 if (TheCondState.Ignore) {
2683 EatToEndOfStatement();
2686 if (ParseAbsoluteExpression(ExprValue))
2689 if (getLexer().isNot(AsmToken::EndOfStatement))
2690 return TokError("unexpected token in '.if' directive");
2694 TheCondState.CondMet = ExprValue;
2695 TheCondState.Ignore = !TheCondState.CondMet;
2701 /// ParseDirectiveIfb
2703 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2704 TheCondStack.push_back(TheCondState);
2705 TheCondState.TheCond = AsmCond::IfCond;
2707 if (TheCondState.Ignore) {
2708 EatToEndOfStatement();
2710 StringRef Str = ParseStringToEndOfStatement();
2712 if (getLexer().isNot(AsmToken::EndOfStatement))
2713 return TokError("unexpected token in '.ifb' directive");
2717 TheCondState.CondMet = ExpectBlank == Str.empty();
2718 TheCondState.Ignore = !TheCondState.CondMet;
2724 /// ParseDirectiveIfc
2725 /// ::= .ifc string1, string2
2726 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2727 TheCondStack.push_back(TheCondState);
2728 TheCondState.TheCond = AsmCond::IfCond;
2730 if (TheCondState.Ignore) {
2731 EatToEndOfStatement();
2733 StringRef Str1 = ParseStringToComma();
2735 if (getLexer().isNot(AsmToken::Comma))
2736 return TokError("unexpected token in '.ifc' directive");
2740 StringRef Str2 = ParseStringToEndOfStatement();
2742 if (getLexer().isNot(AsmToken::EndOfStatement))
2743 return TokError("unexpected token in '.ifc' directive");
2747 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2748 TheCondState.Ignore = !TheCondState.CondMet;
2754 /// ParseDirectiveIfdef
2755 /// ::= .ifdef symbol
2756 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2758 TheCondStack.push_back(TheCondState);
2759 TheCondState.TheCond = AsmCond::IfCond;
2761 if (TheCondState.Ignore) {
2762 EatToEndOfStatement();
2764 if (ParseIdentifier(Name))
2765 return TokError("expected identifier after '.ifdef'");
2769 MCSymbol *Sym = getContext().LookupSymbol(Name);
2772 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2774 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2775 TheCondState.Ignore = !TheCondState.CondMet;
2781 /// ParseDirectiveElseIf
2782 /// ::= .elseif expression
2783 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2784 if (TheCondState.TheCond != AsmCond::IfCond &&
2785 TheCondState.TheCond != AsmCond::ElseIfCond)
2786 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2788 TheCondState.TheCond = AsmCond::ElseIfCond;
2790 bool LastIgnoreState = false;
2791 if (!TheCondStack.empty())
2792 LastIgnoreState = TheCondStack.back().Ignore;
2793 if (LastIgnoreState || TheCondState.CondMet) {
2794 TheCondState.Ignore = true;
2795 EatToEndOfStatement();
2799 if (ParseAbsoluteExpression(ExprValue))
2802 if (getLexer().isNot(AsmToken::EndOfStatement))
2803 return TokError("unexpected token in '.elseif' directive");
2806 TheCondState.CondMet = ExprValue;
2807 TheCondState.Ignore = !TheCondState.CondMet;
2813 /// ParseDirectiveElse
2815 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2816 if (getLexer().isNot(AsmToken::EndOfStatement))
2817 return TokError("unexpected token in '.else' directive");
2821 if (TheCondState.TheCond != AsmCond::IfCond &&
2822 TheCondState.TheCond != AsmCond::ElseIfCond)
2823 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2825 TheCondState.TheCond = AsmCond::ElseCond;
2826 bool LastIgnoreState = false;
2827 if (!TheCondStack.empty())
2828 LastIgnoreState = TheCondStack.back().Ignore;
2829 if (LastIgnoreState || TheCondState.CondMet)
2830 TheCondState.Ignore = true;
2832 TheCondState.Ignore = false;
2837 /// ParseDirectiveEndIf
2839 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2840 if (getLexer().isNot(AsmToken::EndOfStatement))
2841 return TokError("unexpected token in '.endif' directive");
2845 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2846 TheCondStack.empty())
2847 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2849 if (!TheCondStack.empty()) {
2850 TheCondState = TheCondStack.back();
2851 TheCondStack.pop_back();
2857 /// ParseDirectiveFile
2858 /// ::= .file [number] filename
2859 /// ::= .file number directory filename
2860 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2861 // FIXME: I'm not sure what this is.
2862 int64_t FileNumber = -1;
2863 SMLoc FileNumberLoc = getLexer().getLoc();
2864 if (getLexer().is(AsmToken::Integer)) {
2865 FileNumber = getTok().getIntVal();
2869 return TokError("file number less than one");
2872 if (getLexer().isNot(AsmToken::String))
2873 return TokError("unexpected token in '.file' directive");
2875 // Usually the directory and filename together, otherwise just the directory.
2876 StringRef Path = getTok().getString();
2877 Path = Path.substr(1, Path.size()-2);
2880 StringRef Directory;
2882 if (getLexer().is(AsmToken::String)) {
2883 if (FileNumber == -1)
2884 return TokError("explicit path specified, but no file number");
2885 Filename = getTok().getString();
2886 Filename = Filename.substr(1, Filename.size()-2);
2893 if (getLexer().isNot(AsmToken::EndOfStatement))
2894 return TokError("unexpected token in '.file' directive");
2896 if (FileNumber == -1)
2897 getStreamer().EmitFileDirective(Filename);
2899 if (getContext().getGenDwarfForAssembly() == true)
2900 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2901 "used to generate dwarf debug info for assembly code");
2903 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2904 Error(FileNumberLoc, "file number already allocated");
2910 /// ParseDirectiveLine
2911 /// ::= .line [number]
2912 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2913 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2914 if (getLexer().isNot(AsmToken::Integer))
2915 return TokError("unexpected token in '.line' directive");
2917 int64_t LineNumber = getTok().getIntVal();
2921 // FIXME: Do something with the .line.
2924 if (getLexer().isNot(AsmToken::EndOfStatement))
2925 return TokError("unexpected token in '.line' directive");
2931 /// ParseDirectiveLoc
2932 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2933 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2934 /// The first number is a file number, must have been previously assigned with
2935 /// a .file directive, the second number is the line number and optionally the
2936 /// third number is a column position (zero if not specified). The remaining
2937 /// optional items are .loc sub-directives.
2938 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2940 if (getLexer().isNot(AsmToken::Integer))
2941 return TokError("unexpected token in '.loc' directive");
2942 int64_t FileNumber = getTok().getIntVal();
2944 return TokError("file number less than one in '.loc' directive");
2945 if (!getContext().isValidDwarfFileNumber(FileNumber))
2946 return TokError("unassigned file number in '.loc' directive");
2949 int64_t LineNumber = 0;
2950 if (getLexer().is(AsmToken::Integer)) {
2951 LineNumber = getTok().getIntVal();
2953 return TokError("line number less than one in '.loc' directive");
2957 int64_t ColumnPos = 0;
2958 if (getLexer().is(AsmToken::Integer)) {
2959 ColumnPos = getTok().getIntVal();
2961 return TokError("column position less than zero in '.loc' directive");
2965 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2967 int64_t Discriminator = 0;
2968 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2970 if (getLexer().is(AsmToken::EndOfStatement))
2974 SMLoc Loc = getTok().getLoc();
2975 if (getParser().ParseIdentifier(Name))
2976 return TokError("unexpected token in '.loc' directive");
2978 if (Name == "basic_block")
2979 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2980 else if (Name == "prologue_end")
2981 Flags |= DWARF2_FLAG_PROLOGUE_END;
2982 else if (Name == "epilogue_begin")
2983 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2984 else if (Name == "is_stmt") {
2985 SMLoc Loc = getTok().getLoc();
2986 const MCExpr *Value;
2987 if (getParser().ParseExpression(Value))
2989 // The expression must be the constant 0 or 1.
2990 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2991 int Value = MCE->getValue();
2993 Flags &= ~DWARF2_FLAG_IS_STMT;
2994 else if (Value == 1)
2995 Flags |= DWARF2_FLAG_IS_STMT;
2997 return Error(Loc, "is_stmt value not 0 or 1");
3000 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3003 else if (Name == "isa") {
3004 SMLoc Loc = getTok().getLoc();
3005 const MCExpr *Value;
3006 if (getParser().ParseExpression(Value))
3008 // The expression must be a constant greater or equal to 0.
3009 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3010 int Value = MCE->getValue();
3012 return Error(Loc, "isa number less than zero");
3016 return Error(Loc, "isa number not a constant value");
3019 else if (Name == "discriminator") {
3020 if (getParser().ParseAbsoluteExpression(Discriminator))
3024 return Error(Loc, "unknown sub-directive in '.loc' directive");
3027 if (getLexer().is(AsmToken::EndOfStatement))
3032 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3033 Isa, Discriminator, StringRef());
3038 /// ParseDirectiveStabs
3039 /// ::= .stabs string, number, number, number
3040 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
3041 SMLoc DirectiveLoc) {
3042 return TokError("unsupported directive '" + Directive + "'");
3045 /// ParseDirectiveCFISections
3046 /// ::= .cfi_sections section [, section]
3047 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
3048 SMLoc DirectiveLoc) {
3053 if (getParser().ParseIdentifier(Name))
3054 return TokError("Expected an identifier");
3056 if (Name == ".eh_frame")
3058 else if (Name == ".debug_frame")
3061 if (getLexer().is(AsmToken::Comma)) {
3064 if (getParser().ParseIdentifier(Name))
3065 return TokError("Expected an identifier");
3067 if (Name == ".eh_frame")
3069 else if (Name == ".debug_frame")
3073 getStreamer().EmitCFISections(EH, Debug);
3078 /// ParseDirectiveCFIStartProc
3079 /// ::= .cfi_startproc
3080 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
3081 SMLoc DirectiveLoc) {
3082 getStreamer().EmitCFIStartProc();
3086 /// ParseDirectiveCFIEndProc
3087 /// ::= .cfi_endproc
3088 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
3089 getStreamer().EmitCFIEndProc();
3093 /// ParseRegisterOrRegisterNumber - parse register name or number.
3094 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3095 SMLoc DirectiveLoc) {
3098 if (getLexer().isNot(AsmToken::Integer)) {
3099 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3102 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
3104 return getParser().ParseAbsoluteExpression(Register);
3109 /// ParseDirectiveCFIDefCfa
3110 /// ::= .cfi_def_cfa register, offset
3111 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3112 SMLoc DirectiveLoc) {
3113 int64_t Register = 0;
3114 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3117 if (getLexer().isNot(AsmToken::Comma))
3118 return TokError("unexpected token in directive");
3122 if (getParser().ParseAbsoluteExpression(Offset))
3125 getStreamer().EmitCFIDefCfa(Register, Offset);
3129 /// ParseDirectiveCFIDefCfaOffset
3130 /// ::= .cfi_def_cfa_offset offset
3131 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3132 SMLoc DirectiveLoc) {
3134 if (getParser().ParseAbsoluteExpression(Offset))
3137 getStreamer().EmitCFIDefCfaOffset(Offset);
3141 /// ParseDirectiveCFIAdjustCfaOffset
3142 /// ::= .cfi_adjust_cfa_offset adjustment
3143 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3144 SMLoc DirectiveLoc) {
3145 int64_t Adjustment = 0;
3146 if (getParser().ParseAbsoluteExpression(Adjustment))
3149 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3153 /// ParseDirectiveCFIDefCfaRegister
3154 /// ::= .cfi_def_cfa_register register
3155 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3156 SMLoc DirectiveLoc) {
3157 int64_t Register = 0;
3158 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3161 getStreamer().EmitCFIDefCfaRegister(Register);
3165 /// ParseDirectiveCFIOffset
3166 /// ::= .cfi_offset register, offset
3167 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3168 int64_t Register = 0;
3171 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3174 if (getLexer().isNot(AsmToken::Comma))
3175 return TokError("unexpected token in directive");
3178 if (getParser().ParseAbsoluteExpression(Offset))
3181 getStreamer().EmitCFIOffset(Register, Offset);
3185 /// ParseDirectiveCFIRelOffset
3186 /// ::= .cfi_rel_offset register, offset
3187 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3188 SMLoc DirectiveLoc) {
3189 int64_t Register = 0;
3191 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3194 if (getLexer().isNot(AsmToken::Comma))
3195 return TokError("unexpected token in directive");
3199 if (getParser().ParseAbsoluteExpression(Offset))
3202 getStreamer().EmitCFIRelOffset(Register, Offset);
3206 static bool isValidEncoding(int64_t Encoding) {
3207 if (Encoding & ~0xff)
3210 if (Encoding == dwarf::DW_EH_PE_omit)
3213 const unsigned Format = Encoding & 0xf;
3214 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3215 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3216 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3217 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3220 const unsigned Application = Encoding & 0x70;
3221 if (Application != dwarf::DW_EH_PE_absptr &&
3222 Application != dwarf::DW_EH_PE_pcrel)
3228 /// ParseDirectiveCFIPersonalityOrLsda
3229 /// ::= .cfi_personality encoding, [symbol_name]
3230 /// ::= .cfi_lsda encoding, [symbol_name]
3231 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
3232 SMLoc DirectiveLoc) {
3233 int64_t Encoding = 0;
3234 if (getParser().ParseAbsoluteExpression(Encoding))
3236 if (Encoding == dwarf::DW_EH_PE_omit)
3239 if (!isValidEncoding(Encoding))
3240 return TokError("unsupported encoding.");
3242 if (getLexer().isNot(AsmToken::Comma))
3243 return TokError("unexpected token in directive");
3247 if (getParser().ParseIdentifier(Name))
3248 return TokError("expected identifier in directive");
3250 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3252 if (IDVal == ".cfi_personality")
3253 getStreamer().EmitCFIPersonality(Sym, Encoding);
3255 assert(IDVal == ".cfi_lsda");
3256 getStreamer().EmitCFILsda(Sym, Encoding);
3261 /// ParseDirectiveCFIRememberState
3262 /// ::= .cfi_remember_state
3263 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3264 SMLoc DirectiveLoc) {
3265 getStreamer().EmitCFIRememberState();
3269 /// ParseDirectiveCFIRestoreState
3270 /// ::= .cfi_remember_state
3271 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3272 SMLoc DirectiveLoc) {
3273 getStreamer().EmitCFIRestoreState();
3277 /// ParseDirectiveCFISameValue
3278 /// ::= .cfi_same_value register
3279 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3280 SMLoc DirectiveLoc) {
3281 int64_t Register = 0;
3283 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3286 getStreamer().EmitCFISameValue(Register);
3291 /// ParseDirectiveCFIRestore
3292 /// ::= .cfi_restore register
3293 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
3294 SMLoc DirectiveLoc) {
3295 int64_t Register = 0;
3296 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3299 getStreamer().EmitCFIRestore(Register);
3304 /// ParseDirectiveCFIEscape
3305 /// ::= .cfi_escape expression[,...]
3306 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3307 SMLoc DirectiveLoc) {
3310 if (getParser().ParseAbsoluteExpression(CurrValue))
3313 Values.push_back((uint8_t)CurrValue);
3315 while (getLexer().is(AsmToken::Comma)) {
3318 if (getParser().ParseAbsoluteExpression(CurrValue))
3321 Values.push_back((uint8_t)CurrValue);
3324 getStreamer().EmitCFIEscape(Values);
3328 /// ParseDirectiveCFISignalFrame
3329 /// ::= .cfi_signal_frame
3330 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3331 SMLoc DirectiveLoc) {
3332 if (getLexer().isNot(AsmToken::EndOfStatement))
3333 return Error(getLexer().getLoc(),
3334 "unexpected token in '" + Directive + "' directive");
3336 getStreamer().EmitCFISignalFrame();
3341 /// ParseDirectiveCFIUndefined
3342 /// ::= .cfi_undefined register
3343 bool GenericAsmParser::ParseDirectiveCFIUndefined(StringRef Directive,
3344 SMLoc DirectiveLoc) {
3345 int64_t Register = 0;
3347 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3350 getStreamer().EmitCFIUndefined(Register);
3355 /// ParseDirectiveCFIRegister
3356 /// ::= .cfi_register register, register
3357 bool GenericAsmParser::ParseDirectiveCFIRegister(StringRef Directive,
3358 SMLoc DirectiveLoc) {
3359 int64_t Register1 = 0;
3361 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3364 if (getLexer().isNot(AsmToken::Comma))
3365 return TokError("unexpected token in directive");
3368 int64_t Register2 = 0;
3370 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3373 getStreamer().EmitCFIRegister(Register1, Register2);
3378 /// ParseDirectiveMacrosOnOff
3381 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3382 SMLoc DirectiveLoc) {
3383 if (getLexer().isNot(AsmToken::EndOfStatement))
3384 return Error(getLexer().getLoc(),
3385 "unexpected token in '" + Directive + "' directive");
3387 getParser().MacrosEnabled = Directive == ".macros_on";
3392 /// ParseDirectiveMacro
3393 /// ::= .macro name [parameters]
3394 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3395 SMLoc DirectiveLoc) {
3397 if (getParser().ParseIdentifier(Name))
3398 return TokError("expected identifier in '.macro' directive");
3400 MacroParameters Parameters;
3401 // Argument delimiter is initially unknown. It will be set by
3402 // ParseMacroArgument()
3403 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3404 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3406 MacroParameter Parameter;
3407 if (getParser().ParseIdentifier(Parameter.first))
3408 return TokError("expected identifier in '.macro' directive");
3410 if (getLexer().is(AsmToken::Equal)) {
3412 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3416 Parameters.push_back(Parameter);
3418 if (getLexer().is(AsmToken::Comma))
3420 else if (getLexer().is(AsmToken::EndOfStatement))
3425 // Eat the end of statement.
3428 AsmToken EndToken, StartToken = getTok();
3430 // Lex the macro definition.
3432 // Check whether we have reached the end of the file.
3433 if (getLexer().is(AsmToken::Eof))
3434 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3436 // Otherwise, check whether we have reach the .endmacro.
3437 if (getLexer().is(AsmToken::Identifier) &&
3438 (getTok().getIdentifier() == ".endm" ||
3439 getTok().getIdentifier() == ".endmacro")) {
3440 EndToken = getTok();
3442 if (getLexer().isNot(AsmToken::EndOfStatement))
3443 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3448 // Otherwise, scan til the end of the statement.
3449 getParser().EatToEndOfStatement();
3452 if (getParser().MacroMap.lookup(Name)) {
3453 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3456 const char *BodyStart = StartToken.getLoc().getPointer();
3457 const char *BodyEnd = EndToken.getLoc().getPointer();
3458 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3459 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3463 /// ParseDirectiveEndMacro
3466 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3467 SMLoc DirectiveLoc) {
3468 if (getLexer().isNot(AsmToken::EndOfStatement))
3469 return TokError("unexpected token in '" + Directive + "' directive");
3471 // If we are inside a macro instantiation, terminate the current
3473 if (!getParser().ActiveMacros.empty()) {
3474 getParser().HandleMacroExit();
3478 // Otherwise, this .endmacro is a stray entry in the file; well formed
3479 // .endmacro directives are handled during the macro definition parsing.
3480 return TokError("unexpected '" + Directive + "' in file, "
3481 "no current macro definition");
3484 /// ParseDirectivePurgeMacro
3486 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3487 SMLoc DirectiveLoc) {
3489 if (getParser().ParseIdentifier(Name))
3490 return TokError("expected identifier in '.purgem' directive");
3492 if (getLexer().isNot(AsmToken::EndOfStatement))
3493 return TokError("unexpected token in '.purgem' directive");
3495 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3496 if (I == getParser().MacroMap.end())
3497 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3499 // Undefine the macro.
3500 delete I->getValue();
3501 getParser().MacroMap.erase(I);
3505 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3506 getParser().CheckForValidSection();
3508 const MCExpr *Value;
3510 if (getParser().ParseExpression(Value))
3513 if (getLexer().isNot(AsmToken::EndOfStatement))
3514 return TokError("unexpected token in directive");
3516 if (DirName[1] == 's')
3517 getStreamer().EmitSLEB128Value(Value);
3519 getStreamer().EmitULEB128Value(Value);
3524 Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3525 AsmToken EndToken, StartToken = getTok();
3527 unsigned NestLevel = 0;
3529 // Check whether we have reached the end of the file.
3530 if (getLexer().is(AsmToken::Eof)) {
3531 Error(DirectiveLoc, "no matching '.endr' in definition");
3535 if (Lexer.is(AsmToken::Identifier) &&
3536 (getTok().getIdentifier() == ".rept")) {
3540 // Otherwise, check whether we have reached the .endr.
3541 if (Lexer.is(AsmToken::Identifier) &&
3542 getTok().getIdentifier() == ".endr") {
3543 if (NestLevel == 0) {
3544 EndToken = getTok();
3546 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3547 TokError("unexpected token in '.endr' directive");
3555 // Otherwise, scan till the end of the statement.
3556 EatToEndOfStatement();
3559 const char *BodyStart = StartToken.getLoc().getPointer();
3560 const char *BodyEnd = EndToken.getLoc().getPointer();
3561 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3563 // We Are Anonymous.
3565 MacroParameters Parameters;
3566 return new Macro(Name, Body, Parameters);
3569 void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3570 raw_svector_ostream &OS) {
3573 MemoryBuffer *Instantiation =
3574 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3576 // Create the macro instantiation object and add to the current macro
3577 // instantiation stack.
3578 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3582 ActiveMacros.push_back(MI);
3584 // Jump to the macro instantiation and prime the lexer.
3585 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3586 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3590 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3592 if (ParseAbsoluteExpression(Count))
3593 return TokError("unexpected token in '.rept' directive");
3596 return TokError("Count is negative");
3598 if (Lexer.isNot(AsmToken::EndOfStatement))
3599 return TokError("unexpected token in '.rept' directive");
3601 // Eat the end of statement.
3604 // Lex the rept definition.
3605 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3609 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3610 // to hold the macro body with substitutions.
3611 SmallString<256> Buf;
3612 MacroParameters Parameters;
3614 raw_svector_ostream OS(Buf);
3616 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3619 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3624 /// ParseDirectiveIrp
3625 /// ::= .irp symbol,values
3626 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3627 MacroParameters Parameters;
3628 MacroParameter Parameter;
3630 if (ParseIdentifier(Parameter.first))
3631 return TokError("expected identifier in '.irp' directive");
3633 Parameters.push_back(Parameter);
3635 if (Lexer.isNot(AsmToken::Comma))
3636 return TokError("expected comma in '.irp' directive");
3641 if (ParseMacroArguments(0, A))
3644 // Eat the end of statement.
3647 // Lex the irp definition.
3648 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3652 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3653 // to hold the macro body with substitutions.
3654 SmallString<256> Buf;
3655 raw_svector_ostream OS(Buf);
3657 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3658 MacroArguments Args;
3661 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3665 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3670 /// ParseDirectiveIrpc
3671 /// ::= .irpc symbol,values
3672 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3673 MacroParameters Parameters;
3674 MacroParameter Parameter;
3676 if (ParseIdentifier(Parameter.first))
3677 return TokError("expected identifier in '.irpc' directive");
3679 Parameters.push_back(Parameter);
3681 if (Lexer.isNot(AsmToken::Comma))
3682 return TokError("expected comma in '.irpc' directive");
3687 if (ParseMacroArguments(0, A))
3690 if (A.size() != 1 || A.front().size() != 1)
3691 return TokError("unexpected token in '.irpc' directive");
3693 // Eat the end of statement.
3696 // Lex the irpc definition.
3697 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3701 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3702 // to hold the macro body with substitutions.
3703 SmallString<256> Buf;
3704 raw_svector_ostream OS(Buf);
3706 StringRef Values = A.front().front().getString();
3707 std::size_t I, End = Values.size();
3708 for (I = 0; I < End; ++I) {
3710 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3712 MacroArguments Args;
3713 Args.push_back(Arg);
3715 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3719 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3724 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3725 if (ActiveMacros.empty())
3726 return TokError("unmatched '.endr' directive");
3728 // The only .repl that should get here are the ones created by
3729 // InstantiateMacroLikeBody.
3730 assert(getLexer().is(AsmToken::EndOfStatement));
3736 bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3737 const MCExpr *Value;
3738 SMLoc ExprLoc = getLexer().getLoc();
3739 if (ParseExpression(Value))
3741 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3743 return Error(ExprLoc, "unexpected expression in _emit");
3744 uint64_t IntValue = MCE->getValue();
3745 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3746 return Error(ExprLoc, "literal value out of range for directive");
3748 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3752 bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3753 unsigned &NumOutputs, unsigned &NumInputs,
3754 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
3755 SmallVectorImpl<std::string> &Constraints,
3756 SmallVectorImpl<std::string> &Clobbers,
3757 const MCInstrInfo *MII,
3758 const MCInstPrinter *IP,
3759 MCAsmParserSemaCallback &SI) {
3760 SmallVector<void *, 4> InputDecls;
3761 SmallVector<void *, 4> OutputDecls;
3762 SmallVector<bool, 4> InputDeclsOffsetOf;
3763 SmallVector<bool, 4> OutputDeclsOffsetOf;
3764 SmallVector<std::string, 4> InputConstraints;
3765 SmallVector<std::string, 4> OutputConstraints;
3766 std::set<std::string> ClobberRegs;
3768 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
3773 // While we have input, parse each statement.
3774 unsigned InputIdx = 0;
3775 unsigned OutputIdx = 0;
3776 while (getLexer().isNot(AsmToken::Eof)) {
3777 ParseStatementInfo Info(&AsmStrRewrites);
3778 if (ParseStatement(Info))
3781 if (Info.ParseError)
3784 if (Info.Opcode != ~0U) {
3785 const MCInstrDesc &Desc = MII->get(Info.Opcode);
3787 // Build the list of clobbers, outputs and inputs.
3788 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3789 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
3792 if (Operand->isImm()) {
3793 if (Operand->needAsmRewrite())
3794 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3795 Operand->getStartLoc()));
3799 // Register operand.
3800 if (Operand->isReg() && !Operand->isOffsetOf()) {
3801 unsigned NumDefs = Desc.getNumDefs();
3803 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3805 raw_string_ostream OS(Reg);
3806 IP->printRegName(OS, Operand->getReg());
3807 ClobberRegs.insert(StringRef(OS.str()));
3812 // Expr/Input or Output.
3814 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3817 bool isOutput = (i == 1) && Desc.mayStore();
3818 if (!Operand->isOffsetOf() && Operand->needSizeDirective())
3819 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
3820 Operand->getStartLoc(),
3822 Operand->getMemSize()));
3824 std::string Constraint = "=";
3826 OutputDecls.push_back(OpDecl);
3827 OutputDeclsOffsetOf.push_back(Operand->isOffsetOf());
3828 Constraint += Operand->getConstraint().str();
3829 OutputConstraints.push_back(Constraint);
3830 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
3831 Operand->getStartLoc(),
3832 Operand->getNameLen()));
3834 InputDecls.push_back(OpDecl);
3835 InputDeclsOffsetOf.push_back(Operand->isOffsetOf());
3836 InputConstraints.push_back(Operand->getConstraint().str());
3837 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
3838 Operand->getStartLoc(),
3839 Operand->getNameLen()));
3846 // Set the number of Outputs and Inputs.
3847 NumOutputs = OutputDecls.size();
3848 NumInputs = InputDecls.size();
3850 // Set the unique clobbers.
3851 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3852 E = ClobberRegs.end(); I != E; ++I)
3853 Clobbers.push_back(*I);
3855 // Merge the various outputs and inputs. Output are expected first.
3856 if (NumOutputs || NumInputs) {
3857 unsigned NumExprs = NumOutputs + NumInputs;
3858 OpDecls.resize(NumExprs);
3859 Constraints.resize(NumExprs);
3860 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3861 // constraint for offsetof. This needs to be cleaned up!
3862 for (unsigned i = 0; i < NumOutputs; ++i) {
3863 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsOffsetOf[i]);
3864 Constraints[i] = OutputDeclsOffsetOf[i] ? "=r" : OutputConstraints[i];
3866 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
3867 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsOffsetOf[i]);
3868 Constraints[j] = InputDeclsOffsetOf[i] ? "r" : InputConstraints[i];
3872 // Build the IR assembly string.
3873 std::string AsmStringIR;
3874 AsmRewriteKind PrevKind = AOK_Imm;
3875 raw_string_ostream OS(AsmStringIR);
3876 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
3877 for (SmallVectorImpl<struct AsmRewrite>::iterator
3878 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3879 const char *Loc = (*I).Loc.getPointer();
3881 AsmRewriteKind Kind = (*I).Kind;
3883 // Emit everything up to the immediate/expression. If the previous rewrite
3884 // was a size directive, then this has already been done.
3885 if (PrevKind != AOK_SizeDirective)
3886 OS << StringRef(Start, Loc - Start);
3889 // Skip the original expression.
3890 if (Kind == AOK_Skip) {
3891 Start = Loc + (*I).Len;
3895 // Rewrite expressions in $N notation.
3913 case AOK_SizeDirective:
3916 case 8: OS << "byte ptr "; break;
3917 case 16: OS << "word ptr "; break;
3918 case 32: OS << "dword ptr "; break;
3919 case 64: OS << "qword ptr "; break;
3920 case 80: OS << "xword ptr "; break;
3921 case 128: OS << "xmmword ptr "; break;
3922 case 256: OS << "ymmword ptr "; break;
3928 case AOK_DotOperator:
3933 // Skip the original expression.
3934 if (Kind != AOK_SizeDirective)
3935 Start = Loc + (*I).Len;
3938 // Emit the remainder of the asm string.
3939 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3940 if (Start != AsmEnd)
3941 OS << StringRef(Start, AsmEnd - Start);
3943 AsmString = OS.str();
3947 /// \brief Create an MCAsmParser instance.
3948 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3949 MCContext &C, MCStreamer &Out,
3950 const MCAsmInfo &MAI) {
3951 return new AsmParser(SM, C, Out, MAI);