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() {}
54 /// \brief Helper class for storing information about an active macro
56 struct MacroInstantiation {
57 /// The macro being instantiated.
58 const MCAsmMacro *TheMacro;
60 /// The macro instantiation with substitutions.
61 MemoryBuffer *Instantiation;
63 /// The location of the instantiation.
64 SMLoc InstantiationLoc;
66 /// The buffer where parsing should resume upon instantiation completion.
69 /// The location where parsing should resume upon instantiation completion.
73 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
78 struct ParseStatementInfo {
79 /// ParsedOperands - The parsed operands from the last parsed statement.
80 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
82 /// Opcode - The opcode from the last parsed instruction.
85 /// Error - Was there an error parsing the inline assembly?
88 SmallVectorImpl<AsmRewrite> *AsmRewrites;
90 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
91 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
92 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
94 ~ParseStatementInfo() {
95 // Free any parsed operands.
96 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
97 delete ParsedOperands[i];
98 ParsedOperands.clear();
102 /// \brief The concrete assembly parser instance.
103 class AsmParser : public MCAsmParser {
104 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
105 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
110 const MCAsmInfo &MAI;
112 SourceMgr::DiagHandlerTy SavedDiagHandler;
113 void *SavedDiagContext;
114 MCAsmParserExtension *GenericParser;
115 MCAsmParserExtension *PlatformParser;
117 /// This is the current buffer index we're lexing from as managed by the
118 /// SourceMgr object.
121 AsmCond TheCondState;
122 std::vector<AsmCond> TheCondStack;
124 /// DirectiveMap - This is a table handlers for directives. Each handler is
125 /// invoked after the directive identifier is read and is responsible for
126 /// parsing and validating the rest of the directive. The handler is passed
127 /// in the directive name and the location of the directive keyword.
128 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
130 /// MacroMap - Map of currently defined macros.
131 StringMap<MCAsmMacro*> MacroMap;
133 /// ActiveMacros - Stack of active macro instantiations.
134 std::vector<MacroInstantiation*> ActiveMacros;
136 /// Boolean tracking whether macro substitution is enabled.
137 unsigned MacrosEnabledFlag : 1;
139 /// Flag tracking whether any errors have been encountered.
140 unsigned HadError : 1;
142 /// The values from the last parsed cpp hash file line comment if any.
143 StringRef CppHashFilename;
144 int64_t CppHashLineNumber;
148 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
149 unsigned AssemblerDialect;
151 /// IsDarwin - is Darwin compatibility enabled?
154 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
155 bool ParsingInlineAsm;
158 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
159 const MCAsmInfo &MAI);
160 virtual ~AsmParser();
162 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
164 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
166 DirectiveHandler Handler) {
167 DirectiveMap[Directive] = std::make_pair(Object, Handler);
171 /// @name MCAsmParser Interface
174 virtual SourceMgr &getSourceManager() { return SrcMgr; }
175 virtual MCAsmLexer &getLexer() { return Lexer; }
176 virtual MCContext &getContext() { return Ctx; }
177 virtual MCStreamer &getStreamer() { return Out; }
178 virtual unsigned getAssemblerDialect() {
179 if (AssemblerDialect == ~0U)
180 return MAI.getAssemblerDialect();
182 return AssemblerDialect;
184 virtual void setAssemblerDialect(unsigned i) {
185 AssemblerDialect = i;
188 virtual bool Warning(SMLoc L, const Twine &Msg,
189 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
190 virtual bool Error(SMLoc L, const Twine &Msg,
191 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
193 virtual const AsmToken &Lex();
195 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
196 bool isParsingInlineAsm() { return ParsingInlineAsm; }
198 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
199 unsigned &NumOutputs, unsigned &NumInputs,
200 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
201 SmallVectorImpl<std::string> &Constraints,
202 SmallVectorImpl<std::string> &Clobbers,
203 const MCInstrInfo *MII,
204 const MCInstPrinter *IP,
205 MCAsmParserSemaCallback &SI);
207 bool ParseExpression(const MCExpr *&Res);
208 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
209 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
210 virtual bool ParseAbsoluteExpression(int64_t &Res);
212 bool ParseMacroArgument(MCAsmMacroArgument &MA,
213 AsmToken::TokenKind &ArgumentDelimiter);
215 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
216 /// and set \p Res to the identifier contents.
217 virtual bool ParseIdentifier(StringRef &Res);
218 virtual void EatToEndOfStatement();
220 virtual bool MacrosEnabled() {return MacrosEnabledFlag;}
221 virtual void SetMacrosEnabled(bool flag) {MacrosEnabledFlag = flag;}
223 virtual const MCAsmMacro* LookupMacro(StringRef Name);
224 virtual void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
225 virtual void UndefineMacro(StringRef Name);
227 virtual bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
228 virtual bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
229 void HandleMacroExit();
231 virtual void CheckForValidSection();
236 bool ParseStatement(ParseStatementInfo &Info);
237 void EatToEndOfLine();
238 bool ParseCppHashLineFilenameComment(const SMLoc &L);
240 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
241 const MCAsmMacroParameters &Parameters,
242 const MCAsmMacroArguments &A,
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 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
268 /// \brief Parse up to the end of statement and a return the contents from the
269 /// current token until the end of the statement; the current token on exit
270 /// will be either the EndOfStatement or EOF.
271 virtual StringRef ParseStringToEndOfStatement();
273 /// \brief Parse until the end of a statement or a comma is encountered,
274 /// return the contents from the current token up to the end or comma.
275 StringRef ParseStringToComma();
277 bool ParseAssignment(StringRef Name, bool allow_redef,
278 bool NoDeadStrip = false);
280 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
281 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
282 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
283 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
285 // Directive Parsing.
288 DK_NO_DIRECTIVE, // Placeholder
289 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
290 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
291 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
292 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
293 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
294 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
295 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
296 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
297 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
298 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
299 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
300 DK_ELSEIF, DK_ELSE, DK_ENDIF
303 StringMap<DirectiveKind> DirectiveKindMapping;
305 // ".ascii", ".asciz", ".string"
306 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
307 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
308 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
309 bool ParseDirectiveFill(); // ".fill"
310 bool ParseDirectiveZero(); // ".zero"
311 // ".set", ".equ", ".equiv"
312 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
313 bool ParseDirectiveOrg(); // ".org"
314 // ".align{,32}", ".p2align{,w,l}"
315 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
317 // ".bundle_align_mode"
318 bool ParseDirectiveBundleAlignMode();
320 bool ParseDirectiveBundleLock();
322 bool ParseDirectiveBundleUnlock();
324 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
325 /// accepts a single symbol (which should be a label or an external).
326 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
328 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
330 bool ParseDirectiveAbort(); // ".abort"
331 bool ParseDirectiveInclude(); // ".include"
332 bool ParseDirectiveIncbin(); // ".incbin"
334 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
335 // ".ifb" or ".ifnb", depending on ExpectBlank.
336 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
337 // ".ifc" or ".ifnc", depending on ExpectEqual.
338 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
339 // ".ifdef" or ".ifndef", depending on expect_defined
340 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
341 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
342 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
343 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
345 /// ParseEscapedString - Parse the current token as a string which may include
346 /// escaped characters and return the string contents.
347 bool ParseEscapedString(std::string &Data);
349 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
350 MCSymbolRefExpr::VariantKind Variant);
352 // Macro-like directives
353 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
354 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
355 raw_svector_ostream &OS);
356 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
357 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
358 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
359 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
362 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
364 void initializeDirectiveKindMapping();
367 /// \brief Generic implementation of directive handling, etc. which is shared
368 /// (or the default, at least) for all assembler parsers.
369 class GenericAsmParser : public MCAsmParserExtension {
370 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
371 void AddDirectiveHandler(StringRef Directive) {
372 getParser().AddDirectiveHandler(this, Directive,
373 HandleDirective<GenericAsmParser, Handler>);
376 GenericAsmParser() {}
378 virtual void Initialize(MCAsmParser &Parser) {
379 // Call the base implementation.
380 this->MCAsmParserExtension::Initialize(Parser);
382 // Debugging directives.
383 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
384 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
385 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
386 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
388 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveSpace>(".space");
389 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveSpace>(".skip");
392 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
394 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
396 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
398 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
400 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
401 ".cfi_def_cfa_offset");
402 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
403 ".cfi_adjust_cfa_offset");
404 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
405 ".cfi_def_cfa_register");
406 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
408 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
411 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
413 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
415 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
417 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
419 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
421 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
423 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
425 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
427 &GenericAsmParser::ParseDirectiveCFIUndefined>(".cfi_undefined");
429 &GenericAsmParser::ParseDirectiveCFIRegister>(".cfi_register");
432 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
434 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
436 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
437 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
438 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
439 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
441 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
442 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
445 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
447 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
448 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
449 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
450 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
451 bool ParseDirectiveSpace(StringRef, SMLoc DirectiveLoc);
452 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
453 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
454 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
455 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
456 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
457 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
458 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
459 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
460 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
461 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
462 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
463 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
464 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
465 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
466 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
467 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
468 bool ParseDirectiveCFIUndefined(StringRef, SMLoc DirectiveLoc);
469 bool ParseDirectiveCFIRegister(StringRef, SMLoc DirectiveLoc);
471 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
472 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
473 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
474 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
476 bool ParseDirectiveLEB128(StringRef, SMLoc);
483 extern MCAsmParserExtension *createDarwinAsmParser();
484 extern MCAsmParserExtension *createELFAsmParser();
485 extern MCAsmParserExtension *createCOFFAsmParser();
489 enum { DEFAULT_ADDRSPACE = 0 };
491 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
492 MCStreamer &_Out, const MCAsmInfo &_MAI)
493 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
494 GenericParser(new GenericAsmParser), PlatformParser(0),
495 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
496 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
497 // Save the old handler.
498 SavedDiagHandler = SrcMgr.getDiagHandler();
499 SavedDiagContext = SrcMgr.getDiagContext();
500 // Set our own handler which calls the saved handler.
501 SrcMgr.setDiagHandler(DiagHandler, this);
502 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
504 // Initialize the generic parser.
505 GenericParser->Initialize(*this);
507 // Initialize the platform / file format parser.
509 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
511 if (_MAI.hasMicrosoftFastStdCallMangling()) {
512 PlatformParser = createCOFFAsmParser();
513 PlatformParser->Initialize(*this);
514 } else if (_MAI.hasSubsectionsViaSymbols()) {
515 PlatformParser = createDarwinAsmParser();
516 PlatformParser->Initialize(*this);
519 PlatformParser = createELFAsmParser();
520 PlatformParser->Initialize(*this);
523 initializeDirectiveKindMapping();
526 AsmParser::~AsmParser() {
527 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
529 // Destroy any macros.
530 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
531 ie = MacroMap.end(); it != ie; ++it)
532 delete it->getValue();
534 delete PlatformParser;
535 delete GenericParser;
538 void AsmParser::PrintMacroInstantiations() {
539 // Print the active macro instantiation stack.
540 for (std::vector<MacroInstantiation*>::const_reverse_iterator
541 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
542 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
543 "while in macro instantiation");
546 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
547 if (FatalAssemblerWarnings)
548 return Error(L, Msg, Ranges);
549 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
550 PrintMacroInstantiations();
554 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
556 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
557 PrintMacroInstantiations();
561 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
562 std::string IncludedFile;
563 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
569 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
574 /// Process the specified .incbin file by seaching for it in the include paths
575 /// then just emitting the byte contents of the file to the streamer. This
576 /// returns true on failure.
577 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
578 std::string IncludedFile;
579 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
583 // Pick up the bytes from the file and emit them.
584 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
589 void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
590 if (InBuffer != -1) {
591 CurBuffer = InBuffer;
593 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
595 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
598 const AsmToken &AsmParser::Lex() {
599 const AsmToken *tok = &Lexer.Lex();
601 if (tok->is(AsmToken::Eof)) {
602 // If this is the end of an included file, pop the parent file off the
604 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
605 if (ParentIncludeLoc != SMLoc()) {
606 JumpToLoc(ParentIncludeLoc);
611 if (tok->is(AsmToken::Error))
612 Error(Lexer.getErrLoc(), Lexer.getErr());
617 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
618 // Create the initial section, if requested.
619 if (!NoInitialTextSection)
626 AsmCond StartingCondState = TheCondState;
628 // If we are generating dwarf for assembly source files save the initial text
629 // section and generate a .file directive.
630 if (getContext().getGenDwarfForAssembly()) {
631 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
632 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
633 getStreamer().EmitLabel(SectionStartSym);
634 getContext().setGenDwarfSectionStartSym(SectionStartSym);
635 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
637 getContext().getMainFileName());
640 // While we have input, parse each statement.
641 while (Lexer.isNot(AsmToken::Eof)) {
642 ParseStatementInfo Info;
643 if (!ParseStatement(Info)) continue;
645 // We had an error, validate that one was emitted and recover by skipping to
647 assert(HadError && "Parse statement returned an error, but none emitted!");
648 EatToEndOfStatement();
651 if (TheCondState.TheCond != StartingCondState.TheCond ||
652 TheCondState.Ignore != StartingCondState.Ignore)
653 return TokError("unmatched .ifs or .elses");
655 // Check to see there are no empty DwarfFile slots.
656 const std::vector<MCDwarfFile *> &MCDwarfFiles =
657 getContext().getMCDwarfFiles();
658 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
659 if (!MCDwarfFiles[i])
660 TokError("unassigned file number: " + Twine(i) + " for .file directives");
663 // Check to see that all assembler local symbols were actually defined.
664 // Targets that don't do subsections via symbols may not want this, though,
665 // so conservatively exclude them. Only do this if we're finalizing, though,
666 // as otherwise we won't necessarilly have seen everything yet.
667 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
668 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
669 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
672 MCSymbol *Sym = i->getValue();
673 // Variable symbols may not be marked as defined, so check those
674 // explicitly. If we know it's a variable, we have a definition for
675 // the purposes of this check.
676 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
677 // FIXME: We would really like to refer back to where the symbol was
678 // first referenced for a source location. We need to add something
679 // to track that. Currently, we just point to the end of the file.
680 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
681 "assembler local symbol '" + Sym->getName() +
687 // Finalize the output stream if there are no errors and if the client wants
689 if (!HadError && !NoFinalize)
695 void AsmParser::CheckForValidSection() {
696 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
697 TokError("expected section directive before assembly directive");
698 Out.InitToTextSection();
702 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
703 void AsmParser::EatToEndOfStatement() {
704 while (Lexer.isNot(AsmToken::EndOfStatement) &&
705 Lexer.isNot(AsmToken::Eof))
709 if (Lexer.is(AsmToken::EndOfStatement))
713 StringRef AsmParser::ParseStringToEndOfStatement() {
714 const char *Start = getTok().getLoc().getPointer();
716 while (Lexer.isNot(AsmToken::EndOfStatement) &&
717 Lexer.isNot(AsmToken::Eof))
720 const char *End = getTok().getLoc().getPointer();
721 return StringRef(Start, End - Start);
724 StringRef AsmParser::ParseStringToComma() {
725 const char *Start = getTok().getLoc().getPointer();
727 while (Lexer.isNot(AsmToken::EndOfStatement) &&
728 Lexer.isNot(AsmToken::Comma) &&
729 Lexer.isNot(AsmToken::Eof))
732 const char *End = getTok().getLoc().getPointer();
733 return StringRef(Start, End - Start);
736 /// ParseParenExpr - Parse a paren expression and return it.
737 /// NOTE: This assumes the leading '(' has already been consumed.
739 /// parenexpr ::= expr)
741 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
742 if (ParseExpression(Res)) return true;
743 if (Lexer.isNot(AsmToken::RParen))
744 return TokError("expected ')' in parentheses expression");
745 EndLoc = Lexer.getTok().getEndLoc();
750 /// ParseBracketExpr - Parse a bracket expression and return it.
751 /// NOTE: This assumes the leading '[' has already been consumed.
753 /// bracketexpr ::= expr]
755 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
756 if (ParseExpression(Res)) return true;
757 if (Lexer.isNot(AsmToken::RBrac))
758 return TokError("expected ']' in brackets expression");
759 EndLoc = Lexer.getTok().getEndLoc();
764 /// ParsePrimaryExpr - Parse a primary expression and return it.
765 /// primaryexpr ::= (parenexpr
766 /// primaryexpr ::= symbol
767 /// primaryexpr ::= number
768 /// primaryexpr ::= '.'
769 /// primaryexpr ::= ~,+,- primaryexpr
770 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
771 switch (Lexer.getKind()) {
773 return TokError("unknown token in expression");
774 // If we have an error assume that we've already handled it.
775 case AsmToken::Error:
777 case AsmToken::Exclaim:
778 Lex(); // Eat the operator.
779 if (ParsePrimaryExpr(Res, EndLoc))
781 Res = MCUnaryExpr::CreateLNot(Res, getContext());
783 case AsmToken::Dollar:
784 case AsmToken::String:
785 case AsmToken::Identifier: {
786 StringRef Identifier;
787 if (ParseIdentifier(Identifier))
790 EndLoc = SMLoc::getFromPointer(Identifier.end());
792 // This is a symbol reference.
793 std::pair<StringRef, StringRef> Split = Identifier.split('@');
794 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
796 // Lookup the symbol variant if used.
797 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
798 if (Split.first.size() != Identifier.size()) {
799 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
800 if (Variant == MCSymbolRefExpr::VK_Invalid) {
801 Variant = MCSymbolRefExpr::VK_None;
802 return TokError("invalid variant '" + Split.second + "'");
806 // If this is an absolute variable reference, substitute it now to preserve
807 // semantics in the face of reassignment.
808 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
810 return Error(EndLoc, "unexpected modifier on variable reference");
812 Res = Sym->getVariableValue();
816 // Otherwise create a symbol ref.
817 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
820 case AsmToken::Integer: {
821 SMLoc Loc = getTok().getLoc();
822 int64_t IntVal = getTok().getIntVal();
823 Res = MCConstantExpr::Create(IntVal, getContext());
824 EndLoc = Lexer.getTok().getEndLoc();
826 // Look for 'b' or 'f' following an Integer as a directional label
827 if (Lexer.getKind() == AsmToken::Identifier) {
828 StringRef IDVal = getTok().getString();
829 if (IDVal == "f" || IDVal == "b"){
830 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
831 IDVal == "f" ? 1 : 0);
832 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
834 if (IDVal == "b" && Sym->isUndefined())
835 return Error(Loc, "invalid reference to undefined symbol");
836 EndLoc = Lexer.getTok().getEndLoc();
837 Lex(); // Eat identifier.
842 case AsmToken::Real: {
843 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
844 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
845 Res = MCConstantExpr::Create(IntVal, getContext());
846 EndLoc = Lexer.getTok().getEndLoc();
850 case AsmToken::Dot: {
851 // This is a '.' reference, which references the current PC. Emit a
852 // temporary label to the streamer and refer to it.
853 MCSymbol *Sym = Ctx.CreateTempSymbol();
855 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
856 EndLoc = Lexer.getTok().getEndLoc();
857 Lex(); // Eat identifier.
860 case AsmToken::LParen:
861 Lex(); // Eat the '('.
862 return ParseParenExpr(Res, EndLoc);
863 case AsmToken::LBrac:
864 if (!PlatformParser->HasBracketExpressions())
865 return TokError("brackets expression not supported on this target");
866 Lex(); // Eat the '['.
867 return ParseBracketExpr(Res, EndLoc);
868 case AsmToken::Minus:
869 Lex(); // Eat the operator.
870 if (ParsePrimaryExpr(Res, EndLoc))
872 Res = MCUnaryExpr::CreateMinus(Res, getContext());
875 Lex(); // Eat the operator.
876 if (ParsePrimaryExpr(Res, EndLoc))
878 Res = MCUnaryExpr::CreatePlus(Res, getContext());
880 case AsmToken::Tilde:
881 Lex(); // Eat the operator.
882 if (ParsePrimaryExpr(Res, EndLoc))
884 Res = MCUnaryExpr::CreateNot(Res, getContext());
889 bool AsmParser::ParseExpression(const MCExpr *&Res) {
891 return ParseExpression(Res, EndLoc);
895 AsmParser::ApplyModifierToExpr(const MCExpr *E,
896 MCSymbolRefExpr::VariantKind Variant) {
897 // Recurse over the given expression, rebuilding it to apply the given variant
898 // if there is exactly one symbol.
899 switch (E->getKind()) {
901 case MCExpr::Constant:
904 case MCExpr::SymbolRef: {
905 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
907 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
908 TokError("invalid variant on expression '" +
909 getTok().getIdentifier() + "' (already modified)");
913 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
916 case MCExpr::Unary: {
917 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
918 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
921 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
924 case MCExpr::Binary: {
925 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
926 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
927 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
932 if (!LHS) LHS = BE->getLHS();
933 if (!RHS) RHS = BE->getRHS();
935 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
939 llvm_unreachable("Invalid expression kind!");
942 /// ParseExpression - Parse an expression and return it.
944 /// expr ::= expr &&,|| expr -> lowest.
945 /// expr ::= expr |,^,&,! expr
946 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
947 /// expr ::= expr <<,>> expr
948 /// expr ::= expr +,- expr
949 /// expr ::= expr *,/,% expr -> highest.
950 /// expr ::= primaryexpr
952 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
953 // Parse the expression.
955 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
958 // As a special case, we support 'a op b @ modifier' by rewriting the
959 // expression to include the modifier. This is inefficient, but in general we
960 // expect users to use 'a@modifier op b'.
961 if (Lexer.getKind() == AsmToken::At) {
964 if (Lexer.isNot(AsmToken::Identifier))
965 return TokError("unexpected symbol modifier following '@'");
967 MCSymbolRefExpr::VariantKind Variant =
968 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
969 if (Variant == MCSymbolRefExpr::VK_Invalid)
970 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
972 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
974 return TokError("invalid modifier '" + getTok().getIdentifier() +
975 "' (no symbols present)");
982 // Try to constant fold it up front, if possible.
984 if (Res->EvaluateAsAbsolute(Value))
985 Res = MCConstantExpr::Create(Value, getContext());
990 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
992 return ParseParenExpr(Res, EndLoc) ||
993 ParseBinOpRHS(1, Res, EndLoc);
996 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
999 SMLoc StartLoc = Lexer.getLoc();
1000 if (ParseExpression(Expr))
1003 if (!Expr->EvaluateAsAbsolute(Res))
1004 return Error(StartLoc, "expected absolute expression");
1009 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1010 MCBinaryExpr::Opcode &Kind) {
1013 return 0; // not a binop.
1015 // Lowest Precedence: &&, ||
1016 case AsmToken::AmpAmp:
1017 Kind = MCBinaryExpr::LAnd;
1019 case AsmToken::PipePipe:
1020 Kind = MCBinaryExpr::LOr;
1024 // Low Precedence: |, &, ^
1026 // FIXME: gas seems to support '!' as an infix operator?
1027 case AsmToken::Pipe:
1028 Kind = MCBinaryExpr::Or;
1030 case AsmToken::Caret:
1031 Kind = MCBinaryExpr::Xor;
1034 Kind = MCBinaryExpr::And;
1037 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1038 case AsmToken::EqualEqual:
1039 Kind = MCBinaryExpr::EQ;
1041 case AsmToken::ExclaimEqual:
1042 case AsmToken::LessGreater:
1043 Kind = MCBinaryExpr::NE;
1045 case AsmToken::Less:
1046 Kind = MCBinaryExpr::LT;
1048 case AsmToken::LessEqual:
1049 Kind = MCBinaryExpr::LTE;
1051 case AsmToken::Greater:
1052 Kind = MCBinaryExpr::GT;
1054 case AsmToken::GreaterEqual:
1055 Kind = MCBinaryExpr::GTE;
1058 // Intermediate Precedence: <<, >>
1059 case AsmToken::LessLess:
1060 Kind = MCBinaryExpr::Shl;
1062 case AsmToken::GreaterGreater:
1063 Kind = MCBinaryExpr::Shr;
1066 // High Intermediate Precedence: +, -
1067 case AsmToken::Plus:
1068 Kind = MCBinaryExpr::Add;
1070 case AsmToken::Minus:
1071 Kind = MCBinaryExpr::Sub;
1074 // Highest Precedence: *, /, %
1075 case AsmToken::Star:
1076 Kind = MCBinaryExpr::Mul;
1078 case AsmToken::Slash:
1079 Kind = MCBinaryExpr::Div;
1081 case AsmToken::Percent:
1082 Kind = MCBinaryExpr::Mod;
1088 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1089 /// Res contains the LHS of the expression on input.
1090 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1093 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1094 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1096 // If the next token is lower precedence than we are allowed to eat, return
1097 // successfully with what we ate already.
1098 if (TokPrec < Precedence)
1103 // Eat the next primary expression.
1105 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1107 // If BinOp binds less tightly with RHS than the operator after RHS, let
1108 // the pending operator take RHS as its LHS.
1109 MCBinaryExpr::Opcode Dummy;
1110 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1111 if (TokPrec < NextTokPrec) {
1112 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1115 // Merge LHS and RHS according to operator.
1116 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1121 /// ::= EndOfStatement
1122 /// ::= Label* Directive ...Operands... EndOfStatement
1123 /// ::= Label* Identifier OperandList* EndOfStatement
1124 bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
1125 if (Lexer.is(AsmToken::EndOfStatement)) {
1131 // Statements always start with an identifier or are a full line comment.
1132 AsmToken ID = getTok();
1133 SMLoc IDLoc = ID.getLoc();
1135 int64_t LocalLabelVal = -1;
1136 // A full line comment is a '#' as the first token.
1137 if (Lexer.is(AsmToken::Hash))
1138 return ParseCppHashLineFilenameComment(IDLoc);
1140 // Allow an integer followed by a ':' as a directional local label.
1141 if (Lexer.is(AsmToken::Integer)) {
1142 LocalLabelVal = getTok().getIntVal();
1143 if (LocalLabelVal < 0) {
1144 if (!TheCondState.Ignore)
1145 return TokError("unexpected token at start of statement");
1149 IDVal = getTok().getString();
1150 Lex(); // Consume the integer token to be used as an identifier token.
1151 if (Lexer.getKind() != AsmToken::Colon) {
1152 if (!TheCondState.Ignore)
1153 return TokError("unexpected token at start of statement");
1157 } else if (Lexer.is(AsmToken::Dot)) {
1158 // Treat '.' as a valid identifier in this context.
1162 } else if (ParseIdentifier(IDVal)) {
1163 if (!TheCondState.Ignore)
1164 return TokError("unexpected token at start of statement");
1168 // Handle conditional assembly here before checking for skipping. We
1169 // have to do this so that .endif isn't skipped in a ".if 0" block for
1171 StringMap<DirectiveKind>::const_iterator DirKindIt =
1172 DirectiveKindMapping.find(IDVal);
1173 DirectiveKind DirKind =
1174 (DirKindIt == DirectiveKindMapping.end()) ? DK_NO_DIRECTIVE :
1175 DirKindIt->getValue();
1180 return ParseDirectiveIf(IDLoc);
1182 return ParseDirectiveIfb(IDLoc, true);
1184 return ParseDirectiveIfb(IDLoc, false);
1186 return ParseDirectiveIfc(IDLoc, true);
1188 return ParseDirectiveIfc(IDLoc, false);
1190 return ParseDirectiveIfdef(IDLoc, true);
1193 return ParseDirectiveIfdef(IDLoc, false);
1195 return ParseDirectiveElseIf(IDLoc);
1197 return ParseDirectiveElse(IDLoc);
1199 return ParseDirectiveEndIf(IDLoc);
1202 // If we are in a ".if 0" block, ignore this statement.
1203 if (TheCondState.Ignore) {
1204 EatToEndOfStatement();
1208 // FIXME: Recurse on local labels?
1210 // See what kind of statement we have.
1211 switch (Lexer.getKind()) {
1212 case AsmToken::Colon: {
1213 CheckForValidSection();
1215 // identifier ':' -> Label.
1218 // Diagnose attempt to use '.' as a label.
1220 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1222 // Diagnose attempt to use a variable as a label.
1224 // FIXME: Diagnostics. Note the location of the definition as a label.
1225 // FIXME: This doesn't diagnose assignment to a symbol which has been
1226 // implicitly marked as external.
1228 if (LocalLabelVal == -1)
1229 Sym = getContext().GetOrCreateSymbol(IDVal);
1231 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1232 if (!Sym->isUndefined() || Sym->isVariable())
1233 return Error(IDLoc, "invalid symbol redefinition");
1236 if (!ParsingInlineAsm)
1239 // If we are generating dwarf for assembly source files then gather the
1240 // info to make a dwarf label entry for this label if needed.
1241 if (getContext().getGenDwarfForAssembly())
1242 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1245 // Consume any end of statement token, if present, to avoid spurious
1246 // AddBlankLine calls().
1247 if (Lexer.is(AsmToken::EndOfStatement)) {
1249 if (Lexer.is(AsmToken::Eof))
1256 case AsmToken::Equal:
1257 // identifier '=' ... -> assignment statement
1260 return ParseAssignment(IDVal, true);
1262 default: // Normal instruction or directive.
1266 // If macros are enabled, check to see if this is a macro instantiation.
1267 if (MacrosEnabled())
1268 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1269 return HandleMacroEntry(M, IDLoc);
1272 // Otherwise, we have a normal instruction or directive.
1273 if (IDVal[0] == '.' && IDVal != ".") {
1275 // Target hook for parsing target specific directives.
1276 if (!getTargetParser().ParseDirective(ID))
1284 return ParseDirectiveSet(IDVal, true);
1286 return ParseDirectiveSet(IDVal, false);
1288 return ParseDirectiveAscii(IDVal, false);
1291 return ParseDirectiveAscii(IDVal, true);
1293 return ParseDirectiveValue(1);
1297 return ParseDirectiveValue(2);
1301 return ParseDirectiveValue(4);
1304 return ParseDirectiveValue(8);
1307 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1309 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1311 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1312 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1315 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1316 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1319 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1321 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1323 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1325 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1327 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1329 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1331 return ParseDirectiveOrg();
1333 return ParseDirectiveFill();
1335 return ParseDirectiveZero();
1337 EatToEndOfStatement(); // .extern is the default, ignore it.
1341 return ParseDirectiveSymbolAttribute(MCSA_Global);
1342 case DK_INDIRECT_SYMBOL:
1343 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1344 case DK_LAZY_REFERENCE:
1345 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1346 case DK_NO_DEAD_STRIP:
1347 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1348 case DK_SYMBOL_RESOLVER:
1349 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1350 case DK_PRIVATE_EXTERN:
1351 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1353 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1354 case DK_WEAK_DEFINITION:
1355 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1356 case DK_WEAK_REFERENCE:
1357 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1358 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1359 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1362 return ParseDirectiveComm(/*IsLocal=*/false);
1364 return ParseDirectiveComm(/*IsLocal=*/true);
1366 return ParseDirectiveAbort();
1368 return ParseDirectiveInclude();
1370 return ParseDirectiveIncbin();
1373 return TokError(Twine(IDVal) + " not supported yet");
1375 return ParseDirectiveRept(IDLoc);
1377 return ParseDirectiveIrp(IDLoc);
1379 return ParseDirectiveIrpc(IDLoc);
1381 return ParseDirectiveEndr(IDLoc);
1382 case DK_BUNDLE_ALIGN_MODE:
1383 return ParseDirectiveBundleAlignMode();
1384 case DK_BUNDLE_LOCK:
1385 return ParseDirectiveBundleLock();
1386 case DK_BUNDLE_UNLOCK:
1387 return ParseDirectiveBundleUnlock();
1390 // Look up the handler in the extension handler table.
1391 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1392 DirectiveMap.lookup(IDVal);
1394 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1396 return Error(IDLoc, "unknown directive");
1400 if (ParsingInlineAsm && IDVal == "_emit")
1401 return ParseDirectiveEmit(IDLoc, Info);
1403 CheckForValidSection();
1405 // Canonicalize the opcode to lower case.
1406 SmallString<128> OpcodeStr;
1407 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1408 OpcodeStr.push_back(tolower(IDVal[i]));
1410 ParseInstructionInfo IInfo(Info.AsmRewrites);
1411 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1412 IDLoc,Info.ParsedOperands);
1413 Info.ParseError = HadError;
1415 // Dump the parsed representation, if requested.
1416 if (getShowParsedOperands()) {
1417 SmallString<256> Str;
1418 raw_svector_ostream OS(Str);
1419 OS << "parsed instruction: [";
1420 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1423 Info.ParsedOperands[i]->print(OS);
1427 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1430 // If we are generating dwarf for assembly source files and the current
1431 // section is the initial text section then generate a .loc directive for
1433 if (!HadError && getContext().getGenDwarfForAssembly() &&
1434 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
1436 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1438 // If we previously parsed a cpp hash file line comment then make sure the
1439 // current Dwarf File is for the CppHashFilename if not then emit the
1440 // Dwarf File table for it and adjust the line number for the .loc.
1441 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1442 getContext().getMCDwarfFiles();
1443 if (CppHashFilename.size() != 0) {
1444 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1446 getStreamer().EmitDwarfFileDirective(
1447 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1449 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
1450 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1453 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1454 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1455 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1459 // If parsing succeeded, match the instruction.
1462 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1463 Info.ParsedOperands,
1468 // Don't skip the rest of the line, the instruction parser is responsible for
1473 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1474 /// since they may not be able to be tokenized to get to the end of line token.
1475 void AsmParser::EatToEndOfLine() {
1476 if (!Lexer.is(AsmToken::EndOfStatement))
1477 Lexer.LexUntilEndOfLine();
1482 /// ParseCppHashLineFilenameComment as this:
1483 /// ::= # number "filename"
1484 /// or just as a full line comment if it doesn't have a number and a string.
1485 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1486 Lex(); // Eat the hash token.
1488 if (getLexer().isNot(AsmToken::Integer)) {
1489 // Consume the line since in cases it is not a well-formed line directive,
1490 // as if were simply a full line comment.
1495 int64_t LineNumber = getTok().getIntVal();
1498 if (getLexer().isNot(AsmToken::String)) {
1503 StringRef Filename = getTok().getString();
1504 // Get rid of the enclosing quotes.
1505 Filename = Filename.substr(1, Filename.size()-2);
1507 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1509 CppHashFilename = Filename;
1510 CppHashLineNumber = LineNumber;
1511 CppHashBuf = CurBuffer;
1513 // Ignore any trailing characters, they're just comment.
1518 /// DiagHandler - will use the last parsed cpp hash line filename comment
1519 /// for the Filename and LineNo if any in the diagnostic.
1520 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1521 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1522 raw_ostream &OS = errs();
1524 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1525 const SMLoc &DiagLoc = Diag.getLoc();
1526 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1527 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1529 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1530 // before printing the message.
1531 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1532 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1533 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1534 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1537 // If we have not parsed a cpp hash line filename comment or the source
1538 // manager changed or buffer changed (like in a nested include) then just
1539 // print the normal diagnostic using its Filename and LineNo.
1540 if (!Parser->CppHashLineNumber ||
1541 &DiagSrcMgr != &Parser->SrcMgr ||
1542 DiagBuf != CppHashBuf) {
1543 if (Parser->SavedDiagHandler)
1544 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1550 // Use the CppHashFilename and calculate a line number based on the
1551 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1553 const std::string Filename = Parser->CppHashFilename;
1555 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1556 int CppHashLocLineNo =
1557 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1558 int LineNo = Parser->CppHashLineNumber - 1 +
1559 (DiagLocLineNo - CppHashLocLineNo);
1561 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1562 Filename, LineNo, Diag.getColumnNo(),
1563 Diag.getKind(), Diag.getMessage(),
1564 Diag.getLineContents(), Diag.getRanges());
1566 if (Parser->SavedDiagHandler)
1567 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1569 NewDiag.print(0, OS);
1572 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1573 // difference being that that function accepts '@' as part of identifiers and
1574 // we can't do that. AsmLexer.cpp should probably be changed to handle
1575 // '@' as a special case when needed.
1576 static bool isIdentifierChar(char c) {
1577 return isalnum(c) || c == '_' || c == '$' || c == '.';
1580 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1581 const MCAsmMacroParameters &Parameters,
1582 const MCAsmMacroArguments &A,
1584 unsigned NParameters = Parameters.size();
1585 if (NParameters != 0 && NParameters != A.size())
1586 return Error(L, "Wrong number of arguments");
1588 // A macro without parameters is handled differently on Darwin:
1589 // gas accepts no arguments and does no substitutions
1590 while (!Body.empty()) {
1591 // Scan for the next substitution.
1592 std::size_t End = Body.size(), Pos = 0;
1593 for (; Pos != End; ++Pos) {
1594 // Check for a substitution or escape.
1596 // This macro has no parameters, look for $0, $1, etc.
1597 if (Body[Pos] != '$' || Pos + 1 == End)
1600 char Next = Body[Pos + 1];
1601 if (Next == '$' || Next == 'n' || isdigit(Next))
1604 // This macro has parameters, look for \foo, \bar, etc.
1605 if (Body[Pos] == '\\' && Pos + 1 != End)
1611 OS << Body.slice(0, Pos);
1613 // Check if we reached the end.
1618 switch (Body[Pos+1]) {
1624 // $n => number of arguments
1629 // $[0-9] => argument
1631 // Missing arguments are ignored.
1632 unsigned Index = Body[Pos+1] - '0';
1633 if (Index >= A.size())
1636 // Otherwise substitute with the token values, with spaces eliminated.
1637 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1638 ie = A[Index].end(); it != ie; ++it)
1639 OS << it->getString();
1645 unsigned I = Pos + 1;
1646 while (isIdentifierChar(Body[I]) && I + 1 != End)
1649 const char *Begin = Body.data() + Pos +1;
1650 StringRef Argument(Begin, I - (Pos +1));
1652 for (; Index < NParameters; ++Index)
1653 if (Parameters[Index].first == Argument)
1656 if (Index == NParameters) {
1657 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1660 OS << '\\' << Argument;
1664 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1665 ie = A[Index].end(); it != ie; ++it)
1666 if (it->getKind() == AsmToken::String)
1667 OS << it->getStringContents();
1669 OS << it->getString();
1671 Pos += 1 + Argument.size();
1674 // Update the scan point.
1675 Body = Body.substr(Pos);
1681 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
1684 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1689 static bool IsOperator(AsmToken::TokenKind kind)
1695 case AsmToken::Plus:
1696 case AsmToken::Minus:
1697 case AsmToken::Tilde:
1698 case AsmToken::Slash:
1699 case AsmToken::Star:
1701 case AsmToken::Equal:
1702 case AsmToken::EqualEqual:
1703 case AsmToken::Pipe:
1704 case AsmToken::PipePipe:
1705 case AsmToken::Caret:
1707 case AsmToken::AmpAmp:
1708 case AsmToken::Exclaim:
1709 case AsmToken::ExclaimEqual:
1710 case AsmToken::Percent:
1711 case AsmToken::Less:
1712 case AsmToken::LessEqual:
1713 case AsmToken::LessLess:
1714 case AsmToken::LessGreater:
1715 case AsmToken::Greater:
1716 case AsmToken::GreaterEqual:
1717 case AsmToken::GreaterGreater:
1722 bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
1723 AsmToken::TokenKind &ArgumentDelimiter) {
1724 unsigned ParenLevel = 0;
1725 unsigned AddTokens = 0;
1727 // gas accepts arguments separated by whitespace, except on Darwin
1729 Lexer.setSkipSpace(false);
1732 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1733 Lexer.setSkipSpace(true);
1734 return TokError("unexpected token in macro instantiation");
1737 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1738 // Spaces and commas cannot be mixed to delimit parameters
1739 if (ArgumentDelimiter == AsmToken::Eof)
1740 ArgumentDelimiter = AsmToken::Comma;
1741 else if (ArgumentDelimiter != AsmToken::Comma) {
1742 Lexer.setSkipSpace(true);
1743 return TokError("expected ' ' for macro argument separator");
1748 if (Lexer.is(AsmToken::Space)) {
1749 Lex(); // Eat spaces
1751 // Spaces can delimit parameters, but could also be part an expression.
1752 // If the token after a space is an operator, add the token and the next
1753 // one into this argument
1754 if (ArgumentDelimiter == AsmToken::Space ||
1755 ArgumentDelimiter == AsmToken::Eof) {
1756 if (IsOperator(Lexer.getKind())) {
1757 // Check to see whether the token is used as an operator,
1758 // or part of an identifier
1759 const char *NextChar = getTok().getEndLoc().getPointer();
1760 if (*NextChar == ' ')
1764 if (!AddTokens && ParenLevel == 0) {
1765 if (ArgumentDelimiter == AsmToken::Eof &&
1766 !IsOperator(Lexer.getKind()))
1767 ArgumentDelimiter = AsmToken::Space;
1773 // HandleMacroEntry relies on not advancing the lexer here
1774 // to be able to fill in the remaining default parameter values
1775 if (Lexer.is(AsmToken::EndOfStatement))
1778 // Adjust the current parentheses level.
1779 if (Lexer.is(AsmToken::LParen))
1781 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1784 // Append the token to the current argument list.
1785 MA.push_back(getTok());
1791 Lexer.setSkipSpace(true);
1792 if (ParenLevel != 0)
1793 return TokError("unbalanced parentheses in macro argument");
1797 // Parse the macro instantiation arguments.
1798 bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
1799 const unsigned NParameters = M ? M->Parameters.size() : 0;
1800 // Argument delimiter is initially unknown. It will be set by
1801 // ParseMacroArgument()
1802 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1804 // Parse two kinds of macro invocations:
1805 // - macros defined without any parameters accept an arbitrary number of them
1806 // - macros defined with parameters accept at most that many of them
1807 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1809 MCAsmMacroArgument MA;
1811 if (ParseMacroArgument(MA, ArgumentDelimiter))
1814 if (!MA.empty() || !NParameters)
1816 else if (NParameters) {
1817 if (!M->Parameters[Parameter].second.empty())
1818 A.push_back(M->Parameters[Parameter].second);
1821 // At the end of the statement, fill in remaining arguments that have
1822 // default values. If there aren't any, then the next argument is
1823 // required but missing
1824 if (Lexer.is(AsmToken::EndOfStatement)) {
1825 if (NParameters && Parameter < NParameters - 1) {
1826 if (M->Parameters[Parameter + 1].second.empty())
1827 return TokError("macro argument '" +
1828 Twine(M->Parameters[Parameter + 1].first) +
1836 if (Lexer.is(AsmToken::Comma))
1839 return TokError("Too many arguments");
1842 const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1843 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1844 return (I == MacroMap.end()) ? NULL : I->getValue();
1847 void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1848 MacroMap[Name] = new MCAsmMacro(Macro);
1851 void AsmParser::UndefineMacro(StringRef Name) {
1852 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1853 if (I != MacroMap.end()) {
1854 delete I->getValue();
1859 bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
1860 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1861 // this, although we should protect against infinite loops.
1862 if (ActiveMacros.size() == 20)
1863 return TokError("macros cannot be nested more than 20 levels deep");
1865 MCAsmMacroArguments A;
1866 if (ParseMacroArguments(M, A))
1869 // Remove any trailing empty arguments. Do this after-the-fact as we have
1870 // to keep empty arguments in the middle of the list or positionality
1871 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1872 while (!A.empty() && A.back().empty())
1875 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1876 // to hold the macro body with substitutions.
1877 SmallString<256> Buf;
1878 StringRef Body = M->Body;
1879 raw_svector_ostream OS(Buf);
1881 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1884 // We include the .endmacro in the buffer as our cue to exit the macro
1886 OS << ".endmacro\n";
1888 MemoryBuffer *Instantiation =
1889 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1891 // Create the macro instantiation object and add to the current macro
1892 // instantiation stack.
1893 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1897 ActiveMacros.push_back(MI);
1899 // Jump to the macro instantiation and prime the lexer.
1900 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1901 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1907 void AsmParser::HandleMacroExit() {
1908 // Jump to the EndOfStatement we should return to, and consume it.
1909 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
1912 // Pop the instantiation entry.
1913 delete ActiveMacros.back();
1914 ActiveMacros.pop_back();
1917 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1918 switch (Value->getKind()) {
1919 case MCExpr::Binary: {
1920 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1921 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1924 case MCExpr::Target:
1925 case MCExpr::Constant:
1927 case MCExpr::SymbolRef: {
1928 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1930 return IsUsedIn(Sym, S.getVariableValue());
1934 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1937 llvm_unreachable("Unknown expr kind!");
1940 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1942 // FIXME: Use better location, we should use proper tokens.
1943 SMLoc EqualLoc = Lexer.getLoc();
1945 const MCExpr *Value;
1946 if (ParseExpression(Value))
1949 // Note: we don't count b as used in "a = b". This is to allow
1953 if (Lexer.isNot(AsmToken::EndOfStatement))
1954 return TokError("unexpected token in assignment");
1956 // Error on assignment to '.'.
1958 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1959 "(use '.space' or '.org').)"));
1962 // Eat the end of statement marker.
1965 // Validate that the LHS is allowed to be a variable (either it has not been
1966 // used as a symbol, or it is an absolute symbol).
1967 MCSymbol *Sym = getContext().LookupSymbol(Name);
1969 // Diagnose assignment to a label.
1971 // FIXME: Diagnostics. Note the location of the definition as a label.
1972 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1973 if (IsUsedIn(Sym, Value))
1974 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1975 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1976 ; // Allow redefinitions of undefined symbols only used in directives.
1977 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1978 ; // Allow redefinitions of variables that haven't yet been used.
1979 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1980 return Error(EqualLoc, "redefinition of '" + Name + "'");
1981 else if (!Sym->isVariable())
1982 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1983 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1984 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1987 // Don't count these checks as uses.
1988 Sym->setUsed(false);
1990 Sym = getContext().GetOrCreateSymbol(Name);
1992 // FIXME: Handle '.'.
1994 // Do the assignment.
1995 Out.EmitAssignment(Sym, Value);
1997 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2003 /// ParseIdentifier:
2006 bool AsmParser::ParseIdentifier(StringRef &Res) {
2007 // The assembler has relaxed rules for accepting identifiers, in particular we
2008 // allow things like '.globl $foo', which would normally be separate
2009 // tokens. At this level, we have already lexed so we cannot (currently)
2010 // handle this as a context dependent token, instead we detect adjacent tokens
2011 // and return the combined identifier.
2012 if (Lexer.is(AsmToken::Dollar)) {
2013 SMLoc DollarLoc = getLexer().getLoc();
2015 // Consume the dollar sign, and check for a following identifier.
2017 if (Lexer.isNot(AsmToken::Identifier))
2020 // We have a '$' followed by an identifier, make sure they are adjacent.
2021 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2024 // Construct the joined identifier and consume the token.
2025 Res = StringRef(DollarLoc.getPointer(),
2026 getTok().getIdentifier().size() + 1);
2031 if (Lexer.isNot(AsmToken::Identifier) &&
2032 Lexer.isNot(AsmToken::String))
2035 Res = getTok().getIdentifier();
2037 Lex(); // Consume the identifier token.
2042 /// ParseDirectiveSet:
2043 /// ::= .equ identifier ',' expression
2044 /// ::= .equiv identifier ',' expression
2045 /// ::= .set identifier ',' expression
2046 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
2049 if (ParseIdentifier(Name))
2050 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2052 if (getLexer().isNot(AsmToken::Comma))
2053 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2056 return ParseAssignment(Name, allow_redef, true);
2059 bool AsmParser::ParseEscapedString(std::string &Data) {
2060 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2063 StringRef Str = getTok().getStringContents();
2064 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2065 if (Str[i] != '\\') {
2070 // Recognize escaped characters. Note that this escape semantics currently
2071 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2074 return TokError("unexpected backslash at end of string");
2076 // Recognize octal sequences.
2077 if ((unsigned) (Str[i] - '0') <= 7) {
2078 // Consume up to three octal characters.
2079 unsigned Value = Str[i] - '0';
2081 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2083 Value = Value * 8 + (Str[i] - '0');
2085 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2087 Value = Value * 8 + (Str[i] - '0');
2092 return TokError("invalid octal escape sequence (out of range)");
2094 Data += (unsigned char) Value;
2098 // Otherwise recognize individual escapes.
2101 // Just reject invalid escape sequences for now.
2102 return TokError("invalid escape sequence (unrecognized character)");
2104 case 'b': Data += '\b'; break;
2105 case 'f': Data += '\f'; break;
2106 case 'n': Data += '\n'; break;
2107 case 'r': Data += '\r'; break;
2108 case 't': Data += '\t'; break;
2109 case '"': Data += '"'; break;
2110 case '\\': Data += '\\'; break;
2117 /// ParseDirectiveAscii:
2118 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2119 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2120 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2121 CheckForValidSection();
2124 if (getLexer().isNot(AsmToken::String))
2125 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2128 if (ParseEscapedString(Data))
2131 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2133 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2137 if (getLexer().is(AsmToken::EndOfStatement))
2140 if (getLexer().isNot(AsmToken::Comma))
2141 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2150 /// ParseDirectiveValue
2151 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2152 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2153 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2154 CheckForValidSection();
2157 const MCExpr *Value;
2158 SMLoc ExprLoc = getLexer().getLoc();
2159 if (ParseExpression(Value))
2162 // Special case constant expressions to match code generator.
2163 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2164 assert(Size <= 8 && "Invalid size");
2165 uint64_t IntValue = MCE->getValue();
2166 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2167 return Error(ExprLoc, "literal value out of range for directive");
2168 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2170 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2172 if (getLexer().is(AsmToken::EndOfStatement))
2175 // FIXME: Improve diagnostic.
2176 if (getLexer().isNot(AsmToken::Comma))
2177 return TokError("unexpected token in directive");
2186 /// ParseDirectiveRealValue
2187 /// ::= (.single | .double) [ expression (, expression)* ]
2188 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2189 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2190 CheckForValidSection();
2193 // We don't truly support arithmetic on floating point expressions, so we
2194 // have to manually parse unary prefixes.
2196 if (getLexer().is(AsmToken::Minus)) {
2199 } else if (getLexer().is(AsmToken::Plus))
2202 if (getLexer().isNot(AsmToken::Integer) &&
2203 getLexer().isNot(AsmToken::Real) &&
2204 getLexer().isNot(AsmToken::Identifier))
2205 return TokError("unexpected token in directive");
2207 // Convert to an APFloat.
2208 APFloat Value(Semantics);
2209 StringRef IDVal = getTok().getString();
2210 if (getLexer().is(AsmToken::Identifier)) {
2211 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2212 Value = APFloat::getInf(Semantics);
2213 else if (!IDVal.compare_lower("nan"))
2214 Value = APFloat::getNaN(Semantics, false, ~0);
2216 return TokError("invalid floating point literal");
2217 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2218 APFloat::opInvalidOp)
2219 return TokError("invalid floating point literal");
2223 // Consume the numeric token.
2226 // Emit the value as an integer.
2227 APInt AsInt = Value.bitcastToAPInt();
2228 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2229 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2231 if (getLexer().is(AsmToken::EndOfStatement))
2234 if (getLexer().isNot(AsmToken::Comma))
2235 return TokError("unexpected token in directive");
2244 /// ParseDirectiveZero
2245 /// ::= .zero expression
2246 bool AsmParser::ParseDirectiveZero() {
2247 CheckForValidSection();
2250 if (ParseAbsoluteExpression(NumBytes))
2254 if (getLexer().is(AsmToken::Comma)) {
2256 if (ParseAbsoluteExpression(Val))
2260 if (getLexer().isNot(AsmToken::EndOfStatement))
2261 return TokError("unexpected token in '.zero' directive");
2265 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2270 /// ParseDirectiveFill
2271 /// ::= .fill expression , expression , expression
2272 bool AsmParser::ParseDirectiveFill() {
2273 CheckForValidSection();
2276 if (ParseAbsoluteExpression(NumValues))
2279 if (getLexer().isNot(AsmToken::Comma))
2280 return TokError("unexpected token in '.fill' directive");
2284 if (ParseAbsoluteExpression(FillSize))
2287 if (getLexer().isNot(AsmToken::Comma))
2288 return TokError("unexpected token in '.fill' directive");
2292 if (ParseAbsoluteExpression(FillExpr))
2295 if (getLexer().isNot(AsmToken::EndOfStatement))
2296 return TokError("unexpected token in '.fill' directive");
2300 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2301 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2303 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2304 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2309 /// ParseDirectiveOrg
2310 /// ::= .org expression [ , expression ]
2311 bool AsmParser::ParseDirectiveOrg() {
2312 CheckForValidSection();
2314 const MCExpr *Offset;
2315 SMLoc Loc = getTok().getLoc();
2316 if (ParseExpression(Offset))
2319 // Parse optional fill expression.
2320 int64_t FillExpr = 0;
2321 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2322 if (getLexer().isNot(AsmToken::Comma))
2323 return TokError("unexpected token in '.org' directive");
2326 if (ParseAbsoluteExpression(FillExpr))
2329 if (getLexer().isNot(AsmToken::EndOfStatement))
2330 return TokError("unexpected token in '.org' directive");
2335 // Only limited forms of relocatable expressions are accepted here, it
2336 // has to be relative to the current section. The streamer will return
2337 // 'true' if the expression wasn't evaluatable.
2338 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2339 return Error(Loc, "expected assembly-time absolute expression");
2344 /// ParseDirectiveAlign
2345 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2346 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2347 CheckForValidSection();
2349 SMLoc AlignmentLoc = getLexer().getLoc();
2351 if (ParseAbsoluteExpression(Alignment))
2355 bool HasFillExpr = false;
2356 int64_t FillExpr = 0;
2357 int64_t MaxBytesToFill = 0;
2358 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2359 if (getLexer().isNot(AsmToken::Comma))
2360 return TokError("unexpected token in directive");
2363 // The fill expression can be omitted while specifying a maximum number of
2364 // alignment bytes, e.g:
2366 if (getLexer().isNot(AsmToken::Comma)) {
2368 if (ParseAbsoluteExpression(FillExpr))
2372 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2373 if (getLexer().isNot(AsmToken::Comma))
2374 return TokError("unexpected token in directive");
2377 MaxBytesLoc = getLexer().getLoc();
2378 if (ParseAbsoluteExpression(MaxBytesToFill))
2381 if (getLexer().isNot(AsmToken::EndOfStatement))
2382 return TokError("unexpected token in directive");
2391 // Compute alignment in bytes.
2393 // FIXME: Diagnose overflow.
2394 if (Alignment >= 32) {
2395 Error(AlignmentLoc, "invalid alignment value");
2399 Alignment = 1ULL << Alignment;
2402 // Diagnose non-sensical max bytes to align.
2403 if (MaxBytesLoc.isValid()) {
2404 if (MaxBytesToFill < 1) {
2405 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2406 "many bytes, ignoring maximum bytes expression");
2410 if (MaxBytesToFill >= Alignment) {
2411 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2417 // Check whether we should use optimal code alignment for this .align
2419 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2420 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2421 ValueSize == 1 && UseCodeAlign) {
2422 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2424 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2425 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2433 /// ParseDirectiveBundleAlignMode
2434 /// ::= {.bundle_align_mode} expression
2435 bool AsmParser::ParseDirectiveBundleAlignMode() {
2436 CheckForValidSection();
2438 // Expect a single argument: an expression that evaluates to a constant
2439 // in the inclusive range 0-30.
2440 SMLoc ExprLoc = getLexer().getLoc();
2441 int64_t AlignSizePow2;
2442 if (ParseAbsoluteExpression(AlignSizePow2))
2444 else if (getLexer().isNot(AsmToken::EndOfStatement))
2445 return TokError("unexpected token after expression in"
2446 " '.bundle_align_mode' directive");
2447 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
2448 return Error(ExprLoc,
2449 "invalid bundle alignment size (expected between 0 and 30)");
2453 // Because of AlignSizePow2's verified range we can safely truncate it to
2455 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
2459 /// ParseDirectiveBundleLock
2460 /// ::= {.bundle_lock} [align_to_end]
2461 bool AsmParser::ParseDirectiveBundleLock() {
2462 CheckForValidSection();
2463 bool AlignToEnd = false;
2465 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2467 SMLoc Loc = getTok().getLoc();
2468 const char *kInvalidOptionError =
2469 "invalid option for '.bundle_lock' directive";
2471 if (ParseIdentifier(Option))
2472 return Error(Loc, kInvalidOptionError);
2474 if (Option != "align_to_end")
2475 return Error(Loc, kInvalidOptionError);
2476 else if (getLexer().isNot(AsmToken::EndOfStatement))
2478 "unexpected token after '.bundle_lock' directive option");
2484 getStreamer().EmitBundleLock(AlignToEnd);
2488 /// ParseDirectiveBundleLock
2489 /// ::= {.bundle_lock}
2490 bool AsmParser::ParseDirectiveBundleUnlock() {
2491 CheckForValidSection();
2493 if (getLexer().isNot(AsmToken::EndOfStatement))
2494 return TokError("unexpected token in '.bundle_unlock' directive");
2497 getStreamer().EmitBundleUnlock();
2501 /// ParseDirectiveSymbolAttribute
2502 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2503 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2504 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2507 SMLoc Loc = getTok().getLoc();
2509 if (ParseIdentifier(Name))
2510 return Error(Loc, "expected identifier in directive");
2512 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2514 // Assembler local symbols don't make any sense here. Complain loudly.
2515 if (Sym->isTemporary())
2516 return Error(Loc, "non-local symbol required in directive");
2518 getStreamer().EmitSymbolAttribute(Sym, Attr);
2520 if (getLexer().is(AsmToken::EndOfStatement))
2523 if (getLexer().isNot(AsmToken::Comma))
2524 return TokError("unexpected token in directive");
2533 /// ParseDirectiveComm
2534 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2535 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2536 CheckForValidSection();
2538 SMLoc IDLoc = getLexer().getLoc();
2540 if (ParseIdentifier(Name))
2541 return TokError("expected identifier in directive");
2543 // Handle the identifier as the key symbol.
2544 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2546 if (getLexer().isNot(AsmToken::Comma))
2547 return TokError("unexpected token in directive");
2551 SMLoc SizeLoc = getLexer().getLoc();
2552 if (ParseAbsoluteExpression(Size))
2555 int64_t Pow2Alignment = 0;
2556 SMLoc Pow2AlignmentLoc;
2557 if (getLexer().is(AsmToken::Comma)) {
2559 Pow2AlignmentLoc = getLexer().getLoc();
2560 if (ParseAbsoluteExpression(Pow2Alignment))
2563 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2564 if (IsLocal && LCOMM == LCOMM::NoAlignment)
2565 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2567 // If this target takes alignments in bytes (not log) validate and convert.
2568 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2569 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
2570 if (!isPowerOf2_64(Pow2Alignment))
2571 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2572 Pow2Alignment = Log2_64(Pow2Alignment);
2576 if (getLexer().isNot(AsmToken::EndOfStatement))
2577 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2581 // NOTE: a size of zero for a .comm should create a undefined symbol
2582 // but a size of .lcomm creates a bss symbol of size zero.
2584 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2585 "be less than zero");
2587 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2588 // may internally end up wanting an alignment in bytes.
2589 // FIXME: Diagnose overflow.
2590 if (Pow2Alignment < 0)
2591 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2592 "alignment, can't be less than zero");
2594 if (!Sym->isUndefined())
2595 return Error(IDLoc, "invalid symbol redefinition");
2597 // Create the Symbol as a common or local common with Size and Pow2Alignment
2599 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2603 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2607 /// ParseDirectiveAbort
2608 /// ::= .abort [... message ...]
2609 bool AsmParser::ParseDirectiveAbort() {
2610 // FIXME: Use loc from directive.
2611 SMLoc Loc = getLexer().getLoc();
2613 StringRef Str = ParseStringToEndOfStatement();
2614 if (getLexer().isNot(AsmToken::EndOfStatement))
2615 return TokError("unexpected token in '.abort' directive");
2620 Error(Loc, ".abort detected. Assembly stopping.");
2622 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2623 // FIXME: Actually abort assembly here.
2628 /// ParseDirectiveInclude
2629 /// ::= .include "filename"
2630 bool AsmParser::ParseDirectiveInclude() {
2631 if (getLexer().isNot(AsmToken::String))
2632 return TokError("expected string in '.include' directive");
2634 std::string Filename = getTok().getString();
2635 SMLoc IncludeLoc = getLexer().getLoc();
2638 if (getLexer().isNot(AsmToken::EndOfStatement))
2639 return TokError("unexpected token in '.include' directive");
2641 // Strip the quotes.
2642 Filename = Filename.substr(1, Filename.size()-2);
2644 // Attempt to switch the lexer to the included file before consuming the end
2645 // of statement to avoid losing it when we switch.
2646 if (EnterIncludeFile(Filename)) {
2647 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2654 /// ParseDirectiveIncbin
2655 /// ::= .incbin "filename"
2656 bool AsmParser::ParseDirectiveIncbin() {
2657 if (getLexer().isNot(AsmToken::String))
2658 return TokError("expected string in '.incbin' directive");
2660 std::string Filename = getTok().getString();
2661 SMLoc IncbinLoc = getLexer().getLoc();
2664 if (getLexer().isNot(AsmToken::EndOfStatement))
2665 return TokError("unexpected token in '.incbin' directive");
2667 // Strip the quotes.
2668 Filename = Filename.substr(1, Filename.size()-2);
2670 // Attempt to process the included file.
2671 if (ProcessIncbinFile(Filename)) {
2672 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2679 /// ParseDirectiveIf
2680 /// ::= .if expression
2681 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2682 TheCondStack.push_back(TheCondState);
2683 TheCondState.TheCond = AsmCond::IfCond;
2684 if (TheCondState.Ignore) {
2685 EatToEndOfStatement();
2688 if (ParseAbsoluteExpression(ExprValue))
2691 if (getLexer().isNot(AsmToken::EndOfStatement))
2692 return TokError("unexpected token in '.if' directive");
2696 TheCondState.CondMet = ExprValue;
2697 TheCondState.Ignore = !TheCondState.CondMet;
2703 /// ParseDirectiveIfb
2705 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2706 TheCondStack.push_back(TheCondState);
2707 TheCondState.TheCond = AsmCond::IfCond;
2709 if (TheCondState.Ignore) {
2710 EatToEndOfStatement();
2712 StringRef Str = ParseStringToEndOfStatement();
2714 if (getLexer().isNot(AsmToken::EndOfStatement))
2715 return TokError("unexpected token in '.ifb' directive");
2719 TheCondState.CondMet = ExpectBlank == Str.empty();
2720 TheCondState.Ignore = !TheCondState.CondMet;
2726 /// ParseDirectiveIfc
2727 /// ::= .ifc string1, string2
2728 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2729 TheCondStack.push_back(TheCondState);
2730 TheCondState.TheCond = AsmCond::IfCond;
2732 if (TheCondState.Ignore) {
2733 EatToEndOfStatement();
2735 StringRef Str1 = ParseStringToComma();
2737 if (getLexer().isNot(AsmToken::Comma))
2738 return TokError("unexpected token in '.ifc' directive");
2742 StringRef Str2 = ParseStringToEndOfStatement();
2744 if (getLexer().isNot(AsmToken::EndOfStatement))
2745 return TokError("unexpected token in '.ifc' directive");
2749 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2750 TheCondState.Ignore = !TheCondState.CondMet;
2756 /// ParseDirectiveIfdef
2757 /// ::= .ifdef symbol
2758 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2760 TheCondStack.push_back(TheCondState);
2761 TheCondState.TheCond = AsmCond::IfCond;
2763 if (TheCondState.Ignore) {
2764 EatToEndOfStatement();
2766 if (ParseIdentifier(Name))
2767 return TokError("expected identifier after '.ifdef'");
2771 MCSymbol *Sym = getContext().LookupSymbol(Name);
2774 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2776 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2777 TheCondState.Ignore = !TheCondState.CondMet;
2783 /// ParseDirectiveElseIf
2784 /// ::= .elseif expression
2785 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2786 if (TheCondState.TheCond != AsmCond::IfCond &&
2787 TheCondState.TheCond != AsmCond::ElseIfCond)
2788 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2790 TheCondState.TheCond = AsmCond::ElseIfCond;
2792 bool LastIgnoreState = false;
2793 if (!TheCondStack.empty())
2794 LastIgnoreState = TheCondStack.back().Ignore;
2795 if (LastIgnoreState || TheCondState.CondMet) {
2796 TheCondState.Ignore = true;
2797 EatToEndOfStatement();
2801 if (ParseAbsoluteExpression(ExprValue))
2804 if (getLexer().isNot(AsmToken::EndOfStatement))
2805 return TokError("unexpected token in '.elseif' directive");
2808 TheCondState.CondMet = ExprValue;
2809 TheCondState.Ignore = !TheCondState.CondMet;
2815 /// ParseDirectiveElse
2817 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2818 if (getLexer().isNot(AsmToken::EndOfStatement))
2819 return TokError("unexpected token in '.else' directive");
2823 if (TheCondState.TheCond != AsmCond::IfCond &&
2824 TheCondState.TheCond != AsmCond::ElseIfCond)
2825 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2827 TheCondState.TheCond = AsmCond::ElseCond;
2828 bool LastIgnoreState = false;
2829 if (!TheCondStack.empty())
2830 LastIgnoreState = TheCondStack.back().Ignore;
2831 if (LastIgnoreState || TheCondState.CondMet)
2832 TheCondState.Ignore = true;
2834 TheCondState.Ignore = false;
2839 /// ParseDirectiveEndIf
2841 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2842 if (getLexer().isNot(AsmToken::EndOfStatement))
2843 return TokError("unexpected token in '.endif' directive");
2847 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2848 TheCondStack.empty())
2849 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2851 if (!TheCondStack.empty()) {
2852 TheCondState = TheCondStack.back();
2853 TheCondStack.pop_back();
2859 void AsmParser::initializeDirectiveKindMapping() {
2860 DirectiveKindMapping[".set"] = DK_SET;
2861 DirectiveKindMapping[".equ"] = DK_EQU;
2862 DirectiveKindMapping[".equiv"] = DK_EQUIV;
2863 DirectiveKindMapping[".ascii"] = DK_ASCII;
2864 DirectiveKindMapping[".asciz"] = DK_ASCIZ;
2865 DirectiveKindMapping[".string"] = DK_STRING;
2866 DirectiveKindMapping[".byte"] = DK_BYTE;
2867 DirectiveKindMapping[".short"] = DK_SHORT;
2868 DirectiveKindMapping[".value"] = DK_VALUE;
2869 DirectiveKindMapping[".2byte"] = DK_2BYTE;
2870 DirectiveKindMapping[".long"] = DK_LONG;
2871 DirectiveKindMapping[".int"] = DK_INT;
2872 DirectiveKindMapping[".4byte"] = DK_4BYTE;
2873 DirectiveKindMapping[".quad"] = DK_QUAD;
2874 DirectiveKindMapping[".8byte"] = DK_8BYTE;
2875 DirectiveKindMapping[".single"] = DK_SINGLE;
2876 DirectiveKindMapping[".float"] = DK_FLOAT;
2877 DirectiveKindMapping[".double"] = DK_DOUBLE;
2878 DirectiveKindMapping[".align"] = DK_ALIGN;
2879 DirectiveKindMapping[".align32"] = DK_ALIGN32;
2880 DirectiveKindMapping[".balign"] = DK_BALIGN;
2881 DirectiveKindMapping[".balignw"] = DK_BALIGNW;
2882 DirectiveKindMapping[".balignl"] = DK_BALIGNL;
2883 DirectiveKindMapping[".p2align"] = DK_P2ALIGN;
2884 DirectiveKindMapping[".p2alignw"] = DK_P2ALIGNW;
2885 DirectiveKindMapping[".p2alignl"] = DK_P2ALIGNL;
2886 DirectiveKindMapping[".org"] = DK_ORG;
2887 DirectiveKindMapping[".fill"] = DK_FILL;
2888 DirectiveKindMapping[".zero"] = DK_ZERO;
2889 DirectiveKindMapping[".extern"] = DK_EXTERN;
2890 DirectiveKindMapping[".globl"] = DK_GLOBL;
2891 DirectiveKindMapping[".global"] = DK_GLOBAL;
2892 DirectiveKindMapping[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
2893 DirectiveKindMapping[".lazy_reference"] = DK_LAZY_REFERENCE;
2894 DirectiveKindMapping[".no_dead_strip"] = DK_NO_DEAD_STRIP;
2895 DirectiveKindMapping[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
2896 DirectiveKindMapping[".private_extern"] = DK_PRIVATE_EXTERN;
2897 DirectiveKindMapping[".reference"] = DK_REFERENCE;
2898 DirectiveKindMapping[".weak_definition"] = DK_WEAK_DEFINITION;
2899 DirectiveKindMapping[".weak_reference"] = DK_WEAK_REFERENCE;
2900 DirectiveKindMapping[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
2901 DirectiveKindMapping[".comm"] = DK_COMM;
2902 DirectiveKindMapping[".common"] = DK_COMMON;
2903 DirectiveKindMapping[".lcomm"] = DK_LCOMM;
2904 DirectiveKindMapping[".abort"] = DK_ABORT;
2905 DirectiveKindMapping[".include"] = DK_INCLUDE;
2906 DirectiveKindMapping[".incbin"] = DK_INCBIN;
2907 DirectiveKindMapping[".code16"] = DK_CODE16;
2908 DirectiveKindMapping[".code16gcc"] = DK_CODE16GCC;
2909 DirectiveKindMapping[".rept"] = DK_REPT;
2910 DirectiveKindMapping[".irp"] = DK_IRP;
2911 DirectiveKindMapping[".irpc"] = DK_IRPC;
2912 DirectiveKindMapping[".endr"] = DK_ENDR;
2913 DirectiveKindMapping[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
2914 DirectiveKindMapping[".bundle_lock"] = DK_BUNDLE_LOCK;
2915 DirectiveKindMapping[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
2916 DirectiveKindMapping[".if"] = DK_IF;
2917 DirectiveKindMapping[".ifb"] = DK_IFB;
2918 DirectiveKindMapping[".ifnb"] = DK_IFNB;
2919 DirectiveKindMapping[".ifc"] = DK_IFC;
2920 DirectiveKindMapping[".ifnc"] = DK_IFNC;
2921 DirectiveKindMapping[".ifdef"] = DK_IFDEF;
2922 DirectiveKindMapping[".ifndef"] = DK_IFNDEF;
2923 DirectiveKindMapping[".ifnotdef"] = DK_IFNOTDEF;
2924 DirectiveKindMapping[".elseif"] = DK_ELSEIF;
2925 DirectiveKindMapping[".else"] = DK_ELSE;
2926 DirectiveKindMapping[".endif"] = DK_ENDIF;
2929 /// ParseDirectiveFile
2930 /// ::= .file [number] filename
2931 /// ::= .file number directory filename
2932 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2933 // FIXME: I'm not sure what this is.
2934 int64_t FileNumber = -1;
2935 SMLoc FileNumberLoc = getLexer().getLoc();
2936 if (getLexer().is(AsmToken::Integer)) {
2937 FileNumber = getTok().getIntVal();
2941 return TokError("file number less than one");
2944 if (getLexer().isNot(AsmToken::String))
2945 return TokError("unexpected token in '.file' directive");
2947 // Usually the directory and filename together, otherwise just the directory.
2948 StringRef Path = getTok().getString();
2949 Path = Path.substr(1, Path.size()-2);
2952 StringRef Directory;
2954 if (getLexer().is(AsmToken::String)) {
2955 if (FileNumber == -1)
2956 return TokError("explicit path specified, but no file number");
2957 Filename = getTok().getString();
2958 Filename = Filename.substr(1, Filename.size()-2);
2965 if (getLexer().isNot(AsmToken::EndOfStatement))
2966 return TokError("unexpected token in '.file' directive");
2968 if (FileNumber == -1)
2969 getStreamer().EmitFileDirective(Filename);
2971 if (getContext().getGenDwarfForAssembly() == true)
2972 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2973 "used to generate dwarf debug info for assembly code");
2975 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2976 Error(FileNumberLoc, "file number already allocated");
2982 /// ParseDirectiveLine
2983 /// ::= .line [number]
2984 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2985 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2986 if (getLexer().isNot(AsmToken::Integer))
2987 return TokError("unexpected token in '.line' directive");
2989 int64_t LineNumber = getTok().getIntVal();
2993 // FIXME: Do something with the .line.
2996 if (getLexer().isNot(AsmToken::EndOfStatement))
2997 return TokError("unexpected token in '.line' directive");
3003 /// ParseDirectiveLoc
3004 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3005 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3006 /// The first number is a file number, must have been previously assigned with
3007 /// a .file directive, the second number is the line number and optionally the
3008 /// third number is a column position (zero if not specified). The remaining
3009 /// optional items are .loc sub-directives.
3010 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
3012 if (getLexer().isNot(AsmToken::Integer))
3013 return TokError("unexpected token in '.loc' directive");
3014 int64_t FileNumber = getTok().getIntVal();
3016 return TokError("file number less than one in '.loc' directive");
3017 if (!getContext().isValidDwarfFileNumber(FileNumber))
3018 return TokError("unassigned file number in '.loc' directive");
3021 int64_t LineNumber = 0;
3022 if (getLexer().is(AsmToken::Integer)) {
3023 LineNumber = getTok().getIntVal();
3025 return TokError("line number less than one in '.loc' directive");
3029 int64_t ColumnPos = 0;
3030 if (getLexer().is(AsmToken::Integer)) {
3031 ColumnPos = getTok().getIntVal();
3033 return TokError("column position less than zero in '.loc' directive");
3037 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3039 int64_t Discriminator = 0;
3040 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3042 if (getLexer().is(AsmToken::EndOfStatement))
3046 SMLoc Loc = getTok().getLoc();
3047 if (getParser().ParseIdentifier(Name))
3048 return TokError("unexpected token in '.loc' directive");
3050 if (Name == "basic_block")
3051 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3052 else if (Name == "prologue_end")
3053 Flags |= DWARF2_FLAG_PROLOGUE_END;
3054 else if (Name == "epilogue_begin")
3055 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3056 else if (Name == "is_stmt") {
3057 Loc = getTok().getLoc();
3058 const MCExpr *Value;
3059 if (getParser().ParseExpression(Value))
3061 // The expression must be the constant 0 or 1.
3062 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3063 int Value = MCE->getValue();
3065 Flags &= ~DWARF2_FLAG_IS_STMT;
3066 else if (Value == 1)
3067 Flags |= DWARF2_FLAG_IS_STMT;
3069 return Error(Loc, "is_stmt value not 0 or 1");
3072 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3075 else if (Name == "isa") {
3076 Loc = getTok().getLoc();
3077 const MCExpr *Value;
3078 if (getParser().ParseExpression(Value))
3080 // The expression must be a constant greater or equal to 0.
3081 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3082 int Value = MCE->getValue();
3084 return Error(Loc, "isa number less than zero");
3088 return Error(Loc, "isa number not a constant value");
3091 else if (Name == "discriminator") {
3092 if (getParser().ParseAbsoluteExpression(Discriminator))
3096 return Error(Loc, "unknown sub-directive in '.loc' directive");
3099 if (getLexer().is(AsmToken::EndOfStatement))
3104 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3105 Isa, Discriminator, StringRef());
3110 /// ParseDirectiveStabs
3111 /// ::= .stabs string, number, number, number
3112 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
3113 SMLoc DirectiveLoc) {
3114 return TokError("unsupported directive '" + Directive + "'");
3117 /// ParseDirectiveSpace
3118 /// ::= .space expression [ , expression ]
3119 bool GenericAsmParser::ParseDirectiveSpace(StringRef, SMLoc DirectiveLoc) {
3120 getParser().CheckForValidSection();
3123 if (getParser().ParseAbsoluteExpression(NumBytes))
3126 int64_t FillExpr = 0;
3127 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3128 if (getLexer().isNot(AsmToken::Comma))
3129 return TokError("unexpected token in '.space' directive");
3132 if (getParser().ParseAbsoluteExpression(FillExpr))
3135 if (getLexer().isNot(AsmToken::EndOfStatement))
3136 return TokError("unexpected token in '.space' directive");
3142 return TokError("invalid number of bytes in '.space' directive");
3144 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3145 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3150 /// ParseDirectiveCFISections
3151 /// ::= .cfi_sections section [, section]
3152 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
3153 SMLoc DirectiveLoc) {
3158 if (getParser().ParseIdentifier(Name))
3159 return TokError("Expected an identifier");
3161 if (Name == ".eh_frame")
3163 else if (Name == ".debug_frame")
3166 if (getLexer().is(AsmToken::Comma)) {
3169 if (getParser().ParseIdentifier(Name))
3170 return TokError("Expected an identifier");
3172 if (Name == ".eh_frame")
3174 else if (Name == ".debug_frame")
3178 getStreamer().EmitCFISections(EH, Debug);
3183 /// ParseDirectiveCFIStartProc
3184 /// ::= .cfi_startproc
3185 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
3186 SMLoc DirectiveLoc) {
3187 getStreamer().EmitCFIStartProc();
3191 /// ParseDirectiveCFIEndProc
3192 /// ::= .cfi_endproc
3193 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
3194 getStreamer().EmitCFIEndProc();
3198 /// ParseRegisterOrRegisterNumber - parse register name or number.
3199 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3200 SMLoc DirectiveLoc) {
3203 if (getLexer().isNot(AsmToken::Integer)) {
3204 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3207 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
3209 return getParser().ParseAbsoluteExpression(Register);
3214 /// ParseDirectiveCFIDefCfa
3215 /// ::= .cfi_def_cfa register, offset
3216 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3217 SMLoc DirectiveLoc) {
3218 int64_t Register = 0;
3219 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3222 if (getLexer().isNot(AsmToken::Comma))
3223 return TokError("unexpected token in directive");
3227 if (getParser().ParseAbsoluteExpression(Offset))
3230 getStreamer().EmitCFIDefCfa(Register, Offset);
3234 /// ParseDirectiveCFIDefCfaOffset
3235 /// ::= .cfi_def_cfa_offset offset
3236 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3237 SMLoc DirectiveLoc) {
3239 if (getParser().ParseAbsoluteExpression(Offset))
3242 getStreamer().EmitCFIDefCfaOffset(Offset);
3246 /// ParseDirectiveCFIAdjustCfaOffset
3247 /// ::= .cfi_adjust_cfa_offset adjustment
3248 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3249 SMLoc DirectiveLoc) {
3250 int64_t Adjustment = 0;
3251 if (getParser().ParseAbsoluteExpression(Adjustment))
3254 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3258 /// ParseDirectiveCFIDefCfaRegister
3259 /// ::= .cfi_def_cfa_register register
3260 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3261 SMLoc DirectiveLoc) {
3262 int64_t Register = 0;
3263 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3266 getStreamer().EmitCFIDefCfaRegister(Register);
3270 /// ParseDirectiveCFIOffset
3271 /// ::= .cfi_offset register, offset
3272 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3273 int64_t Register = 0;
3276 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3279 if (getLexer().isNot(AsmToken::Comma))
3280 return TokError("unexpected token in directive");
3283 if (getParser().ParseAbsoluteExpression(Offset))
3286 getStreamer().EmitCFIOffset(Register, Offset);
3290 /// ParseDirectiveCFIRelOffset
3291 /// ::= .cfi_rel_offset register, offset
3292 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3293 SMLoc DirectiveLoc) {
3294 int64_t Register = 0;
3296 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3299 if (getLexer().isNot(AsmToken::Comma))
3300 return TokError("unexpected token in directive");
3304 if (getParser().ParseAbsoluteExpression(Offset))
3307 getStreamer().EmitCFIRelOffset(Register, Offset);
3311 static bool isValidEncoding(int64_t Encoding) {
3312 if (Encoding & ~0xff)
3315 if (Encoding == dwarf::DW_EH_PE_omit)
3318 const unsigned Format = Encoding & 0xf;
3319 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3320 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3321 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3322 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3325 const unsigned Application = Encoding & 0x70;
3326 if (Application != dwarf::DW_EH_PE_absptr &&
3327 Application != dwarf::DW_EH_PE_pcrel)
3333 /// ParseDirectiveCFIPersonalityOrLsda
3334 /// ::= .cfi_personality encoding, [symbol_name]
3335 /// ::= .cfi_lsda encoding, [symbol_name]
3336 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
3337 SMLoc DirectiveLoc) {
3338 int64_t Encoding = 0;
3339 if (getParser().ParseAbsoluteExpression(Encoding))
3341 if (Encoding == dwarf::DW_EH_PE_omit)
3344 if (!isValidEncoding(Encoding))
3345 return TokError("unsupported encoding.");
3347 if (getLexer().isNot(AsmToken::Comma))
3348 return TokError("unexpected token in directive");
3352 if (getParser().ParseIdentifier(Name))
3353 return TokError("expected identifier in directive");
3355 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3357 if (IDVal == ".cfi_personality")
3358 getStreamer().EmitCFIPersonality(Sym, Encoding);
3360 assert(IDVal == ".cfi_lsda");
3361 getStreamer().EmitCFILsda(Sym, Encoding);
3366 /// ParseDirectiveCFIRememberState
3367 /// ::= .cfi_remember_state
3368 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3369 SMLoc DirectiveLoc) {
3370 getStreamer().EmitCFIRememberState();
3374 /// ParseDirectiveCFIRestoreState
3375 /// ::= .cfi_remember_state
3376 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3377 SMLoc DirectiveLoc) {
3378 getStreamer().EmitCFIRestoreState();
3382 /// ParseDirectiveCFISameValue
3383 /// ::= .cfi_same_value register
3384 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3385 SMLoc DirectiveLoc) {
3386 int64_t Register = 0;
3388 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3391 getStreamer().EmitCFISameValue(Register);
3396 /// ParseDirectiveCFIRestore
3397 /// ::= .cfi_restore register
3398 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
3399 SMLoc DirectiveLoc) {
3400 int64_t Register = 0;
3401 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3404 getStreamer().EmitCFIRestore(Register);
3409 /// ParseDirectiveCFIEscape
3410 /// ::= .cfi_escape expression[,...]
3411 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3412 SMLoc DirectiveLoc) {
3415 if (getParser().ParseAbsoluteExpression(CurrValue))
3418 Values.push_back((uint8_t)CurrValue);
3420 while (getLexer().is(AsmToken::Comma)) {
3423 if (getParser().ParseAbsoluteExpression(CurrValue))
3426 Values.push_back((uint8_t)CurrValue);
3429 getStreamer().EmitCFIEscape(Values);
3433 /// ParseDirectiveCFISignalFrame
3434 /// ::= .cfi_signal_frame
3435 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3436 SMLoc DirectiveLoc) {
3437 if (getLexer().isNot(AsmToken::EndOfStatement))
3438 return Error(getLexer().getLoc(),
3439 "unexpected token in '" + Directive + "' directive");
3441 getStreamer().EmitCFISignalFrame();
3446 /// ParseDirectiveCFIUndefined
3447 /// ::= .cfi_undefined register
3448 bool GenericAsmParser::ParseDirectiveCFIUndefined(StringRef Directive,
3449 SMLoc DirectiveLoc) {
3450 int64_t Register = 0;
3452 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3455 getStreamer().EmitCFIUndefined(Register);
3460 /// ParseDirectiveCFIRegister
3461 /// ::= .cfi_register register, register
3462 bool GenericAsmParser::ParseDirectiveCFIRegister(StringRef Directive,
3463 SMLoc DirectiveLoc) {
3464 int64_t Register1 = 0;
3466 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3469 if (getLexer().isNot(AsmToken::Comma))
3470 return TokError("unexpected token in directive");
3473 int64_t Register2 = 0;
3475 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3478 getStreamer().EmitCFIRegister(Register1, Register2);
3483 /// ParseDirectiveMacrosOnOff
3486 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3487 SMLoc DirectiveLoc) {
3488 if (getLexer().isNot(AsmToken::EndOfStatement))
3489 return Error(getLexer().getLoc(),
3490 "unexpected token in '" + Directive + "' directive");
3492 getParser().SetMacrosEnabled(Directive == ".macros_on");
3497 /// ParseDirectiveMacro
3498 /// ::= .macro name [parameters]
3499 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3500 SMLoc DirectiveLoc) {
3502 if (getParser().ParseIdentifier(Name))
3503 return TokError("expected identifier in '.macro' directive");
3505 MCAsmMacroParameters Parameters;
3506 // Argument delimiter is initially unknown. It will be set by
3507 // ParseMacroArgument()
3508 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3509 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3511 MCAsmMacroParameter Parameter;
3512 if (getParser().ParseIdentifier(Parameter.first))
3513 return TokError("expected identifier in '.macro' directive");
3515 if (getLexer().is(AsmToken::Equal)) {
3517 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3521 Parameters.push_back(Parameter);
3523 if (getLexer().is(AsmToken::Comma))
3525 else if (getLexer().is(AsmToken::EndOfStatement))
3530 // Eat the end of statement.
3533 AsmToken EndToken, StartToken = getTok();
3535 // Lex the macro definition.
3537 // Check whether we have reached the end of the file.
3538 if (getLexer().is(AsmToken::Eof))
3539 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3541 // Otherwise, check whether we have reach the .endmacro.
3542 if (getLexer().is(AsmToken::Identifier) &&
3543 (getTok().getIdentifier() == ".endm" ||
3544 getTok().getIdentifier() == ".endmacro")) {
3545 EndToken = getTok();
3547 if (getLexer().isNot(AsmToken::EndOfStatement))
3548 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3553 // Otherwise, scan til the end of the statement.
3554 getParser().EatToEndOfStatement();
3557 if (getParser().LookupMacro(Name)) {
3558 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3561 const char *BodyStart = StartToken.getLoc().getPointer();
3562 const char *BodyEnd = EndToken.getLoc().getPointer();
3563 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3564 getParser().DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3568 /// ParseDirectiveEndMacro
3571 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3572 SMLoc DirectiveLoc) {
3573 if (getLexer().isNot(AsmToken::EndOfStatement))
3574 return TokError("unexpected token in '" + Directive + "' directive");
3576 // If we are inside a macro instantiation, terminate the current
3578 if (getParser().InsideMacroInstantiation()) {
3579 getParser().HandleMacroExit();
3583 // Otherwise, this .endmacro is a stray entry in the file; well formed
3584 // .endmacro directives are handled during the macro definition parsing.
3585 return TokError("unexpected '" + Directive + "' in file, "
3586 "no current macro definition");
3589 /// ParseDirectivePurgeMacro
3591 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3592 SMLoc DirectiveLoc) {
3594 if (getParser().ParseIdentifier(Name))
3595 return TokError("expected identifier in '.purgem' directive");
3597 if (getLexer().isNot(AsmToken::EndOfStatement))
3598 return TokError("unexpected token in '.purgem' directive");
3600 if (!getParser().LookupMacro(Name))
3601 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3603 getParser().UndefineMacro(Name);
3607 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3608 getParser().CheckForValidSection();
3610 const MCExpr *Value;
3612 if (getParser().ParseExpression(Value))
3615 if (getLexer().isNot(AsmToken::EndOfStatement))
3616 return TokError("unexpected token in directive");
3618 if (DirName[1] == 's')
3619 getStreamer().EmitSLEB128Value(Value);
3621 getStreamer().EmitULEB128Value(Value);
3626 MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3627 AsmToken EndToken, StartToken = getTok();
3629 unsigned NestLevel = 0;
3631 // Check whether we have reached the end of the file.
3632 if (getLexer().is(AsmToken::Eof)) {
3633 Error(DirectiveLoc, "no matching '.endr' in definition");
3637 if (Lexer.is(AsmToken::Identifier) &&
3638 (getTok().getIdentifier() == ".rept")) {
3642 // Otherwise, check whether we have reached the .endr.
3643 if (Lexer.is(AsmToken::Identifier) &&
3644 getTok().getIdentifier() == ".endr") {
3645 if (NestLevel == 0) {
3646 EndToken = getTok();
3648 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3649 TokError("unexpected token in '.endr' directive");
3657 // Otherwise, scan till the end of the statement.
3658 EatToEndOfStatement();
3661 const char *BodyStart = StartToken.getLoc().getPointer();
3662 const char *BodyEnd = EndToken.getLoc().getPointer();
3663 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3665 // We Are Anonymous.
3667 MCAsmMacroParameters Parameters;
3668 return new MCAsmMacro(Name, Body, Parameters);
3671 void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
3672 raw_svector_ostream &OS) {
3675 MemoryBuffer *Instantiation =
3676 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3678 // Create the macro instantiation object and add to the current macro
3679 // instantiation stack.
3680 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3684 ActiveMacros.push_back(MI);
3686 // Jump to the macro instantiation and prime the lexer.
3687 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3688 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3692 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3694 if (ParseAbsoluteExpression(Count))
3695 return TokError("unexpected token in '.rept' directive");
3698 return TokError("Count is negative");
3700 if (Lexer.isNot(AsmToken::EndOfStatement))
3701 return TokError("unexpected token in '.rept' directive");
3703 // Eat the end of statement.
3706 // Lex the rept definition.
3707 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3711 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3712 // to hold the macro body with substitutions.
3713 SmallString<256> Buf;
3714 MCAsmMacroParameters Parameters;
3715 MCAsmMacroArguments A;
3716 raw_svector_ostream OS(Buf);
3718 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3721 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3726 /// ParseDirectiveIrp
3727 /// ::= .irp symbol,values
3728 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3729 MCAsmMacroParameters Parameters;
3730 MCAsmMacroParameter Parameter;
3732 if (ParseIdentifier(Parameter.first))
3733 return TokError("expected identifier in '.irp' directive");
3735 Parameters.push_back(Parameter);
3737 if (Lexer.isNot(AsmToken::Comma))
3738 return TokError("expected comma in '.irp' directive");
3742 MCAsmMacroArguments A;
3743 if (ParseMacroArguments(0, A))
3746 // Eat the end of statement.
3749 // Lex the irp definition.
3750 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3754 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3755 // to hold the macro body with substitutions.
3756 SmallString<256> Buf;
3757 raw_svector_ostream OS(Buf);
3759 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3760 MCAsmMacroArguments Args;
3763 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3767 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3772 /// ParseDirectiveIrpc
3773 /// ::= .irpc symbol,values
3774 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3775 MCAsmMacroParameters Parameters;
3776 MCAsmMacroParameter Parameter;
3778 if (ParseIdentifier(Parameter.first))
3779 return TokError("expected identifier in '.irpc' directive");
3781 Parameters.push_back(Parameter);
3783 if (Lexer.isNot(AsmToken::Comma))
3784 return TokError("expected comma in '.irpc' directive");
3788 MCAsmMacroArguments A;
3789 if (ParseMacroArguments(0, A))
3792 if (A.size() != 1 || A.front().size() != 1)
3793 return TokError("unexpected token in '.irpc' directive");
3795 // Eat the end of statement.
3798 // Lex the irpc definition.
3799 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3803 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3804 // to hold the macro body with substitutions.
3805 SmallString<256> Buf;
3806 raw_svector_ostream OS(Buf);
3808 StringRef Values = A.front().front().getString();
3809 std::size_t I, End = Values.size();
3810 for (I = 0; I < End; ++I) {
3811 MCAsmMacroArgument Arg;
3812 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3814 MCAsmMacroArguments Args;
3815 Args.push_back(Arg);
3817 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3821 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3826 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3827 if (ActiveMacros.empty())
3828 return TokError("unmatched '.endr' directive");
3830 // The only .repl that should get here are the ones created by
3831 // InstantiateMacroLikeBody.
3832 assert(getLexer().is(AsmToken::EndOfStatement));
3838 bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3839 const MCExpr *Value;
3840 SMLoc ExprLoc = getLexer().getLoc();
3841 if (ParseExpression(Value))
3843 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3845 return Error(ExprLoc, "unexpected expression in _emit");
3846 uint64_t IntValue = MCE->getValue();
3847 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3848 return Error(ExprLoc, "literal value out of range for directive");
3850 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3854 bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3855 unsigned &NumOutputs, unsigned &NumInputs,
3856 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
3857 SmallVectorImpl<std::string> &Constraints,
3858 SmallVectorImpl<std::string> &Clobbers,
3859 const MCInstrInfo *MII,
3860 const MCInstPrinter *IP,
3861 MCAsmParserSemaCallback &SI) {
3862 SmallVector<void *, 4> InputDecls;
3863 SmallVector<void *, 4> OutputDecls;
3864 SmallVector<bool, 4> InputDeclsAddressOf;
3865 SmallVector<bool, 4> OutputDeclsAddressOf;
3866 SmallVector<std::string, 4> InputConstraints;
3867 SmallVector<std::string, 4> OutputConstraints;
3868 std::set<std::string> ClobberRegs;
3870 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
3875 // While we have input, parse each statement.
3876 unsigned InputIdx = 0;
3877 unsigned OutputIdx = 0;
3878 while (getLexer().isNot(AsmToken::Eof)) {
3879 ParseStatementInfo Info(&AsmStrRewrites);
3880 if (ParseStatement(Info))
3883 if (Info.ParseError)
3886 if (Info.Opcode != ~0U) {
3887 const MCInstrDesc &Desc = MII->get(Info.Opcode);
3889 // Build the list of clobbers, outputs and inputs.
3890 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3891 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
3894 if (Operand->isImm()) {
3895 if (Operand->needAsmRewrite())
3896 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3897 Operand->getStartLoc()));
3901 // Register operand.
3902 if (Operand->isReg() && !Operand->needAddressOf()) {
3903 unsigned NumDefs = Desc.getNumDefs();
3905 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3907 raw_string_ostream OS(Reg);
3908 IP->printRegName(OS, Operand->getReg());
3909 ClobberRegs.insert(StringRef(OS.str()));
3914 // Expr/Input or Output.
3917 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3920 bool isOutput = (i == 1) && Desc.mayStore();
3921 if (Operand->isMem() && Operand->needSizeDirective())
3922 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
3923 Operand->getStartLoc(),
3925 Operand->getMemSize()));
3927 std::string Constraint = "=";
3929 OutputDecls.push_back(OpDecl);
3930 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
3931 Constraint += Operand->getConstraint().str();
3932 OutputConstraints.push_back(Constraint);
3933 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
3934 Operand->getStartLoc(),
3935 Operand->getNameLen()));
3937 InputDecls.push_back(OpDecl);
3938 InputDeclsAddressOf.push_back(Operand->needAddressOf());
3939 InputConstraints.push_back(Operand->getConstraint().str());
3940 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
3941 Operand->getStartLoc(),
3942 Operand->getNameLen()));
3949 // Set the number of Outputs and Inputs.
3950 NumOutputs = OutputDecls.size();
3951 NumInputs = InputDecls.size();
3953 // Set the unique clobbers.
3954 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3955 E = ClobberRegs.end(); I != E; ++I)
3956 Clobbers.push_back(*I);
3958 // Merge the various outputs and inputs. Output are expected first.
3959 if (NumOutputs || NumInputs) {
3960 unsigned NumExprs = NumOutputs + NumInputs;
3961 OpDecls.resize(NumExprs);
3962 Constraints.resize(NumExprs);
3963 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3964 // constraint for addressof. This needs to be cleaned up!
3965 for (unsigned i = 0; i < NumOutputs; ++i) {
3966 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
3967 Constraints[i] = OutputDeclsAddressOf[i] ? "=r" : OutputConstraints[i];
3969 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
3970 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
3971 Constraints[j] = InputDeclsAddressOf[i] ? "r" : InputConstraints[i];
3975 // Build the IR assembly string.
3976 std::string AsmStringIR;
3977 AsmRewriteKind PrevKind = AOK_Imm;
3978 raw_string_ostream OS(AsmStringIR);
3979 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
3980 for (SmallVectorImpl<struct AsmRewrite>::iterator
3981 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3982 const char *Loc = (*I).Loc.getPointer();
3984 AsmRewriteKind Kind = (*I).Kind;
3986 // Emit everything up to the immediate/expression. If the previous rewrite
3987 // was a size directive, then this has already been done.
3988 if (PrevKind != AOK_SizeDirective)
3989 OS << StringRef(Start, Loc - Start);
3992 // Skip the original expression.
3993 if (Kind == AOK_Skip) {
3994 Start = Loc + (*I).Len;
3998 // Rewrite expressions in $N notation.
4016 case AOK_SizeDirective:
4019 case 8: OS << "byte ptr "; break;
4020 case 16: OS << "word ptr "; break;
4021 case 32: OS << "dword ptr "; break;
4022 case 64: OS << "qword ptr "; break;
4023 case 80: OS << "xword ptr "; break;
4024 case 128: OS << "xmmword ptr "; break;
4025 case 256: OS << "ymmword ptr "; break;
4031 case AOK_DotOperator:
4036 // Skip the original expression.
4037 if (Kind != AOK_SizeDirective)
4038 Start = Loc + (*I).Len;
4041 // Emit the remainder of the asm string.
4042 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4043 if (Start != AsmEnd)
4044 OS << StringRef(Start, AsmEnd - Start);
4046 AsmString = OS.str();
4050 /// \brief Create an MCAsmParser instance.
4051 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
4052 MCContext &C, MCStreamer &Out,
4053 const MCAsmInfo &MAI) {
4054 return new AsmParser(SM, C, Out, MAI);