1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCDwarf.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInstPrinter.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCParser/AsmCond.h"
25 #include "llvm/MC/MCParser/AsmLexer.h"
26 #include "llvm/MC/MCParser/MCAsmParser.h"
27 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSectionMachO.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/MC/MCTargetAsmParser.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/raw_ostream.h"
46 FatalAssemblerWarnings("fatal-assembler-warnings",
47 cl::desc("Consider warnings as error"));
49 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
53 /// \brief Helper types for tracking macro definitions.
54 typedef std::vector<AsmToken> MCAsmMacroArgument;
55 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
56 typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
57 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
62 MCAsmMacroParameters Parameters;
65 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
66 Name(N), Body(B), Parameters(P) {}
68 MCAsmMacro(const MCAsmMacro& Other)
69 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
72 /// \brief Helper class for storing information about an active macro
74 struct MacroInstantiation {
75 /// The macro being instantiated.
76 const MCAsmMacro *TheMacro;
78 /// The macro instantiation with substitutions.
79 MemoryBuffer *Instantiation;
81 /// The location of the instantiation.
82 SMLoc InstantiationLoc;
84 /// The buffer where parsing should resume upon instantiation completion.
87 /// The location where parsing should resume upon instantiation completion.
91 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
95 struct ParseStatementInfo {
96 /// ParsedOperands - The parsed operands from the last parsed statement.
97 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
99 /// Opcode - The opcode from the last parsed instruction.
102 /// Error - Was there an error parsing the inline assembly?
105 SmallVectorImpl<AsmRewrite> *AsmRewrites;
107 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
108 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
109 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
111 ~ParseStatementInfo() {
112 // Free any parsed operands.
113 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
114 delete ParsedOperands[i];
115 ParsedOperands.clear();
119 /// \brief The concrete assembly parser instance.
120 class AsmParser : public MCAsmParser {
121 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
122 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
127 const MCAsmInfo &MAI;
129 SourceMgr::DiagHandlerTy SavedDiagHandler;
130 void *SavedDiagContext;
131 MCAsmParserExtension *PlatformParser;
133 /// This is the current buffer index we're lexing from as managed by the
134 /// SourceMgr object.
137 AsmCond TheCondState;
138 std::vector<AsmCond> TheCondStack;
140 /// ExtensionDirectiveMap - maps directive names to handler methods in parser
141 /// extensions. Extensions register themselves in this map by calling
142 /// AddDirectiveHandler.
143 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
145 /// MacroMap - Map of currently defined macros.
146 StringMap<MCAsmMacro*> MacroMap;
148 /// ActiveMacros - Stack of active macro instantiations.
149 std::vector<MacroInstantiation*> ActiveMacros;
151 /// Boolean tracking whether macro substitution is enabled.
152 unsigned MacrosEnabledFlag : 1;
154 /// Flag tracking whether any errors have been encountered.
155 unsigned HadError : 1;
157 /// The values from the last parsed cpp hash file line comment if any.
158 StringRef CppHashFilename;
159 int64_t CppHashLineNumber;
163 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
164 unsigned AssemblerDialect;
166 /// IsDarwin - is Darwin compatibility enabled?
169 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
170 bool ParsingInlineAsm;
173 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
174 const MCAsmInfo &MAI);
175 virtual ~AsmParser();
177 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
179 virtual void AddDirectiveHandler(StringRef Directive,
180 ExtensionDirectiveHandler Handler) {
181 ExtensionDirectiveMap[Directive] = Handler;
185 /// @name MCAsmParser Interface
188 virtual SourceMgr &getSourceManager() { return SrcMgr; }
189 virtual MCAsmLexer &getLexer() { return Lexer; }
190 virtual MCContext &getContext() { return Ctx; }
191 virtual MCStreamer &getStreamer() { return Out; }
192 virtual unsigned getAssemblerDialect() {
193 if (AssemblerDialect == ~0U)
194 return MAI.getAssemblerDialect();
196 return AssemblerDialect;
198 virtual void setAssemblerDialect(unsigned i) {
199 AssemblerDialect = i;
202 virtual bool Warning(SMLoc L, const Twine &Msg,
203 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
204 virtual bool Error(SMLoc L, const Twine &Msg,
205 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
207 virtual const AsmToken &Lex();
209 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
210 bool isParsingInlineAsm() { return ParsingInlineAsm; }
212 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
213 unsigned &NumOutputs, unsigned &NumInputs,
214 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
215 SmallVectorImpl<std::string> &Constraints,
216 SmallVectorImpl<std::string> &Clobbers,
217 const MCInstrInfo *MII,
218 const MCInstPrinter *IP,
219 MCAsmParserSemaCallback &SI);
221 bool ParseExpression(const MCExpr *&Res);
222 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
223 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
224 virtual bool ParseAbsoluteExpression(int64_t &Res);
226 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
227 /// and set \p Res to the identifier contents.
228 virtual bool ParseIdentifier(StringRef &Res);
229 virtual void EatToEndOfStatement();
231 virtual void CheckForValidSection();
236 bool ParseStatement(ParseStatementInfo &Info);
237 void EatToEndOfLine();
238 bool ParseCppHashLineFilenameComment(const SMLoc &L);
240 void CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
241 MCAsmMacroParameters Parameters);
242 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
243 const MCAsmMacroParameters &Parameters,
244 const MCAsmMacroArguments &A,
247 /// \brief Are macros enabled in the parser?
248 bool MacrosEnabled() {return MacrosEnabledFlag;}
250 /// \brief Control a flag in the parser that enables or disables macros.
251 void SetMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
253 /// \brief Lookup a previously defined macro.
254 /// \param Name Macro name.
255 /// \returns Pointer to macro. NULL if no such macro was defined.
256 const MCAsmMacro* LookupMacro(StringRef Name);
258 /// \brief Define a new macro with the given name and information.
259 void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
261 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
262 void UndefineMacro(StringRef Name);
264 /// \brief Are we inside a macro instantiation?
265 bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
267 /// \brief Handle entry to macro instantiation.
269 /// \param M The macro.
270 /// \param NameLoc Instantiation location.
271 bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
273 /// \brief Handle exit from macro instantiation.
274 void HandleMacroExit();
276 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
277 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
278 /// correct delimiter by the method.
279 bool ParseMacroArgument(MCAsmMacroArgument &MA,
280 AsmToken::TokenKind &ArgumentDelimiter);
282 /// \brief Parse all macro arguments for a given macro.
283 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
285 void PrintMacroInstantiations();
286 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
287 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
288 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
290 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
292 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
293 bool EnterIncludeFile(const std::string &Filename);
294 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
295 /// This returns true on failure.
296 bool ProcessIncbinFile(const std::string &Filename);
298 /// \brief Reset the current lexer position to that given by \p Loc. The
299 /// current token is not set; clients should ensure Lex() is called
302 /// \param InBuffer If not -1, should be the known buffer id that contains the
304 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
306 /// \brief Parse up to the end of statement and a return the contents from the
307 /// current token until the end of the statement; the current token on exit
308 /// will be either the EndOfStatement or EOF.
309 virtual StringRef ParseStringToEndOfStatement();
311 /// \brief Parse until the end of a statement or a comma is encountered,
312 /// return the contents from the current token up to the end or comma.
313 StringRef ParseStringToComma();
315 bool ParseAssignment(StringRef Name, bool allow_redef,
316 bool NoDeadStrip = false);
318 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
319 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
320 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
321 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
323 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
325 // Generic (target and platform independent) directive parsing.
327 DK_NO_DIRECTIVE, // Placeholder
328 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
329 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
330 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
331 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
332 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
333 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
334 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
335 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
336 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
337 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
338 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
339 DK_ELSEIF, DK_ELSE, DK_ENDIF,
340 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
341 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
342 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
343 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
344 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
345 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
347 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
348 DK_SLEB128, DK_ULEB128
351 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
352 /// directives parsed by this class.
353 StringMap<DirectiveKind> DirectiveKindMap;
355 // ".ascii", ".asciz", ".string"
356 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
357 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
358 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
359 bool ParseDirectiveFill(); // ".fill"
360 bool ParseDirectiveZero(); // ".zero"
361 // ".set", ".equ", ".equiv"
362 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
363 bool ParseDirectiveOrg(); // ".org"
364 // ".align{,32}", ".p2align{,w,l}"
365 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
367 // ".file", ".line", ".loc", ".stabs"
368 bool ParseDirectiveFile(SMLoc DirectiveLoc);
369 bool ParseDirectiveLine();
370 bool ParseDirectiveLoc();
371 bool ParseDirectiveStabs();
374 bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
375 bool ParseDirectiveCFISections();
376 bool ParseDirectiveCFIStartProc();
377 bool ParseDirectiveCFIEndProc();
378 bool ParseDirectiveCFIDefCfaOffset();
379 bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
380 bool ParseDirectiveCFIAdjustCfaOffset();
381 bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
382 bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
383 bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
384 bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
385 bool ParseDirectiveCFIRememberState();
386 bool ParseDirectiveCFIRestoreState();
387 bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
388 bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
389 bool ParseDirectiveCFIEscape();
390 bool ParseDirectiveCFISignalFrame();
391 bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
394 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
395 bool ParseDirectiveEndMacro(StringRef Directive);
396 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
397 bool ParseDirectiveMacrosOnOff(StringRef Directive);
399 // ".bundle_align_mode"
400 bool ParseDirectiveBundleAlignMode();
402 bool ParseDirectiveBundleLock();
404 bool ParseDirectiveBundleUnlock();
407 bool ParseDirectiveSpace(StringRef IDVal);
409 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
410 bool ParseDirectiveLEB128(bool Signed);
412 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
413 /// accepts a single symbol (which should be a label or an external).
414 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
416 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
418 bool ParseDirectiveAbort(); // ".abort"
419 bool ParseDirectiveInclude(); // ".include"
420 bool ParseDirectiveIncbin(); // ".incbin"
422 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
423 // ".ifb" or ".ifnb", depending on ExpectBlank.
424 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
425 // ".ifc" or ".ifnc", depending on ExpectEqual.
426 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
427 // ".ifdef" or ".ifndef", depending on expect_defined
428 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
429 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
430 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
431 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
432 virtual bool ParseEscapedString(std::string &Data);
434 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
435 MCSymbolRefExpr::VariantKind Variant);
437 // Macro-like directives
438 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
439 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
440 raw_svector_ostream &OS);
441 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
442 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
443 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
444 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
446 // "_emit" or "__emit"
447 bool ParseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
451 bool ParseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
453 void initializeDirectiveKindMap();
459 extern MCAsmParserExtension *createDarwinAsmParser();
460 extern MCAsmParserExtension *createELFAsmParser();
461 extern MCAsmParserExtension *createCOFFAsmParser();
465 enum { DEFAULT_ADDRSPACE = 0 };
467 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
468 MCStreamer &_Out, const MCAsmInfo &_MAI)
469 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
471 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
472 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
473 // Save the old handler.
474 SavedDiagHandler = SrcMgr.getDiagHandler();
475 SavedDiagContext = SrcMgr.getDiagContext();
476 // Set our own handler which calls the saved handler.
477 SrcMgr.setDiagHandler(DiagHandler, this);
478 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
480 // Initialize the platform / file format parser.
482 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
484 if (_MAI.hasMicrosoftFastStdCallMangling()) {
485 PlatformParser = createCOFFAsmParser();
486 PlatformParser->Initialize(*this);
487 } else if (_MAI.hasSubsectionsViaSymbols()) {
488 PlatformParser = createDarwinAsmParser();
489 PlatformParser->Initialize(*this);
492 PlatformParser = createELFAsmParser();
493 PlatformParser->Initialize(*this);
496 initializeDirectiveKindMap();
499 AsmParser::~AsmParser() {
500 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
502 // Destroy any macros.
503 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
504 ie = MacroMap.end(); it != ie; ++it)
505 delete it->getValue();
507 delete PlatformParser;
510 void AsmParser::PrintMacroInstantiations() {
511 // Print the active macro instantiation stack.
512 for (std::vector<MacroInstantiation*>::const_reverse_iterator
513 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
514 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
515 "while in macro instantiation");
518 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
519 if (FatalAssemblerWarnings)
520 return Error(L, Msg, Ranges);
521 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
522 PrintMacroInstantiations();
526 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
528 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
529 PrintMacroInstantiations();
533 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
534 std::string IncludedFile;
535 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
541 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
546 /// Process the specified .incbin file by seaching for it in the include paths
547 /// then just emitting the byte contents of the file to the streamer. This
548 /// returns true on failure.
549 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
550 std::string IncludedFile;
551 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
555 // Pick up the bytes from the file and emit them.
556 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
561 void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
562 if (InBuffer != -1) {
563 CurBuffer = InBuffer;
565 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
567 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
570 const AsmToken &AsmParser::Lex() {
571 const AsmToken *tok = &Lexer.Lex();
573 if (tok->is(AsmToken::Eof)) {
574 // If this is the end of an included file, pop the parent file off the
576 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
577 if (ParentIncludeLoc != SMLoc()) {
578 JumpToLoc(ParentIncludeLoc);
583 if (tok->is(AsmToken::Error))
584 Error(Lexer.getErrLoc(), Lexer.getErr());
589 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
590 // Create the initial section, if requested.
591 if (!NoInitialTextSection)
598 AsmCond StartingCondState = TheCondState;
600 // If we are generating dwarf for assembly source files save the initial text
601 // section and generate a .file directive.
602 if (getContext().getGenDwarfForAssembly()) {
603 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
604 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
605 getStreamer().EmitLabel(SectionStartSym);
606 getContext().setGenDwarfSectionStartSym(SectionStartSym);
607 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
609 getContext().getMainFileName());
612 // While we have input, parse each statement.
613 while (Lexer.isNot(AsmToken::Eof)) {
614 ParseStatementInfo Info;
615 if (!ParseStatement(Info)) continue;
617 // We had an error, validate that one was emitted and recover by skipping to
619 assert(HadError && "Parse statement returned an error, but none emitted!");
620 EatToEndOfStatement();
623 if (TheCondState.TheCond != StartingCondState.TheCond ||
624 TheCondState.Ignore != StartingCondState.Ignore)
625 return TokError("unmatched .ifs or .elses");
627 // Check to see there are no empty DwarfFile slots.
628 const std::vector<MCDwarfFile *> &MCDwarfFiles =
629 getContext().getMCDwarfFiles();
630 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
631 if (!MCDwarfFiles[i])
632 TokError("unassigned file number: " + Twine(i) + " for .file directives");
635 // Check to see that all assembler local symbols were actually defined.
636 // Targets that don't do subsections via symbols may not want this, though,
637 // so conservatively exclude them. Only do this if we're finalizing, though,
638 // as otherwise we won't necessarilly have seen everything yet.
639 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
640 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
641 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
644 MCSymbol *Sym = i->getValue();
645 // Variable symbols may not be marked as defined, so check those
646 // explicitly. If we know it's a variable, we have a definition for
647 // the purposes of this check.
648 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
649 // FIXME: We would really like to refer back to where the symbol was
650 // first referenced for a source location. We need to add something
651 // to track that. Currently, we just point to the end of the file.
652 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
653 "assembler local symbol '" + Sym->getName() +
659 // Finalize the output stream if there are no errors and if the client wants
661 if (!HadError && !NoFinalize)
667 void AsmParser::CheckForValidSection() {
668 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
669 TokError("expected section directive before assembly directive");
670 Out.InitToTextSection();
674 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
675 void AsmParser::EatToEndOfStatement() {
676 while (Lexer.isNot(AsmToken::EndOfStatement) &&
677 Lexer.isNot(AsmToken::Eof))
681 if (Lexer.is(AsmToken::EndOfStatement))
685 StringRef AsmParser::ParseStringToEndOfStatement() {
686 const char *Start = getTok().getLoc().getPointer();
688 while (Lexer.isNot(AsmToken::EndOfStatement) &&
689 Lexer.isNot(AsmToken::Eof))
692 const char *End = getTok().getLoc().getPointer();
693 return StringRef(Start, End - Start);
696 StringRef AsmParser::ParseStringToComma() {
697 const char *Start = getTok().getLoc().getPointer();
699 while (Lexer.isNot(AsmToken::EndOfStatement) &&
700 Lexer.isNot(AsmToken::Comma) &&
701 Lexer.isNot(AsmToken::Eof))
704 const char *End = getTok().getLoc().getPointer();
705 return StringRef(Start, End - Start);
708 /// ParseParenExpr - Parse a paren expression and return it.
709 /// NOTE: This assumes the leading '(' has already been consumed.
711 /// parenexpr ::= expr)
713 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
714 if (ParseExpression(Res)) return true;
715 if (Lexer.isNot(AsmToken::RParen))
716 return TokError("expected ')' in parentheses expression");
717 EndLoc = Lexer.getTok().getEndLoc();
722 /// ParseBracketExpr - Parse a bracket expression and return it.
723 /// NOTE: This assumes the leading '[' has already been consumed.
725 /// bracketexpr ::= expr]
727 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
728 if (ParseExpression(Res)) return true;
729 if (Lexer.isNot(AsmToken::RBrac))
730 return TokError("expected ']' in brackets expression");
731 EndLoc = Lexer.getTok().getEndLoc();
736 /// ParsePrimaryExpr - Parse a primary expression and return it.
737 /// primaryexpr ::= (parenexpr
738 /// primaryexpr ::= symbol
739 /// primaryexpr ::= number
740 /// primaryexpr ::= '.'
741 /// primaryexpr ::= ~,+,- primaryexpr
742 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
743 SMLoc FirstTokenLoc = getLexer().getLoc();
744 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
745 switch (FirstTokenKind) {
747 return TokError("unknown token in expression");
748 // If we have an error assume that we've already handled it.
749 case AsmToken::Error:
751 case AsmToken::Exclaim:
752 Lex(); // Eat the operator.
753 if (ParsePrimaryExpr(Res, EndLoc))
755 Res = MCUnaryExpr::CreateLNot(Res, getContext());
757 case AsmToken::Dollar:
758 case AsmToken::String:
759 case AsmToken::Identifier: {
760 StringRef Identifier;
761 if (ParseIdentifier(Identifier)) {
762 if (FirstTokenKind == AsmToken::Dollar)
763 return Error(FirstTokenLoc, "invalid token in expression");
767 EndLoc = SMLoc::getFromPointer(Identifier.end());
769 // This is a symbol reference.
770 std::pair<StringRef, StringRef> Split = Identifier.split('@');
771 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
773 // Lookup the symbol variant if used.
774 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
775 if (Split.first.size() != Identifier.size()) {
776 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
777 if (Variant == MCSymbolRefExpr::VK_Invalid) {
778 Variant = MCSymbolRefExpr::VK_None;
779 return TokError("invalid variant '" + Split.second + "'");
783 // If this is an absolute variable reference, substitute it now to preserve
784 // semantics in the face of reassignment.
785 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
787 return Error(EndLoc, "unexpected modifier on variable reference");
789 Res = Sym->getVariableValue();
793 // Otherwise create a symbol ref.
794 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
797 case AsmToken::Integer: {
798 SMLoc Loc = getTok().getLoc();
799 int64_t IntVal = getTok().getIntVal();
800 Res = MCConstantExpr::Create(IntVal, getContext());
801 EndLoc = Lexer.getTok().getEndLoc();
803 // Look for 'b' or 'f' following an Integer as a directional label
804 if (Lexer.getKind() == AsmToken::Identifier) {
805 StringRef IDVal = getTok().getString();
806 if (IDVal == "f" || IDVal == "b"){
807 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
808 IDVal == "f" ? 1 : 0);
809 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
811 if (IDVal == "b" && Sym->isUndefined())
812 return Error(Loc, "invalid reference to undefined symbol");
813 EndLoc = Lexer.getTok().getEndLoc();
814 Lex(); // Eat identifier.
819 case AsmToken::Real: {
820 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
821 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
822 Res = MCConstantExpr::Create(IntVal, getContext());
823 EndLoc = Lexer.getTok().getEndLoc();
827 case AsmToken::Dot: {
828 // This is a '.' reference, which references the current PC. Emit a
829 // temporary label to the streamer and refer to it.
830 MCSymbol *Sym = Ctx.CreateTempSymbol();
832 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
833 EndLoc = Lexer.getTok().getEndLoc();
834 Lex(); // Eat identifier.
837 case AsmToken::LParen:
838 Lex(); // Eat the '('.
839 return ParseParenExpr(Res, EndLoc);
840 case AsmToken::LBrac:
841 if (!PlatformParser->HasBracketExpressions())
842 return TokError("brackets expression not supported on this target");
843 Lex(); // Eat the '['.
844 return ParseBracketExpr(Res, EndLoc);
845 case AsmToken::Minus:
846 Lex(); // Eat the operator.
847 if (ParsePrimaryExpr(Res, EndLoc))
849 Res = MCUnaryExpr::CreateMinus(Res, getContext());
852 Lex(); // Eat the operator.
853 if (ParsePrimaryExpr(Res, EndLoc))
855 Res = MCUnaryExpr::CreatePlus(Res, getContext());
857 case AsmToken::Tilde:
858 Lex(); // Eat the operator.
859 if (ParsePrimaryExpr(Res, EndLoc))
861 Res = MCUnaryExpr::CreateNot(Res, getContext());
866 bool AsmParser::ParseExpression(const MCExpr *&Res) {
868 return ParseExpression(Res, EndLoc);
872 AsmParser::ApplyModifierToExpr(const MCExpr *E,
873 MCSymbolRefExpr::VariantKind Variant) {
874 // Recurse over the given expression, rebuilding it to apply the given variant
875 // if there is exactly one symbol.
876 switch (E->getKind()) {
878 case MCExpr::Constant:
881 case MCExpr::SymbolRef: {
882 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
884 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
885 TokError("invalid variant on expression '" +
886 getTok().getIdentifier() + "' (already modified)");
890 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
893 case MCExpr::Unary: {
894 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
895 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
898 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
901 case MCExpr::Binary: {
902 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
903 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
904 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
909 if (!LHS) LHS = BE->getLHS();
910 if (!RHS) RHS = BE->getRHS();
912 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
916 llvm_unreachable("Invalid expression kind!");
919 /// ParseExpression - Parse an expression and return it.
921 /// expr ::= expr &&,|| expr -> lowest.
922 /// expr ::= expr |,^,&,! expr
923 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
924 /// expr ::= expr <<,>> expr
925 /// expr ::= expr +,- expr
926 /// expr ::= expr *,/,% expr -> highest.
927 /// expr ::= primaryexpr
929 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
930 // Parse the expression.
932 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
935 // As a special case, we support 'a op b @ modifier' by rewriting the
936 // expression to include the modifier. This is inefficient, but in general we
937 // expect users to use 'a@modifier op b'.
938 if (Lexer.getKind() == AsmToken::At) {
941 if (Lexer.isNot(AsmToken::Identifier))
942 return TokError("unexpected symbol modifier following '@'");
944 MCSymbolRefExpr::VariantKind Variant =
945 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
946 if (Variant == MCSymbolRefExpr::VK_Invalid)
947 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
949 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
951 return TokError("invalid modifier '" + getTok().getIdentifier() +
952 "' (no symbols present)");
959 // Try to constant fold it up front, if possible.
961 if (Res->EvaluateAsAbsolute(Value))
962 Res = MCConstantExpr::Create(Value, getContext());
967 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
969 return ParseParenExpr(Res, EndLoc) ||
970 ParseBinOpRHS(1, Res, EndLoc);
973 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
976 SMLoc StartLoc = Lexer.getLoc();
977 if (ParseExpression(Expr))
980 if (!Expr->EvaluateAsAbsolute(Res))
981 return Error(StartLoc, "expected absolute expression");
986 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
987 MCBinaryExpr::Opcode &Kind) {
990 return 0; // not a binop.
992 // Lowest Precedence: &&, ||
993 case AsmToken::AmpAmp:
994 Kind = MCBinaryExpr::LAnd;
996 case AsmToken::PipePipe:
997 Kind = MCBinaryExpr::LOr;
1001 // Low Precedence: |, &, ^
1003 // FIXME: gas seems to support '!' as an infix operator?
1004 case AsmToken::Pipe:
1005 Kind = MCBinaryExpr::Or;
1007 case AsmToken::Caret:
1008 Kind = MCBinaryExpr::Xor;
1011 Kind = MCBinaryExpr::And;
1014 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1015 case AsmToken::EqualEqual:
1016 Kind = MCBinaryExpr::EQ;
1018 case AsmToken::ExclaimEqual:
1019 case AsmToken::LessGreater:
1020 Kind = MCBinaryExpr::NE;
1022 case AsmToken::Less:
1023 Kind = MCBinaryExpr::LT;
1025 case AsmToken::LessEqual:
1026 Kind = MCBinaryExpr::LTE;
1028 case AsmToken::Greater:
1029 Kind = MCBinaryExpr::GT;
1031 case AsmToken::GreaterEqual:
1032 Kind = MCBinaryExpr::GTE;
1035 // Intermediate Precedence: <<, >>
1036 case AsmToken::LessLess:
1037 Kind = MCBinaryExpr::Shl;
1039 case AsmToken::GreaterGreater:
1040 Kind = MCBinaryExpr::Shr;
1043 // High Intermediate Precedence: +, -
1044 case AsmToken::Plus:
1045 Kind = MCBinaryExpr::Add;
1047 case AsmToken::Minus:
1048 Kind = MCBinaryExpr::Sub;
1051 // Highest Precedence: *, /, %
1052 case AsmToken::Star:
1053 Kind = MCBinaryExpr::Mul;
1055 case AsmToken::Slash:
1056 Kind = MCBinaryExpr::Div;
1058 case AsmToken::Percent:
1059 Kind = MCBinaryExpr::Mod;
1065 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1066 /// Res contains the LHS of the expression on input.
1067 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1070 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1071 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1073 // If the next token is lower precedence than we are allowed to eat, return
1074 // successfully with what we ate already.
1075 if (TokPrec < Precedence)
1080 // Eat the next primary expression.
1082 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1084 // If BinOp binds less tightly with RHS than the operator after RHS, let
1085 // the pending operator take RHS as its LHS.
1086 MCBinaryExpr::Opcode Dummy;
1087 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1088 if (TokPrec < NextTokPrec) {
1089 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1092 // Merge LHS and RHS according to operator.
1093 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1098 /// ::= EndOfStatement
1099 /// ::= Label* Directive ...Operands... EndOfStatement
1100 /// ::= Label* Identifier OperandList* EndOfStatement
1101 bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
1102 if (Lexer.is(AsmToken::EndOfStatement)) {
1108 // Statements always start with an identifier or are a full line comment.
1109 AsmToken ID = getTok();
1110 SMLoc IDLoc = ID.getLoc();
1112 int64_t LocalLabelVal = -1;
1113 // A full line comment is a '#' as the first token.
1114 if (Lexer.is(AsmToken::Hash))
1115 return ParseCppHashLineFilenameComment(IDLoc);
1117 // Allow an integer followed by a ':' as a directional local label.
1118 if (Lexer.is(AsmToken::Integer)) {
1119 LocalLabelVal = getTok().getIntVal();
1120 if (LocalLabelVal < 0) {
1121 if (!TheCondState.Ignore)
1122 return TokError("unexpected token at start of statement");
1125 IDVal = getTok().getString();
1126 Lex(); // Consume the integer token to be used as an identifier token.
1127 if (Lexer.getKind() != AsmToken::Colon) {
1128 if (!TheCondState.Ignore)
1129 return TokError("unexpected token at start of statement");
1132 } else if (Lexer.is(AsmToken::Dot)) {
1133 // Treat '.' as a valid identifier in this context.
1136 } else if (ParseIdentifier(IDVal)) {
1137 if (!TheCondState.Ignore)
1138 return TokError("unexpected token at start of statement");
1142 // Handle conditional assembly here before checking for skipping. We
1143 // have to do this so that .endif isn't skipped in a ".if 0" block for
1145 StringMap<DirectiveKind>::const_iterator DirKindIt =
1146 DirectiveKindMap.find(IDVal);
1147 DirectiveKind DirKind =
1148 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1149 DirKindIt->getValue();
1154 return ParseDirectiveIf(IDLoc);
1156 return ParseDirectiveIfb(IDLoc, true);
1158 return ParseDirectiveIfb(IDLoc, false);
1160 return ParseDirectiveIfc(IDLoc, true);
1162 return ParseDirectiveIfc(IDLoc, false);
1164 return ParseDirectiveIfdef(IDLoc, true);
1167 return ParseDirectiveIfdef(IDLoc, false);
1169 return ParseDirectiveElseIf(IDLoc);
1171 return ParseDirectiveElse(IDLoc);
1173 return ParseDirectiveEndIf(IDLoc);
1176 // Ignore the statement if in the middle of inactive conditional
1178 if (TheCondState.Ignore) {
1179 EatToEndOfStatement();
1183 // FIXME: Recurse on local labels?
1185 // See what kind of statement we have.
1186 switch (Lexer.getKind()) {
1187 case AsmToken::Colon: {
1188 CheckForValidSection();
1190 // identifier ':' -> Label.
1193 // Diagnose attempt to use '.' as a label.
1195 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1197 // Diagnose attempt to use a variable as a label.
1199 // FIXME: Diagnostics. Note the location of the definition as a label.
1200 // FIXME: This doesn't diagnose assignment to a symbol which has been
1201 // implicitly marked as external.
1203 if (LocalLabelVal == -1)
1204 Sym = getContext().GetOrCreateSymbol(IDVal);
1206 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1207 if (!Sym->isUndefined() || Sym->isVariable())
1208 return Error(IDLoc, "invalid symbol redefinition");
1211 if (!ParsingInlineAsm)
1214 // If we are generating dwarf for assembly source files then gather the
1215 // info to make a dwarf label entry for this label if needed.
1216 if (getContext().getGenDwarfForAssembly())
1217 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1220 // Consume any end of statement token, if present, to avoid spurious
1221 // AddBlankLine calls().
1222 if (Lexer.is(AsmToken::EndOfStatement)) {
1224 if (Lexer.is(AsmToken::Eof))
1231 case AsmToken::Equal:
1232 // identifier '=' ... -> assignment statement
1235 return ParseAssignment(IDVal, true);
1237 default: // Normal instruction or directive.
1241 // If macros are enabled, check to see if this is a macro instantiation.
1242 if (MacrosEnabled())
1243 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1244 return HandleMacroEntry(M, IDLoc);
1247 // Otherwise, we have a normal instruction or directive.
1249 // Directives start with "."
1250 if (IDVal[0] == '.' && IDVal != ".") {
1251 // There are several entities interested in parsing directives:
1253 // 1. The target-specific assembly parser. Some directives are target
1254 // specific or may potentially behave differently on certain targets.
1255 // 2. Asm parser extensions. For example, platform-specific parsers
1256 // (like the ELF parser) register themselves as extensions.
1257 // 3. The generic directive parser implemented by this class. These are
1258 // all the directives that behave in a target and platform independent
1259 // manner, or at least have a default behavior that's shared between
1260 // all targets and platforms.
1262 // First query the target-specific parser. It will return 'true' if it
1263 // isn't interested in this directive.
1264 if (!getTargetParser().ParseDirective(ID))
1267 // Next, check the extention directive map to see if any extension has
1268 // registered itself to parse this directive.
1269 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1270 ExtensionDirectiveMap.lookup(IDVal);
1272 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1274 // Finally, if no one else is interested in this directive, it must be
1275 // generic and familiar to this class.
1281 return ParseDirectiveSet(IDVal, true);
1283 return ParseDirectiveSet(IDVal, false);
1285 return ParseDirectiveAscii(IDVal, false);
1288 return ParseDirectiveAscii(IDVal, true);
1290 return ParseDirectiveValue(1);
1294 return ParseDirectiveValue(2);
1298 return ParseDirectiveValue(4);
1301 return ParseDirectiveValue(8);
1304 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1306 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1308 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1309 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1312 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1313 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1316 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1318 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1320 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1322 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1324 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1326 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1328 return ParseDirectiveOrg();
1330 return ParseDirectiveFill();
1332 return ParseDirectiveZero();
1334 EatToEndOfStatement(); // .extern is the default, ignore it.
1338 return ParseDirectiveSymbolAttribute(MCSA_Global);
1339 case DK_INDIRECT_SYMBOL:
1340 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1341 case DK_LAZY_REFERENCE:
1342 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1343 case DK_NO_DEAD_STRIP:
1344 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1345 case DK_SYMBOL_RESOLVER:
1346 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1347 case DK_PRIVATE_EXTERN:
1348 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1350 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1351 case DK_WEAK_DEFINITION:
1352 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1353 case DK_WEAK_REFERENCE:
1354 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1355 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1356 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1359 return ParseDirectiveComm(/*IsLocal=*/false);
1361 return ParseDirectiveComm(/*IsLocal=*/true);
1363 return ParseDirectiveAbort();
1365 return ParseDirectiveInclude();
1367 return ParseDirectiveIncbin();
1370 return TokError(Twine(IDVal) + " not supported yet");
1372 return ParseDirectiveRept(IDLoc);
1374 return ParseDirectiveIrp(IDLoc);
1376 return ParseDirectiveIrpc(IDLoc);
1378 return ParseDirectiveEndr(IDLoc);
1379 case DK_BUNDLE_ALIGN_MODE:
1380 return ParseDirectiveBundleAlignMode();
1381 case DK_BUNDLE_LOCK:
1382 return ParseDirectiveBundleLock();
1383 case DK_BUNDLE_UNLOCK:
1384 return ParseDirectiveBundleUnlock();
1386 return ParseDirectiveLEB128(true);
1388 return ParseDirectiveLEB128(false);
1391 return ParseDirectiveSpace(IDVal);
1393 return ParseDirectiveFile(IDLoc);
1395 return ParseDirectiveLine();
1397 return ParseDirectiveLoc();
1399 return ParseDirectiveStabs();
1400 case DK_CFI_SECTIONS:
1401 return ParseDirectiveCFISections();
1402 case DK_CFI_STARTPROC:
1403 return ParseDirectiveCFIStartProc();
1404 case DK_CFI_ENDPROC:
1405 return ParseDirectiveCFIEndProc();
1406 case DK_CFI_DEF_CFA:
1407 return ParseDirectiveCFIDefCfa(IDLoc);
1408 case DK_CFI_DEF_CFA_OFFSET:
1409 return ParseDirectiveCFIDefCfaOffset();
1410 case DK_CFI_ADJUST_CFA_OFFSET:
1411 return ParseDirectiveCFIAdjustCfaOffset();
1412 case DK_CFI_DEF_CFA_REGISTER:
1413 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1415 return ParseDirectiveCFIOffset(IDLoc);
1416 case DK_CFI_REL_OFFSET:
1417 return ParseDirectiveCFIRelOffset(IDLoc);
1418 case DK_CFI_PERSONALITY:
1419 return ParseDirectiveCFIPersonalityOrLsda(true);
1421 return ParseDirectiveCFIPersonalityOrLsda(false);
1422 case DK_CFI_REMEMBER_STATE:
1423 return ParseDirectiveCFIRememberState();
1424 case DK_CFI_RESTORE_STATE:
1425 return ParseDirectiveCFIRestoreState();
1426 case DK_CFI_SAME_VALUE:
1427 return ParseDirectiveCFISameValue(IDLoc);
1428 case DK_CFI_RESTORE:
1429 return ParseDirectiveCFIRestore(IDLoc);
1431 return ParseDirectiveCFIEscape();
1432 case DK_CFI_SIGNAL_FRAME:
1433 return ParseDirectiveCFISignalFrame();
1434 case DK_CFI_UNDEFINED:
1435 return ParseDirectiveCFIUndefined(IDLoc);
1436 case DK_CFI_REGISTER:
1437 return ParseDirectiveCFIRegister(IDLoc);
1440 return ParseDirectiveMacrosOnOff(IDVal);
1442 return ParseDirectiveMacro(IDLoc);
1445 return ParseDirectiveEndMacro(IDVal);
1447 return ParseDirectivePurgeMacro(IDLoc);
1450 return Error(IDLoc, "unknown directive");
1453 // __asm _emit or __asm __emit
1454 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1455 IDVal == "_EMIT" || IDVal == "__EMIT"))
1456 return ParseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1459 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1460 return ParseDirectiveMSAlign(IDLoc, Info);
1462 CheckForValidSection();
1464 // Canonicalize the opcode to lower case.
1465 std::string OpcodeStr = IDVal.lower();
1466 ParseInstructionInfo IInfo(Info.AsmRewrites);
1467 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
1468 IDLoc, Info.ParsedOperands);
1469 Info.ParseError = HadError;
1471 // Dump the parsed representation, if requested.
1472 if (getShowParsedOperands()) {
1473 SmallString<256> Str;
1474 raw_svector_ostream OS(Str);
1475 OS << "parsed instruction: [";
1476 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1479 Info.ParsedOperands[i]->print(OS);
1483 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1486 // If we are generating dwarf for assembly source files and the current
1487 // section is the initial text section then generate a .loc directive for
1489 if (!HadError && getContext().getGenDwarfForAssembly() &&
1490 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
1492 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1494 // If we previously parsed a cpp hash file line comment then make sure the
1495 // current Dwarf File is for the CppHashFilename if not then emit the
1496 // Dwarf File table for it and adjust the line number for the .loc.
1497 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1498 getContext().getMCDwarfFiles();
1499 if (CppHashFilename.size() != 0) {
1500 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1502 getStreamer().EmitDwarfFileDirective(
1503 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
1505 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
1506 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1509 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1510 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1511 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1515 // If parsing succeeded, match the instruction.
1518 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1519 Info.ParsedOperands,
1524 // Don't skip the rest of the line, the instruction parser is responsible for
1529 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1530 /// since they may not be able to be tokenized to get to the end of line token.
1531 void AsmParser::EatToEndOfLine() {
1532 if (!Lexer.is(AsmToken::EndOfStatement))
1533 Lexer.LexUntilEndOfLine();
1538 /// ParseCppHashLineFilenameComment as this:
1539 /// ::= # number "filename"
1540 /// or just as a full line comment if it doesn't have a number and a string.
1541 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1542 Lex(); // Eat the hash token.
1544 if (getLexer().isNot(AsmToken::Integer)) {
1545 // Consume the line since in cases it is not a well-formed line directive,
1546 // as if were simply a full line comment.
1551 int64_t LineNumber = getTok().getIntVal();
1554 if (getLexer().isNot(AsmToken::String)) {
1559 StringRef Filename = getTok().getString();
1560 // Get rid of the enclosing quotes.
1561 Filename = Filename.substr(1, Filename.size()-2);
1563 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1565 CppHashFilename = Filename;
1566 CppHashLineNumber = LineNumber;
1567 CppHashBuf = CurBuffer;
1569 // Ignore any trailing characters, they're just comment.
1574 /// DiagHandler - will use the last parsed cpp hash line filename comment
1575 /// for the Filename and LineNo if any in the diagnostic.
1576 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1577 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1578 raw_ostream &OS = errs();
1580 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1581 const SMLoc &DiagLoc = Diag.getLoc();
1582 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1583 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1585 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1586 // before printing the message.
1587 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1588 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1589 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1590 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1593 // If we have not parsed a cpp hash line filename comment or the source
1594 // manager changed or buffer changed (like in a nested include) then just
1595 // print the normal diagnostic using its Filename and LineNo.
1596 if (!Parser->CppHashLineNumber ||
1597 &DiagSrcMgr != &Parser->SrcMgr ||
1598 DiagBuf != CppHashBuf) {
1599 if (Parser->SavedDiagHandler)
1600 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1606 // Use the CppHashFilename and calculate a line number based on the
1607 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1609 const std::string Filename = Parser->CppHashFilename;
1611 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1612 int CppHashLocLineNo =
1613 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1614 int LineNo = Parser->CppHashLineNumber - 1 +
1615 (DiagLocLineNo - CppHashLocLineNo);
1617 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1618 Filename, LineNo, Diag.getColumnNo(),
1619 Diag.getKind(), Diag.getMessage(),
1620 Diag.getLineContents(), Diag.getRanges());
1622 if (Parser->SavedDiagHandler)
1623 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1625 NewDiag.print(0, OS);
1628 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1629 // difference being that that function accepts '@' as part of identifiers and
1630 // we can't do that. AsmLexer.cpp should probably be changed to handle
1631 // '@' as a special case when needed.
1632 static bool isIdentifierChar(char c) {
1633 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1637 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1638 const MCAsmMacroParameters &Parameters,
1639 const MCAsmMacroArguments &A,
1641 unsigned NParameters = Parameters.size();
1642 if (NParameters != 0 && NParameters != A.size())
1643 return Error(L, "Wrong number of arguments");
1645 // A macro without parameters is handled differently on Darwin:
1646 // gas accepts no arguments and does no substitutions
1647 while (!Body.empty()) {
1648 // Scan for the next substitution.
1649 std::size_t End = Body.size(), Pos = 0;
1650 for (; Pos != End; ++Pos) {
1651 // Check for a substitution or escape.
1653 // This macro has no parameters, look for $0, $1, etc.
1654 if (Body[Pos] != '$' || Pos + 1 == End)
1657 char Next = Body[Pos + 1];
1658 if (Next == '$' || Next == 'n' ||
1659 isdigit(static_cast<unsigned char>(Next)))
1662 // This macro has parameters, look for \foo, \bar, etc.
1663 if (Body[Pos] == '\\' && Pos + 1 != End)
1669 OS << Body.slice(0, Pos);
1671 // Check if we reached the end.
1676 switch (Body[Pos+1]) {
1682 // $n => number of arguments
1687 // $[0-9] => argument
1689 // Missing arguments are ignored.
1690 unsigned Index = Body[Pos+1] - '0';
1691 if (Index >= A.size())
1694 // Otherwise substitute with the token values, with spaces eliminated.
1695 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1696 ie = A[Index].end(); it != ie; ++it)
1697 OS << it->getString();
1703 unsigned I = Pos + 1;
1704 while (isIdentifierChar(Body[I]) && I + 1 != End)
1707 const char *Begin = Body.data() + Pos +1;
1708 StringRef Argument(Begin, I - (Pos +1));
1710 for (; Index < NParameters; ++Index)
1711 if (Parameters[Index].first == Argument)
1714 if (Index == NParameters) {
1715 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1718 OS << '\\' << Argument;
1722 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1723 ie = A[Index].end(); it != ie; ++it)
1724 if (it->getKind() == AsmToken::String)
1725 OS << it->getStringContents();
1727 OS << it->getString();
1729 Pos += 1 + Argument.size();
1732 // Update the scan point.
1733 Body = Body.substr(Pos);
1739 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
1742 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1747 static bool IsOperator(AsmToken::TokenKind kind)
1753 case AsmToken::Plus:
1754 case AsmToken::Minus:
1755 case AsmToken::Tilde:
1756 case AsmToken::Slash:
1757 case AsmToken::Star:
1759 case AsmToken::Equal:
1760 case AsmToken::EqualEqual:
1761 case AsmToken::Pipe:
1762 case AsmToken::PipePipe:
1763 case AsmToken::Caret:
1765 case AsmToken::AmpAmp:
1766 case AsmToken::Exclaim:
1767 case AsmToken::ExclaimEqual:
1768 case AsmToken::Percent:
1769 case AsmToken::Less:
1770 case AsmToken::LessEqual:
1771 case AsmToken::LessLess:
1772 case AsmToken::LessGreater:
1773 case AsmToken::Greater:
1774 case AsmToken::GreaterEqual:
1775 case AsmToken::GreaterGreater:
1780 bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
1781 AsmToken::TokenKind &ArgumentDelimiter) {
1782 unsigned ParenLevel = 0;
1783 unsigned AddTokens = 0;
1785 // gas accepts arguments separated by whitespace, except on Darwin
1787 Lexer.setSkipSpace(false);
1790 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1791 Lexer.setSkipSpace(true);
1792 return TokError("unexpected token in macro instantiation");
1795 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1796 // Spaces and commas cannot be mixed to delimit parameters
1797 if (ArgumentDelimiter == AsmToken::Eof)
1798 ArgumentDelimiter = AsmToken::Comma;
1799 else if (ArgumentDelimiter != AsmToken::Comma) {
1800 Lexer.setSkipSpace(true);
1801 return TokError("expected ' ' for macro argument separator");
1806 if (Lexer.is(AsmToken::Space)) {
1807 Lex(); // Eat spaces
1809 // Spaces can delimit parameters, but could also be part an expression.
1810 // If the token after a space is an operator, add the token and the next
1811 // one into this argument
1812 if (ArgumentDelimiter == AsmToken::Space ||
1813 ArgumentDelimiter == AsmToken::Eof) {
1814 if (IsOperator(Lexer.getKind())) {
1815 // Check to see whether the token is used as an operator,
1816 // or part of an identifier
1817 const char *NextChar = getTok().getEndLoc().getPointer();
1818 if (*NextChar == ' ')
1822 if (!AddTokens && ParenLevel == 0) {
1823 if (ArgumentDelimiter == AsmToken::Eof &&
1824 !IsOperator(Lexer.getKind()))
1825 ArgumentDelimiter = AsmToken::Space;
1831 // HandleMacroEntry relies on not advancing the lexer here
1832 // to be able to fill in the remaining default parameter values
1833 if (Lexer.is(AsmToken::EndOfStatement))
1836 // Adjust the current parentheses level.
1837 if (Lexer.is(AsmToken::LParen))
1839 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1842 // Append the token to the current argument list.
1843 MA.push_back(getTok());
1849 Lexer.setSkipSpace(true);
1850 if (ParenLevel != 0)
1851 return TokError("unbalanced parentheses in macro argument");
1855 // Parse the macro instantiation arguments.
1856 bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
1857 const unsigned NParameters = M ? M->Parameters.size() : 0;
1858 // Argument delimiter is initially unknown. It will be set by
1859 // ParseMacroArgument()
1860 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1862 // Parse two kinds of macro invocations:
1863 // - macros defined without any parameters accept an arbitrary number of them
1864 // - macros defined with parameters accept at most that many of them
1865 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1867 MCAsmMacroArgument MA;
1869 if (ParseMacroArgument(MA, ArgumentDelimiter))
1872 if (!MA.empty() || !NParameters)
1874 else if (NParameters) {
1875 if (!M->Parameters[Parameter].second.empty())
1876 A.push_back(M->Parameters[Parameter].second);
1879 // At the end of the statement, fill in remaining arguments that have
1880 // default values. If there aren't any, then the next argument is
1881 // required but missing
1882 if (Lexer.is(AsmToken::EndOfStatement)) {
1883 if (NParameters && Parameter < NParameters - 1) {
1884 if (M->Parameters[Parameter + 1].second.empty())
1885 return TokError("macro argument '" +
1886 Twine(M->Parameters[Parameter + 1].first) +
1894 if (Lexer.is(AsmToken::Comma))
1897 return TokError("Too many arguments");
1900 const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1901 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1902 return (I == MacroMap.end()) ? NULL : I->getValue();
1905 void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1906 MacroMap[Name] = new MCAsmMacro(Macro);
1909 void AsmParser::UndefineMacro(StringRef Name) {
1910 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1911 if (I != MacroMap.end()) {
1912 delete I->getValue();
1917 bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
1918 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1919 // this, although we should protect against infinite loops.
1920 if (ActiveMacros.size() == 20)
1921 return TokError("macros cannot be nested more than 20 levels deep");
1923 MCAsmMacroArguments A;
1924 if (ParseMacroArguments(M, A))
1927 // Remove any trailing empty arguments. Do this after-the-fact as we have
1928 // to keep empty arguments in the middle of the list or positionality
1929 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1930 while (!A.empty() && A.back().empty())
1933 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1934 // to hold the macro body with substitutions.
1935 SmallString<256> Buf;
1936 StringRef Body = M->Body;
1937 raw_svector_ostream OS(Buf);
1939 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1942 // We include the .endmacro in the buffer as our cue to exit the macro
1944 OS << ".endmacro\n";
1946 MemoryBuffer *Instantiation =
1947 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1949 // Create the macro instantiation object and add to the current macro
1950 // instantiation stack.
1951 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1955 ActiveMacros.push_back(MI);
1957 // Jump to the macro instantiation and prime the lexer.
1958 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1959 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1965 void AsmParser::HandleMacroExit() {
1966 // Jump to the EndOfStatement we should return to, and consume it.
1967 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
1970 // Pop the instantiation entry.
1971 delete ActiveMacros.back();
1972 ActiveMacros.pop_back();
1975 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1976 switch (Value->getKind()) {
1977 case MCExpr::Binary: {
1978 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1979 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1982 case MCExpr::Target:
1983 case MCExpr::Constant:
1985 case MCExpr::SymbolRef: {
1986 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1988 return IsUsedIn(Sym, S.getVariableValue());
1992 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1995 llvm_unreachable("Unknown expr kind!");
1998 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
2000 // FIXME: Use better location, we should use proper tokens.
2001 SMLoc EqualLoc = Lexer.getLoc();
2003 const MCExpr *Value;
2004 if (ParseExpression(Value))
2007 // Note: we don't count b as used in "a = b". This is to allow
2011 if (Lexer.isNot(AsmToken::EndOfStatement))
2012 return TokError("unexpected token in assignment");
2014 // Error on assignment to '.'.
2016 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2017 "(use '.space' or '.org').)"));
2020 // Eat the end of statement marker.
2023 // Validate that the LHS is allowed to be a variable (either it has not been
2024 // used as a symbol, or it is an absolute symbol).
2025 MCSymbol *Sym = getContext().LookupSymbol(Name);
2027 // Diagnose assignment to a label.
2029 // FIXME: Diagnostics. Note the location of the definition as a label.
2030 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2031 if (IsUsedIn(Sym, Value))
2032 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2033 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2034 ; // Allow redefinitions of undefined symbols only used in directives.
2035 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2036 ; // Allow redefinitions of variables that haven't yet been used.
2037 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2038 return Error(EqualLoc, "redefinition of '" + Name + "'");
2039 else if (!Sym->isVariable())
2040 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2041 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2042 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2045 // Don't count these checks as uses.
2046 Sym->setUsed(false);
2048 Sym = getContext().GetOrCreateSymbol(Name);
2050 // FIXME: Handle '.'.
2052 // Do the assignment.
2053 Out.EmitAssignment(Sym, Value);
2055 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2061 /// ParseIdentifier:
2064 bool AsmParser::ParseIdentifier(StringRef &Res) {
2065 // The assembler has relaxed rules for accepting identifiers, in particular we
2066 // allow things like '.globl $foo', which would normally be separate
2067 // tokens. At this level, we have already lexed so we cannot (currently)
2068 // handle this as a context dependent token, instead we detect adjacent tokens
2069 // and return the combined identifier.
2070 if (Lexer.is(AsmToken::Dollar)) {
2071 SMLoc DollarLoc = getLexer().getLoc();
2073 // Consume the dollar sign, and check for a following identifier.
2075 if (Lexer.isNot(AsmToken::Identifier))
2078 // We have a '$' followed by an identifier, make sure they are adjacent.
2079 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2082 // Construct the joined identifier and consume the token.
2083 Res = StringRef(DollarLoc.getPointer(),
2084 getTok().getIdentifier().size() + 1);
2089 if (Lexer.isNot(AsmToken::Identifier) &&
2090 Lexer.isNot(AsmToken::String))
2093 Res = getTok().getIdentifier();
2095 Lex(); // Consume the identifier token.
2100 /// ParseDirectiveSet:
2101 /// ::= .equ identifier ',' expression
2102 /// ::= .equiv identifier ',' expression
2103 /// ::= .set identifier ',' expression
2104 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
2107 if (ParseIdentifier(Name))
2108 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2110 if (getLexer().isNot(AsmToken::Comma))
2111 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2114 return ParseAssignment(Name, allow_redef, true);
2117 bool AsmParser::ParseEscapedString(std::string &Data) {
2118 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2121 StringRef Str = getTok().getStringContents();
2122 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2123 if (Str[i] != '\\') {
2128 // Recognize escaped characters. Note that this escape semantics currently
2129 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2132 return TokError("unexpected backslash at end of string");
2134 // Recognize octal sequences.
2135 if ((unsigned) (Str[i] - '0') <= 7) {
2136 // Consume up to three octal characters.
2137 unsigned Value = Str[i] - '0';
2139 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2141 Value = Value * 8 + (Str[i] - '0');
2143 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2145 Value = Value * 8 + (Str[i] - '0');
2150 return TokError("invalid octal escape sequence (out of range)");
2152 Data += (unsigned char) Value;
2156 // Otherwise recognize individual escapes.
2159 // Just reject invalid escape sequences for now.
2160 return TokError("invalid escape sequence (unrecognized character)");
2162 case 'b': Data += '\b'; break;
2163 case 'f': Data += '\f'; break;
2164 case 'n': Data += '\n'; break;
2165 case 'r': Data += '\r'; break;
2166 case 't': Data += '\t'; break;
2167 case '"': Data += '"'; break;
2168 case '\\': Data += '\\'; break;
2175 /// ParseDirectiveAscii:
2176 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2177 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2178 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2179 CheckForValidSection();
2182 if (getLexer().isNot(AsmToken::String))
2183 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2186 if (ParseEscapedString(Data))
2189 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2191 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2195 if (getLexer().is(AsmToken::EndOfStatement))
2198 if (getLexer().isNot(AsmToken::Comma))
2199 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2208 /// ParseDirectiveValue
2209 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2210 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2211 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2212 CheckForValidSection();
2215 const MCExpr *Value;
2216 SMLoc ExprLoc = getLexer().getLoc();
2217 if (ParseExpression(Value))
2220 // Special case constant expressions to match code generator.
2221 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2222 assert(Size <= 8 && "Invalid size");
2223 uint64_t IntValue = MCE->getValue();
2224 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2225 return Error(ExprLoc, "literal value out of range for directive");
2226 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2228 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2230 if (getLexer().is(AsmToken::EndOfStatement))
2233 // FIXME: Improve diagnostic.
2234 if (getLexer().isNot(AsmToken::Comma))
2235 return TokError("unexpected token in directive");
2244 /// ParseDirectiveRealValue
2245 /// ::= (.single | .double) [ expression (, expression)* ]
2246 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2247 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2248 CheckForValidSection();
2251 // We don't truly support arithmetic on floating point expressions, so we
2252 // have to manually parse unary prefixes.
2254 if (getLexer().is(AsmToken::Minus)) {
2257 } else if (getLexer().is(AsmToken::Plus))
2260 if (getLexer().isNot(AsmToken::Integer) &&
2261 getLexer().isNot(AsmToken::Real) &&
2262 getLexer().isNot(AsmToken::Identifier))
2263 return TokError("unexpected token in directive");
2265 // Convert to an APFloat.
2266 APFloat Value(Semantics);
2267 StringRef IDVal = getTok().getString();
2268 if (getLexer().is(AsmToken::Identifier)) {
2269 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2270 Value = APFloat::getInf(Semantics);
2271 else if (!IDVal.compare_lower("nan"))
2272 Value = APFloat::getNaN(Semantics, false, ~0);
2274 return TokError("invalid floating point literal");
2275 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2276 APFloat::opInvalidOp)
2277 return TokError("invalid floating point literal");
2281 // Consume the numeric token.
2284 // Emit the value as an integer.
2285 APInt AsInt = Value.bitcastToAPInt();
2286 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2287 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2289 if (getLexer().is(AsmToken::EndOfStatement))
2292 if (getLexer().isNot(AsmToken::Comma))
2293 return TokError("unexpected token in directive");
2302 /// ParseDirectiveZero
2303 /// ::= .zero expression
2304 bool AsmParser::ParseDirectiveZero() {
2305 CheckForValidSection();
2308 if (ParseAbsoluteExpression(NumBytes))
2312 if (getLexer().is(AsmToken::Comma)) {
2314 if (ParseAbsoluteExpression(Val))
2318 if (getLexer().isNot(AsmToken::EndOfStatement))
2319 return TokError("unexpected token in '.zero' directive");
2323 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2328 /// ParseDirectiveFill
2329 /// ::= .fill expression , expression , expression
2330 bool AsmParser::ParseDirectiveFill() {
2331 CheckForValidSection();
2334 if (ParseAbsoluteExpression(NumValues))
2337 if (getLexer().isNot(AsmToken::Comma))
2338 return TokError("unexpected token in '.fill' directive");
2342 if (ParseAbsoluteExpression(FillSize))
2345 if (getLexer().isNot(AsmToken::Comma))
2346 return TokError("unexpected token in '.fill' directive");
2350 if (ParseAbsoluteExpression(FillExpr))
2353 if (getLexer().isNot(AsmToken::EndOfStatement))
2354 return TokError("unexpected token in '.fill' directive");
2358 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2359 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2361 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2362 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2367 /// ParseDirectiveOrg
2368 /// ::= .org expression [ , expression ]
2369 bool AsmParser::ParseDirectiveOrg() {
2370 CheckForValidSection();
2372 const MCExpr *Offset;
2373 SMLoc Loc = getTok().getLoc();
2374 if (ParseExpression(Offset))
2377 // Parse optional fill expression.
2378 int64_t FillExpr = 0;
2379 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2380 if (getLexer().isNot(AsmToken::Comma))
2381 return TokError("unexpected token in '.org' directive");
2384 if (ParseAbsoluteExpression(FillExpr))
2387 if (getLexer().isNot(AsmToken::EndOfStatement))
2388 return TokError("unexpected token in '.org' directive");
2393 // Only limited forms of relocatable expressions are accepted here, it
2394 // has to be relative to the current section. The streamer will return
2395 // 'true' if the expression wasn't evaluatable.
2396 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2397 return Error(Loc, "expected assembly-time absolute expression");
2402 /// ParseDirectiveAlign
2403 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2404 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2405 CheckForValidSection();
2407 SMLoc AlignmentLoc = getLexer().getLoc();
2409 if (ParseAbsoluteExpression(Alignment))
2413 bool HasFillExpr = false;
2414 int64_t FillExpr = 0;
2415 int64_t MaxBytesToFill = 0;
2416 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2417 if (getLexer().isNot(AsmToken::Comma))
2418 return TokError("unexpected token in directive");
2421 // The fill expression can be omitted while specifying a maximum number of
2422 // alignment bytes, e.g:
2424 if (getLexer().isNot(AsmToken::Comma)) {
2426 if (ParseAbsoluteExpression(FillExpr))
2430 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2431 if (getLexer().isNot(AsmToken::Comma))
2432 return TokError("unexpected token in directive");
2435 MaxBytesLoc = getLexer().getLoc();
2436 if (ParseAbsoluteExpression(MaxBytesToFill))
2439 if (getLexer().isNot(AsmToken::EndOfStatement))
2440 return TokError("unexpected token in directive");
2449 // Compute alignment in bytes.
2451 // FIXME: Diagnose overflow.
2452 if (Alignment >= 32) {
2453 Error(AlignmentLoc, "invalid alignment value");
2457 Alignment = 1ULL << Alignment;
2460 // Diagnose non-sensical max bytes to align.
2461 if (MaxBytesLoc.isValid()) {
2462 if (MaxBytesToFill < 1) {
2463 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2464 "many bytes, ignoring maximum bytes expression");
2468 if (MaxBytesToFill >= Alignment) {
2469 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2475 // Check whether we should use optimal code alignment for this .align
2477 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2478 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2479 ValueSize == 1 && UseCodeAlign) {
2480 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2482 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2483 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2490 /// ParseDirectiveFile
2491 /// ::= .file [number] filename
2492 /// ::= .file number directory filename
2493 bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2494 // FIXME: I'm not sure what this is.
2495 int64_t FileNumber = -1;
2496 SMLoc FileNumberLoc = getLexer().getLoc();
2497 if (getLexer().is(AsmToken::Integer)) {
2498 FileNumber = getTok().getIntVal();
2502 return TokError("file number less than one");
2505 if (getLexer().isNot(AsmToken::String))
2506 return TokError("unexpected token in '.file' directive");
2508 // Usually the directory and filename together, otherwise just the directory.
2509 StringRef Path = getTok().getString();
2510 Path = Path.substr(1, Path.size()-2);
2513 StringRef Directory;
2515 if (getLexer().is(AsmToken::String)) {
2516 if (FileNumber == -1)
2517 return TokError("explicit path specified, but no file number");
2518 Filename = getTok().getString();
2519 Filename = Filename.substr(1, Filename.size()-2);
2526 if (getLexer().isNot(AsmToken::EndOfStatement))
2527 return TokError("unexpected token in '.file' directive");
2529 if (FileNumber == -1)
2530 getStreamer().EmitFileDirective(Filename);
2532 if (getContext().getGenDwarfForAssembly() == true)
2533 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2534 "used to generate dwarf debug info for assembly code");
2536 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2537 Error(FileNumberLoc, "file number already allocated");
2543 /// ParseDirectiveLine
2544 /// ::= .line [number]
2545 bool AsmParser::ParseDirectiveLine() {
2546 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2547 if (getLexer().isNot(AsmToken::Integer))
2548 return TokError("unexpected token in '.line' directive");
2550 int64_t LineNumber = getTok().getIntVal();
2554 // FIXME: Do something with the .line.
2557 if (getLexer().isNot(AsmToken::EndOfStatement))
2558 return TokError("unexpected token in '.line' directive");
2563 /// ParseDirectiveLoc
2564 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2565 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2566 /// The first number is a file number, must have been previously assigned with
2567 /// a .file directive, the second number is the line number and optionally the
2568 /// third number is a column position (zero if not specified). The remaining
2569 /// optional items are .loc sub-directives.
2570 bool AsmParser::ParseDirectiveLoc() {
2571 if (getLexer().isNot(AsmToken::Integer))
2572 return TokError("unexpected token in '.loc' directive");
2573 int64_t FileNumber = getTok().getIntVal();
2575 return TokError("file number less than one in '.loc' directive");
2576 if (!getContext().isValidDwarfFileNumber(FileNumber))
2577 return TokError("unassigned file number in '.loc' directive");
2580 int64_t LineNumber = 0;
2581 if (getLexer().is(AsmToken::Integer)) {
2582 LineNumber = getTok().getIntVal();
2584 return TokError("line number less than one in '.loc' directive");
2588 int64_t ColumnPos = 0;
2589 if (getLexer().is(AsmToken::Integer)) {
2590 ColumnPos = getTok().getIntVal();
2592 return TokError("column position less than zero in '.loc' directive");
2596 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2598 int64_t Discriminator = 0;
2599 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2601 if (getLexer().is(AsmToken::EndOfStatement))
2605 SMLoc Loc = getTok().getLoc();
2606 if (ParseIdentifier(Name))
2607 return TokError("unexpected token in '.loc' directive");
2609 if (Name == "basic_block")
2610 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2611 else if (Name == "prologue_end")
2612 Flags |= DWARF2_FLAG_PROLOGUE_END;
2613 else if (Name == "epilogue_begin")
2614 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2615 else if (Name == "is_stmt") {
2616 Loc = getTok().getLoc();
2617 const MCExpr *Value;
2618 if (ParseExpression(Value))
2620 // The expression must be the constant 0 or 1.
2621 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2622 int Value = MCE->getValue();
2624 Flags &= ~DWARF2_FLAG_IS_STMT;
2625 else if (Value == 1)
2626 Flags |= DWARF2_FLAG_IS_STMT;
2628 return Error(Loc, "is_stmt value not 0 or 1");
2631 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2634 else if (Name == "isa") {
2635 Loc = getTok().getLoc();
2636 const MCExpr *Value;
2637 if (ParseExpression(Value))
2639 // The expression must be a constant greater or equal to 0.
2640 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2641 int Value = MCE->getValue();
2643 return Error(Loc, "isa number less than zero");
2647 return Error(Loc, "isa number not a constant value");
2650 else if (Name == "discriminator") {
2651 if (ParseAbsoluteExpression(Discriminator))
2655 return Error(Loc, "unknown sub-directive in '.loc' directive");
2658 if (getLexer().is(AsmToken::EndOfStatement))
2663 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2664 Isa, Discriminator, StringRef());
2669 /// ParseDirectiveStabs
2670 /// ::= .stabs string, number, number, number
2671 bool AsmParser::ParseDirectiveStabs() {
2672 return TokError("unsupported directive '.stabs'");
2675 /// ParseDirectiveCFISections
2676 /// ::= .cfi_sections section [, section]
2677 bool AsmParser::ParseDirectiveCFISections() {
2682 if (ParseIdentifier(Name))
2683 return TokError("Expected an identifier");
2685 if (Name == ".eh_frame")
2687 else if (Name == ".debug_frame")
2690 if (getLexer().is(AsmToken::Comma)) {
2693 if (ParseIdentifier(Name))
2694 return TokError("Expected an identifier");
2696 if (Name == ".eh_frame")
2698 else if (Name == ".debug_frame")
2702 getStreamer().EmitCFISections(EH, Debug);
2706 /// ParseDirectiveCFIStartProc
2707 /// ::= .cfi_startproc
2708 bool AsmParser::ParseDirectiveCFIStartProc() {
2709 getStreamer().EmitCFIStartProc();
2713 /// ParseDirectiveCFIEndProc
2714 /// ::= .cfi_endproc
2715 bool AsmParser::ParseDirectiveCFIEndProc() {
2716 getStreamer().EmitCFIEndProc();
2720 /// ParseRegisterOrRegisterNumber - parse register name or number.
2721 bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2722 SMLoc DirectiveLoc) {
2725 if (getLexer().isNot(AsmToken::Integer)) {
2726 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2728 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2730 return ParseAbsoluteExpression(Register);
2735 /// ParseDirectiveCFIDefCfa
2736 /// ::= .cfi_def_cfa register, offset
2737 bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2738 int64_t Register = 0;
2739 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2742 if (getLexer().isNot(AsmToken::Comma))
2743 return TokError("unexpected token in directive");
2747 if (ParseAbsoluteExpression(Offset))
2750 getStreamer().EmitCFIDefCfa(Register, Offset);
2754 /// ParseDirectiveCFIDefCfaOffset
2755 /// ::= .cfi_def_cfa_offset offset
2756 bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2758 if (ParseAbsoluteExpression(Offset))
2761 getStreamer().EmitCFIDefCfaOffset(Offset);
2765 /// ParseDirectiveCFIRegister
2766 /// ::= .cfi_register register, register
2767 bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2768 int64_t Register1 = 0;
2769 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2772 if (getLexer().isNot(AsmToken::Comma))
2773 return TokError("unexpected token in directive");
2776 int64_t Register2 = 0;
2777 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2780 getStreamer().EmitCFIRegister(Register1, Register2);
2784 /// ParseDirectiveCFIAdjustCfaOffset
2785 /// ::= .cfi_adjust_cfa_offset adjustment
2786 bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2787 int64_t Adjustment = 0;
2788 if (ParseAbsoluteExpression(Adjustment))
2791 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2795 /// ParseDirectiveCFIDefCfaRegister
2796 /// ::= .cfi_def_cfa_register register
2797 bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2798 int64_t Register = 0;
2799 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2802 getStreamer().EmitCFIDefCfaRegister(Register);
2806 /// ParseDirectiveCFIOffset
2807 /// ::= .cfi_offset register, offset
2808 bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2809 int64_t Register = 0;
2812 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2815 if (getLexer().isNot(AsmToken::Comma))
2816 return TokError("unexpected token in directive");
2819 if (ParseAbsoluteExpression(Offset))
2822 getStreamer().EmitCFIOffset(Register, Offset);
2826 /// ParseDirectiveCFIRelOffset
2827 /// ::= .cfi_rel_offset register, offset
2828 bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2829 int64_t Register = 0;
2831 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2834 if (getLexer().isNot(AsmToken::Comma))
2835 return TokError("unexpected token in directive");
2839 if (ParseAbsoluteExpression(Offset))
2842 getStreamer().EmitCFIRelOffset(Register, Offset);
2846 static bool isValidEncoding(int64_t Encoding) {
2847 if (Encoding & ~0xff)
2850 if (Encoding == dwarf::DW_EH_PE_omit)
2853 const unsigned Format = Encoding & 0xf;
2854 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2855 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2856 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2857 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2860 const unsigned Application = Encoding & 0x70;
2861 if (Application != dwarf::DW_EH_PE_absptr &&
2862 Application != dwarf::DW_EH_PE_pcrel)
2868 /// ParseDirectiveCFIPersonalityOrLsda
2869 /// IsPersonality true for cfi_personality, false for cfi_lsda
2870 /// ::= .cfi_personality encoding, [symbol_name]
2871 /// ::= .cfi_lsda encoding, [symbol_name]
2872 bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2873 int64_t Encoding = 0;
2874 if (ParseAbsoluteExpression(Encoding))
2876 if (Encoding == dwarf::DW_EH_PE_omit)
2879 if (!isValidEncoding(Encoding))
2880 return TokError("unsupported encoding.");
2882 if (getLexer().isNot(AsmToken::Comma))
2883 return TokError("unexpected token in directive");
2887 if (ParseIdentifier(Name))
2888 return TokError("expected identifier in directive");
2890 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2893 getStreamer().EmitCFIPersonality(Sym, Encoding);
2895 getStreamer().EmitCFILsda(Sym, Encoding);
2899 /// ParseDirectiveCFIRememberState
2900 /// ::= .cfi_remember_state
2901 bool AsmParser::ParseDirectiveCFIRememberState() {
2902 getStreamer().EmitCFIRememberState();
2906 /// ParseDirectiveCFIRestoreState
2907 /// ::= .cfi_remember_state
2908 bool AsmParser::ParseDirectiveCFIRestoreState() {
2909 getStreamer().EmitCFIRestoreState();
2913 /// ParseDirectiveCFISameValue
2914 /// ::= .cfi_same_value register
2915 bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2916 int64_t Register = 0;
2918 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2921 getStreamer().EmitCFISameValue(Register);
2925 /// ParseDirectiveCFIRestore
2926 /// ::= .cfi_restore register
2927 bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2928 int64_t Register = 0;
2929 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2932 getStreamer().EmitCFIRestore(Register);
2936 /// ParseDirectiveCFIEscape
2937 /// ::= .cfi_escape expression[,...]
2938 bool AsmParser::ParseDirectiveCFIEscape() {
2941 if (ParseAbsoluteExpression(CurrValue))
2944 Values.push_back((uint8_t)CurrValue);
2946 while (getLexer().is(AsmToken::Comma)) {
2949 if (ParseAbsoluteExpression(CurrValue))
2952 Values.push_back((uint8_t)CurrValue);
2955 getStreamer().EmitCFIEscape(Values);
2959 /// ParseDirectiveCFISignalFrame
2960 /// ::= .cfi_signal_frame
2961 bool AsmParser::ParseDirectiveCFISignalFrame() {
2962 if (getLexer().isNot(AsmToken::EndOfStatement))
2963 return Error(getLexer().getLoc(),
2964 "unexpected token in '.cfi_signal_frame'");
2966 getStreamer().EmitCFISignalFrame();
2970 /// ParseDirectiveCFIUndefined
2971 /// ::= .cfi_undefined register
2972 bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
2973 int64_t Register = 0;
2975 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2978 getStreamer().EmitCFIUndefined(Register);
2982 /// ParseDirectiveMacrosOnOff
2985 bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
2986 if (getLexer().isNot(AsmToken::EndOfStatement))
2987 return Error(getLexer().getLoc(),
2988 "unexpected token in '" + Directive + "' directive");
2990 SetMacrosEnabled(Directive == ".macros_on");
2994 /// ParseDirectiveMacro
2995 /// ::= .macro name [parameters]
2996 bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
2998 if (ParseIdentifier(Name))
2999 return TokError("expected identifier in '.macro' directive");
3001 MCAsmMacroParameters Parameters;
3002 // Argument delimiter is initially unknown. It will be set by
3003 // ParseMacroArgument()
3004 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3005 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3007 MCAsmMacroParameter Parameter;
3008 if (ParseIdentifier(Parameter.first))
3009 return TokError("expected identifier in '.macro' directive");
3011 if (getLexer().is(AsmToken::Equal)) {
3013 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3017 Parameters.push_back(Parameter);
3019 if (getLexer().is(AsmToken::Comma))
3021 else if (getLexer().is(AsmToken::EndOfStatement))
3026 // Eat the end of statement.
3029 AsmToken EndToken, StartToken = getTok();
3031 // Lex the macro definition.
3033 // Check whether we have reached the end of the file.
3034 if (getLexer().is(AsmToken::Eof))
3035 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3037 // Otherwise, check whether we have reach the .endmacro.
3038 if (getLexer().is(AsmToken::Identifier) &&
3039 (getTok().getIdentifier() == ".endm" ||
3040 getTok().getIdentifier() == ".endmacro")) {
3041 EndToken = getTok();
3043 if (getLexer().isNot(AsmToken::EndOfStatement))
3044 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3049 // Otherwise, scan til the end of the statement.
3050 EatToEndOfStatement();
3053 if (LookupMacro(Name)) {
3054 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3057 const char *BodyStart = StartToken.getLoc().getPointer();
3058 const char *BodyEnd = EndToken.getLoc().getPointer();
3059 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3060 CheckForBadMacro(DirectiveLoc, Name, Body, Parameters);
3061 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3065 /// CheckForBadMacro
3067 /// With the support added for named parameters there may be code out there that
3068 /// is transitioning from positional parameters. In versions of gas that did
3069 /// not support named parameters they would be ignored on the macro defintion.
3070 /// But to support both styles of parameters this is not possible so if a macro
3071 /// defintion has named parameters but does not use them and has what appears
3072 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3073 /// warning that the positional parameter found in body which have no effect.
3074 /// Hoping the developer will either remove the named parameters from the macro
3075 /// definiton so the positional parameters get used if that was what was
3076 /// intended or change the macro to use the named parameters. It is possible
3077 /// this warning will trigger when the none of the named parameters are used
3078 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3079 void AsmParser::CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3081 MCAsmMacroParameters Parameters) {
3082 // If this macro is not defined with named parameters the warning we are
3083 // checking for here doesn't apply.
3084 unsigned NParameters = Parameters.size();
3085 if (NParameters == 0)
3088 bool NamedParametersFound = false;
3089 bool PositionalParametersFound = false;
3091 // Look at the body of the macro for use of both the named parameters and what
3092 // are likely to be positional parameters. This is what expandMacro() is
3093 // doing when it finds the parameters in the body.
3094 while (!Body.empty()) {
3095 // Scan for the next possible parameter.
3096 std::size_t End = Body.size(), Pos = 0;
3097 for (; Pos != End; ++Pos) {
3098 // Check for a substitution or escape.
3099 // This macro is defined with parameters, look for \foo, \bar, etc.
3100 if (Body[Pos] == '\\' && Pos + 1 != End)
3103 // This macro should have parameters, but look for $0, $1, ..., $n too.
3104 if (Body[Pos] != '$' || Pos + 1 == End)
3106 char Next = Body[Pos + 1];
3107 if (Next == '$' || Next == 'n' ||
3108 isdigit(static_cast<unsigned char>(Next)))
3112 // Check if we reached the end.
3116 if (Body[Pos] == '$') {
3117 switch (Body[Pos+1]) {
3122 // $n => number of arguments
3124 PositionalParametersFound = true;
3127 // $[0-9] => argument
3129 PositionalParametersFound = true;
3135 unsigned I = Pos + 1;
3136 while (isIdentifierChar(Body[I]) && I + 1 != End)
3139 const char *Begin = Body.data() + Pos +1;
3140 StringRef Argument(Begin, I - (Pos +1));
3142 for (; Index < NParameters; ++Index)
3143 if (Parameters[Index].first == Argument)
3146 if (Index == NParameters) {
3147 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
3153 NamedParametersFound = true;
3154 Pos += 1 + Argument.size();
3157 // Update the scan point.
3158 Body = Body.substr(Pos);
3161 if (!NamedParametersFound && PositionalParametersFound)
3162 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3163 "used in macro body, possible positional parameter "
3164 "found in body which will have no effect");
3167 /// ParseDirectiveEndMacro
3170 bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3171 if (getLexer().isNot(AsmToken::EndOfStatement))
3172 return TokError("unexpected token in '" + Directive + "' directive");
3174 // If we are inside a macro instantiation, terminate the current
3176 if (InsideMacroInstantiation()) {
3181 // Otherwise, this .endmacro is a stray entry in the file; well formed
3182 // .endmacro directives are handled during the macro definition parsing.
3183 return TokError("unexpected '" + Directive + "' in file, "
3184 "no current macro definition");
3187 /// ParseDirectivePurgeMacro
3189 bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3191 if (ParseIdentifier(Name))
3192 return TokError("expected identifier in '.purgem' directive");
3194 if (getLexer().isNot(AsmToken::EndOfStatement))
3195 return TokError("unexpected token in '.purgem' directive");
3197 if (!LookupMacro(Name))
3198 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3200 UndefineMacro(Name);
3204 /// ParseDirectiveBundleAlignMode
3205 /// ::= {.bundle_align_mode} expression
3206 bool AsmParser::ParseDirectiveBundleAlignMode() {
3207 CheckForValidSection();
3209 // Expect a single argument: an expression that evaluates to a constant
3210 // in the inclusive range 0-30.
3211 SMLoc ExprLoc = getLexer().getLoc();
3212 int64_t AlignSizePow2;
3213 if (ParseAbsoluteExpression(AlignSizePow2))
3215 else if (getLexer().isNot(AsmToken::EndOfStatement))
3216 return TokError("unexpected token after expression in"
3217 " '.bundle_align_mode' directive");
3218 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3219 return Error(ExprLoc,
3220 "invalid bundle alignment size (expected between 0 and 30)");
3224 // Because of AlignSizePow2's verified range we can safely truncate it to
3226 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3230 /// ParseDirectiveBundleLock
3231 /// ::= {.bundle_lock} [align_to_end]
3232 bool AsmParser::ParseDirectiveBundleLock() {
3233 CheckForValidSection();
3234 bool AlignToEnd = false;
3236 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3238 SMLoc Loc = getTok().getLoc();
3239 const char *kInvalidOptionError =
3240 "invalid option for '.bundle_lock' directive";
3242 if (ParseIdentifier(Option))
3243 return Error(Loc, kInvalidOptionError);
3245 if (Option != "align_to_end")
3246 return Error(Loc, kInvalidOptionError);
3247 else if (getLexer().isNot(AsmToken::EndOfStatement))
3249 "unexpected token after '.bundle_lock' directive option");
3255 getStreamer().EmitBundleLock(AlignToEnd);
3259 /// ParseDirectiveBundleLock
3260 /// ::= {.bundle_lock}
3261 bool AsmParser::ParseDirectiveBundleUnlock() {
3262 CheckForValidSection();
3264 if (getLexer().isNot(AsmToken::EndOfStatement))
3265 return TokError("unexpected token in '.bundle_unlock' directive");
3268 getStreamer().EmitBundleUnlock();
3272 /// ParseDirectiveSpace
3273 /// ::= (.skip | .space) expression [ , expression ]
3274 bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
3275 CheckForValidSection();
3278 if (ParseAbsoluteExpression(NumBytes))
3281 int64_t FillExpr = 0;
3282 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3283 if (getLexer().isNot(AsmToken::Comma))
3284 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3287 if (ParseAbsoluteExpression(FillExpr))
3290 if (getLexer().isNot(AsmToken::EndOfStatement))
3291 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3297 return TokError("invalid number of bytes in '" +
3298 Twine(IDVal) + "' directive");
3300 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3301 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3306 /// ParseDirectiveLEB128
3307 /// ::= (.sleb128 | .uleb128) expression
3308 bool AsmParser::ParseDirectiveLEB128(bool Signed) {
3309 CheckForValidSection();
3310 const MCExpr *Value;
3312 if (ParseExpression(Value))
3315 if (getLexer().isNot(AsmToken::EndOfStatement))
3316 return TokError("unexpected token in directive");
3319 getStreamer().EmitSLEB128Value(Value);
3321 getStreamer().EmitULEB128Value(Value);
3326 /// ParseDirectiveSymbolAttribute
3327 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3328 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3329 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3332 SMLoc Loc = getTok().getLoc();
3334 if (ParseIdentifier(Name))
3335 return Error(Loc, "expected identifier in directive");
3337 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3339 // Assembler local symbols don't make any sense here. Complain loudly.
3340 if (Sym->isTemporary())
3341 return Error(Loc, "non-local symbol required in directive");
3343 getStreamer().EmitSymbolAttribute(Sym, Attr);
3345 if (getLexer().is(AsmToken::EndOfStatement))
3348 if (getLexer().isNot(AsmToken::Comma))
3349 return TokError("unexpected token in directive");
3358 /// ParseDirectiveComm
3359 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3360 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
3361 CheckForValidSection();
3363 SMLoc IDLoc = getLexer().getLoc();
3365 if (ParseIdentifier(Name))
3366 return TokError("expected identifier in directive");
3368 // Handle the identifier as the key symbol.
3369 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3371 if (getLexer().isNot(AsmToken::Comma))
3372 return TokError("unexpected token in directive");
3376 SMLoc SizeLoc = getLexer().getLoc();
3377 if (ParseAbsoluteExpression(Size))
3380 int64_t Pow2Alignment = 0;
3381 SMLoc Pow2AlignmentLoc;
3382 if (getLexer().is(AsmToken::Comma)) {
3384 Pow2AlignmentLoc = getLexer().getLoc();
3385 if (ParseAbsoluteExpression(Pow2Alignment))
3388 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3389 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3390 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3392 // If this target takes alignments in bytes (not log) validate and convert.
3393 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3394 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3395 if (!isPowerOf2_64(Pow2Alignment))
3396 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3397 Pow2Alignment = Log2_64(Pow2Alignment);
3401 if (getLexer().isNot(AsmToken::EndOfStatement))
3402 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3406 // NOTE: a size of zero for a .comm should create a undefined symbol
3407 // but a size of .lcomm creates a bss symbol of size zero.
3409 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3410 "be less than zero");
3412 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3413 // may internally end up wanting an alignment in bytes.
3414 // FIXME: Diagnose overflow.
3415 if (Pow2Alignment < 0)
3416 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3417 "alignment, can't be less than zero");
3419 if (!Sym->isUndefined())
3420 return Error(IDLoc, "invalid symbol redefinition");
3422 // Create the Symbol as a common or local common with Size and Pow2Alignment
3424 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3428 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3432 /// ParseDirectiveAbort
3433 /// ::= .abort [... message ...]
3434 bool AsmParser::ParseDirectiveAbort() {
3435 // FIXME: Use loc from directive.
3436 SMLoc Loc = getLexer().getLoc();
3438 StringRef Str = ParseStringToEndOfStatement();
3439 if (getLexer().isNot(AsmToken::EndOfStatement))
3440 return TokError("unexpected token in '.abort' directive");
3445 Error(Loc, ".abort detected. Assembly stopping.");
3447 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3448 // FIXME: Actually abort assembly here.
3453 /// ParseDirectiveInclude
3454 /// ::= .include "filename"
3455 bool AsmParser::ParseDirectiveInclude() {
3456 if (getLexer().isNot(AsmToken::String))
3457 return TokError("expected string in '.include' directive");
3459 std::string Filename = getTok().getString();
3460 SMLoc IncludeLoc = getLexer().getLoc();
3463 if (getLexer().isNot(AsmToken::EndOfStatement))
3464 return TokError("unexpected token in '.include' directive");
3466 // Strip the quotes.
3467 Filename = Filename.substr(1, Filename.size()-2);
3469 // Attempt to switch the lexer to the included file before consuming the end
3470 // of statement to avoid losing it when we switch.
3471 if (EnterIncludeFile(Filename)) {
3472 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3479 /// ParseDirectiveIncbin
3480 /// ::= .incbin "filename"
3481 bool AsmParser::ParseDirectiveIncbin() {
3482 if (getLexer().isNot(AsmToken::String))
3483 return TokError("expected string in '.incbin' directive");
3485 std::string Filename = getTok().getString();
3486 SMLoc IncbinLoc = getLexer().getLoc();
3489 if (getLexer().isNot(AsmToken::EndOfStatement))
3490 return TokError("unexpected token in '.incbin' directive");
3492 // Strip the quotes.
3493 Filename = Filename.substr(1, Filename.size()-2);
3495 // Attempt to process the included file.
3496 if (ProcessIncbinFile(Filename)) {
3497 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3504 /// ParseDirectiveIf
3505 /// ::= .if expression
3506 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
3507 TheCondStack.push_back(TheCondState);
3508 TheCondState.TheCond = AsmCond::IfCond;
3509 if (TheCondState.Ignore) {
3510 EatToEndOfStatement();
3513 if (ParseAbsoluteExpression(ExprValue))
3516 if (getLexer().isNot(AsmToken::EndOfStatement))
3517 return TokError("unexpected token in '.if' directive");
3521 TheCondState.CondMet = ExprValue;
3522 TheCondState.Ignore = !TheCondState.CondMet;
3528 /// ParseDirectiveIfb
3530 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3531 TheCondStack.push_back(TheCondState);
3532 TheCondState.TheCond = AsmCond::IfCond;
3534 if (TheCondState.Ignore) {
3535 EatToEndOfStatement();
3537 StringRef Str = ParseStringToEndOfStatement();
3539 if (getLexer().isNot(AsmToken::EndOfStatement))
3540 return TokError("unexpected token in '.ifb' directive");
3544 TheCondState.CondMet = ExpectBlank == Str.empty();
3545 TheCondState.Ignore = !TheCondState.CondMet;
3551 /// ParseDirectiveIfc
3552 /// ::= .ifc string1, string2
3553 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3554 TheCondStack.push_back(TheCondState);
3555 TheCondState.TheCond = AsmCond::IfCond;
3557 if (TheCondState.Ignore) {
3558 EatToEndOfStatement();
3560 StringRef Str1 = ParseStringToComma();
3562 if (getLexer().isNot(AsmToken::Comma))
3563 return TokError("unexpected token in '.ifc' directive");
3567 StringRef Str2 = ParseStringToEndOfStatement();
3569 if (getLexer().isNot(AsmToken::EndOfStatement))
3570 return TokError("unexpected token in '.ifc' directive");
3574 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3575 TheCondState.Ignore = !TheCondState.CondMet;
3581 /// ParseDirectiveIfdef
3582 /// ::= .ifdef symbol
3583 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3585 TheCondStack.push_back(TheCondState);
3586 TheCondState.TheCond = AsmCond::IfCond;
3588 if (TheCondState.Ignore) {
3589 EatToEndOfStatement();
3591 if (ParseIdentifier(Name))
3592 return TokError("expected identifier after '.ifdef'");
3596 MCSymbol *Sym = getContext().LookupSymbol(Name);
3599 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3601 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3602 TheCondState.Ignore = !TheCondState.CondMet;
3608 /// ParseDirectiveElseIf
3609 /// ::= .elseif expression
3610 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3611 if (TheCondState.TheCond != AsmCond::IfCond &&
3612 TheCondState.TheCond != AsmCond::ElseIfCond)
3613 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3615 TheCondState.TheCond = AsmCond::ElseIfCond;
3617 bool LastIgnoreState = false;
3618 if (!TheCondStack.empty())
3619 LastIgnoreState = TheCondStack.back().Ignore;
3620 if (LastIgnoreState || TheCondState.CondMet) {
3621 TheCondState.Ignore = true;
3622 EatToEndOfStatement();
3626 if (ParseAbsoluteExpression(ExprValue))
3629 if (getLexer().isNot(AsmToken::EndOfStatement))
3630 return TokError("unexpected token in '.elseif' directive");
3633 TheCondState.CondMet = ExprValue;
3634 TheCondState.Ignore = !TheCondState.CondMet;
3640 /// ParseDirectiveElse
3642 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
3643 if (getLexer().isNot(AsmToken::EndOfStatement))
3644 return TokError("unexpected token in '.else' directive");
3648 if (TheCondState.TheCond != AsmCond::IfCond &&
3649 TheCondState.TheCond != AsmCond::ElseIfCond)
3650 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3652 TheCondState.TheCond = AsmCond::ElseCond;
3653 bool LastIgnoreState = false;
3654 if (!TheCondStack.empty())
3655 LastIgnoreState = TheCondStack.back().Ignore;
3656 if (LastIgnoreState || TheCondState.CondMet)
3657 TheCondState.Ignore = true;
3659 TheCondState.Ignore = false;
3664 /// ParseDirectiveEndIf
3666 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
3667 if (getLexer().isNot(AsmToken::EndOfStatement))
3668 return TokError("unexpected token in '.endif' directive");
3672 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3673 TheCondStack.empty())
3674 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3676 if (!TheCondStack.empty()) {
3677 TheCondState = TheCondStack.back();
3678 TheCondStack.pop_back();
3684 void AsmParser::initializeDirectiveKindMap() {
3685 DirectiveKindMap[".set"] = DK_SET;
3686 DirectiveKindMap[".equ"] = DK_EQU;
3687 DirectiveKindMap[".equiv"] = DK_EQUIV;
3688 DirectiveKindMap[".ascii"] = DK_ASCII;
3689 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3690 DirectiveKindMap[".string"] = DK_STRING;
3691 DirectiveKindMap[".byte"] = DK_BYTE;
3692 DirectiveKindMap[".short"] = DK_SHORT;
3693 DirectiveKindMap[".value"] = DK_VALUE;
3694 DirectiveKindMap[".2byte"] = DK_2BYTE;
3695 DirectiveKindMap[".long"] = DK_LONG;
3696 DirectiveKindMap[".int"] = DK_INT;
3697 DirectiveKindMap[".4byte"] = DK_4BYTE;
3698 DirectiveKindMap[".quad"] = DK_QUAD;
3699 DirectiveKindMap[".8byte"] = DK_8BYTE;
3700 DirectiveKindMap[".single"] = DK_SINGLE;
3701 DirectiveKindMap[".float"] = DK_FLOAT;
3702 DirectiveKindMap[".double"] = DK_DOUBLE;
3703 DirectiveKindMap[".align"] = DK_ALIGN;
3704 DirectiveKindMap[".align32"] = DK_ALIGN32;
3705 DirectiveKindMap[".balign"] = DK_BALIGN;
3706 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3707 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3708 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3709 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3710 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3711 DirectiveKindMap[".org"] = DK_ORG;
3712 DirectiveKindMap[".fill"] = DK_FILL;
3713 DirectiveKindMap[".zero"] = DK_ZERO;
3714 DirectiveKindMap[".extern"] = DK_EXTERN;
3715 DirectiveKindMap[".globl"] = DK_GLOBL;
3716 DirectiveKindMap[".global"] = DK_GLOBAL;
3717 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3718 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3719 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3720 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3721 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3722 DirectiveKindMap[".reference"] = DK_REFERENCE;
3723 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3724 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3725 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3726 DirectiveKindMap[".comm"] = DK_COMM;
3727 DirectiveKindMap[".common"] = DK_COMMON;
3728 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3729 DirectiveKindMap[".abort"] = DK_ABORT;
3730 DirectiveKindMap[".include"] = DK_INCLUDE;
3731 DirectiveKindMap[".incbin"] = DK_INCBIN;
3732 DirectiveKindMap[".code16"] = DK_CODE16;
3733 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3734 DirectiveKindMap[".rept"] = DK_REPT;
3735 DirectiveKindMap[".irp"] = DK_IRP;
3736 DirectiveKindMap[".irpc"] = DK_IRPC;
3737 DirectiveKindMap[".endr"] = DK_ENDR;
3738 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3739 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3740 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3741 DirectiveKindMap[".if"] = DK_IF;
3742 DirectiveKindMap[".ifb"] = DK_IFB;
3743 DirectiveKindMap[".ifnb"] = DK_IFNB;
3744 DirectiveKindMap[".ifc"] = DK_IFC;
3745 DirectiveKindMap[".ifnc"] = DK_IFNC;
3746 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3747 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3748 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3749 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3750 DirectiveKindMap[".else"] = DK_ELSE;
3751 DirectiveKindMap[".endif"] = DK_ENDIF;
3752 DirectiveKindMap[".skip"] = DK_SKIP;
3753 DirectiveKindMap[".space"] = DK_SPACE;
3754 DirectiveKindMap[".file"] = DK_FILE;
3755 DirectiveKindMap[".line"] = DK_LINE;
3756 DirectiveKindMap[".loc"] = DK_LOC;
3757 DirectiveKindMap[".stabs"] = DK_STABS;
3758 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3759 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3760 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3761 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3762 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3763 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3764 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3765 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3766 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3767 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3768 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3769 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3770 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3771 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3772 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3773 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3774 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3775 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3776 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3777 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3778 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3779 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3780 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3781 DirectiveKindMap[".macro"] = DK_MACRO;
3782 DirectiveKindMap[".endm"] = DK_ENDM;
3783 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3784 DirectiveKindMap[".purgem"] = DK_PURGEM;
3788 MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3789 AsmToken EndToken, StartToken = getTok();
3791 unsigned NestLevel = 0;
3793 // Check whether we have reached the end of the file.
3794 if (getLexer().is(AsmToken::Eof)) {
3795 Error(DirectiveLoc, "no matching '.endr' in definition");
3799 if (Lexer.is(AsmToken::Identifier) &&
3800 (getTok().getIdentifier() == ".rept")) {
3804 // Otherwise, check whether we have reached the .endr.
3805 if (Lexer.is(AsmToken::Identifier) &&
3806 getTok().getIdentifier() == ".endr") {
3807 if (NestLevel == 0) {
3808 EndToken = getTok();
3810 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3811 TokError("unexpected token in '.endr' directive");
3819 // Otherwise, scan till the end of the statement.
3820 EatToEndOfStatement();
3823 const char *BodyStart = StartToken.getLoc().getPointer();
3824 const char *BodyEnd = EndToken.getLoc().getPointer();
3825 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3827 // We Are Anonymous.
3829 MCAsmMacroParameters Parameters;
3830 return new MCAsmMacro(Name, Body, Parameters);
3833 void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
3834 raw_svector_ostream &OS) {
3837 MemoryBuffer *Instantiation =
3838 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3840 // Create the macro instantiation object and add to the current macro
3841 // instantiation stack.
3842 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3846 ActiveMacros.push_back(MI);
3848 // Jump to the macro instantiation and prime the lexer.
3849 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3850 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3854 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3856 if (ParseAbsoluteExpression(Count))
3857 return TokError("unexpected token in '.rept' directive");
3860 return TokError("Count is negative");
3862 if (Lexer.isNot(AsmToken::EndOfStatement))
3863 return TokError("unexpected token in '.rept' directive");
3865 // Eat the end of statement.
3868 // Lex the rept definition.
3869 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3873 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3874 // to hold the macro body with substitutions.
3875 SmallString<256> Buf;
3876 MCAsmMacroParameters Parameters;
3877 MCAsmMacroArguments A;
3878 raw_svector_ostream OS(Buf);
3880 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3883 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3888 /// ParseDirectiveIrp
3889 /// ::= .irp symbol,values
3890 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3891 MCAsmMacroParameters Parameters;
3892 MCAsmMacroParameter Parameter;
3894 if (ParseIdentifier(Parameter.first))
3895 return TokError("expected identifier in '.irp' directive");
3897 Parameters.push_back(Parameter);
3899 if (Lexer.isNot(AsmToken::Comma))
3900 return TokError("expected comma in '.irp' directive");
3904 MCAsmMacroArguments A;
3905 if (ParseMacroArguments(0, A))
3908 // Eat the end of statement.
3911 // Lex the irp definition.
3912 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3916 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3917 // to hold the macro body with substitutions.
3918 SmallString<256> Buf;
3919 raw_svector_ostream OS(Buf);
3921 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3922 MCAsmMacroArguments Args;
3925 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3929 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3934 /// ParseDirectiveIrpc
3935 /// ::= .irpc symbol,values
3936 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3937 MCAsmMacroParameters Parameters;
3938 MCAsmMacroParameter Parameter;
3940 if (ParseIdentifier(Parameter.first))
3941 return TokError("expected identifier in '.irpc' directive");
3943 Parameters.push_back(Parameter);
3945 if (Lexer.isNot(AsmToken::Comma))
3946 return TokError("expected comma in '.irpc' directive");
3950 MCAsmMacroArguments A;
3951 if (ParseMacroArguments(0, A))
3954 if (A.size() != 1 || A.front().size() != 1)
3955 return TokError("unexpected token in '.irpc' directive");
3957 // Eat the end of statement.
3960 // Lex the irpc definition.
3961 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
3965 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3966 // to hold the macro body with substitutions.
3967 SmallString<256> Buf;
3968 raw_svector_ostream OS(Buf);
3970 StringRef Values = A.front().front().getString();
3971 std::size_t I, End = Values.size();
3972 for (I = 0; I < End; ++I) {
3973 MCAsmMacroArgument Arg;
3974 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3976 MCAsmMacroArguments Args;
3977 Args.push_back(Arg);
3979 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3983 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3988 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3989 if (ActiveMacros.empty())
3990 return TokError("unmatched '.endr' directive");
3992 // The only .repl that should get here are the ones created by
3993 // InstantiateMacroLikeBody.
3994 assert(getLexer().is(AsmToken::EndOfStatement));
4000 bool AsmParser::ParseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info, size_t Len) {
4001 const MCExpr *Value;
4002 SMLoc ExprLoc = getLexer().getLoc();
4003 if (ParseExpression(Value))
4005 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4007 return Error(ExprLoc, "unexpected expression in _emit");
4008 uint64_t IntValue = MCE->getValue();
4009 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4010 return Error(ExprLoc, "literal value out of range for directive");
4012 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4016 bool AsmParser::ParseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4017 const MCExpr *Value;
4018 SMLoc ExprLoc = getLexer().getLoc();
4019 if (ParseExpression(Value))
4021 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4023 return Error(ExprLoc, "unexpected expression in align");
4024 uint64_t IntValue = MCE->getValue();
4025 if (!isPowerOf2_64(IntValue))
4026 return Error(ExprLoc, "literal value not a power of two greater then zero");
4028 Info.AsmRewrites->push_back(AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4032 bool AsmStringSort (AsmRewrite A, AsmRewrite B) {
4033 return A.Loc.getPointer() < B.Loc.getPointer();
4036 bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
4037 unsigned &NumOutputs, unsigned &NumInputs,
4038 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4039 SmallVectorImpl<std::string> &Constraints,
4040 SmallVectorImpl<std::string> &Clobbers,
4041 const MCInstrInfo *MII,
4042 const MCInstPrinter *IP,
4043 MCAsmParserSemaCallback &SI) {
4044 SmallVector<void *, 4> InputDecls;
4045 SmallVector<void *, 4> OutputDecls;
4046 SmallVector<bool, 4> InputDeclsAddressOf;
4047 SmallVector<bool, 4> OutputDeclsAddressOf;
4048 SmallVector<std::string, 4> InputConstraints;
4049 SmallVector<std::string, 4> OutputConstraints;
4050 std::set<std::string> ClobberRegs;
4052 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
4057 // While we have input, parse each statement.
4058 unsigned InputIdx = 0;
4059 unsigned OutputIdx = 0;
4060 while (getLexer().isNot(AsmToken::Eof)) {
4061 ParseStatementInfo Info(&AsmStrRewrites);
4062 if (ParseStatement(Info))
4065 if (Info.ParseError)
4068 if (Info.Opcode != ~0U) {
4069 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4071 // Build the list of clobbers, outputs and inputs.
4072 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4073 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
4076 if (Operand->isImm()) {
4077 if (Operand->needAsmRewrite())
4078 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
4079 Operand->getStartLoc()));
4083 // Register operand.
4084 if (Operand->isReg() && !Operand->needAddressOf()) {
4085 unsigned NumDefs = Desc.getNumDefs();
4087 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
4089 raw_string_ostream OS(Reg);
4090 IP->printRegName(OS, Operand->getReg());
4091 ClobberRegs.insert(StringRef(OS.str()));
4096 // Expr/Input or Output.
4098 unsigned Length, Size, Type;
4099 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
4100 Length, Size, Type, IsVarDecl);
4102 bool isOutput = (i == 1) && Desc.mayStore();
4103 if (Operand->isMem() && Operand->needSizeDirective())
4104 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
4105 Operand->getStartLoc(),
4107 Operand->getMemSize()));
4109 std::string Constraint = "=";
4111 OutputDecls.push_back(OpDecl);
4112 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4113 Constraint += Operand->getConstraint().str();
4114 OutputConstraints.push_back(Constraint);
4115 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
4116 Operand->getStartLoc(),
4117 Operand->getNameLen()));
4119 InputDecls.push_back(OpDecl);
4120 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4121 InputConstraints.push_back(Operand->getConstraint().str());
4122 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
4123 Operand->getStartLoc(),
4124 Operand->getNameLen()));
4131 // Set the number of Outputs and Inputs.
4132 NumOutputs = OutputDecls.size();
4133 NumInputs = InputDecls.size();
4135 // Set the unique clobbers.
4136 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
4137 E = ClobberRegs.end(); I != E; ++I)
4138 Clobbers.push_back(*I);
4140 // Merge the various outputs and inputs. Output are expected first.
4141 if (NumOutputs || NumInputs) {
4142 unsigned NumExprs = NumOutputs + NumInputs;
4143 OpDecls.resize(NumExprs);
4144 Constraints.resize(NumExprs);
4145 for (unsigned i = 0; i < NumOutputs; ++i) {
4146 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4147 Constraints[i] = OutputConstraints[i];
4149 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4150 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4151 Constraints[j] = InputConstraints[i];
4155 // Build the IR assembly string.
4156 std::string AsmStringIR;
4157 AsmRewriteKind PrevKind = AOK_Imm;
4158 raw_string_ostream OS(AsmStringIR);
4159 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4160 std::sort (AsmStrRewrites.begin(), AsmStrRewrites.end(), AsmStringSort);
4161 for (SmallVectorImpl<struct AsmRewrite>::iterator
4162 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
4163 const char *Loc = (*I).Loc.getPointer();
4165 unsigned AdditionalSkip = 0;
4166 AsmRewriteKind Kind = (*I).Kind;
4168 // Emit everything up to the immediate/expression. If the previous rewrite
4169 // was a size directive, then this has already been done.
4170 if (PrevKind != AOK_SizeDirective)
4171 OS << StringRef(Start, Loc - Start);
4174 // Skip the original expression.
4175 if (Kind == AOK_Skip) {
4176 Start = Loc + (*I).Len;
4180 // Rewrite expressions in $N notation.
4198 case AOK_SizeDirective:
4201 case 8: OS << "byte ptr "; break;
4202 case 16: OS << "word ptr "; break;
4203 case 32: OS << "dword ptr "; break;
4204 case 64: OS << "qword ptr "; break;
4205 case 80: OS << "xword ptr "; break;
4206 case 128: OS << "xmmword ptr "; break;
4207 case 256: OS << "ymmword ptr "; break;
4214 unsigned Val = (*I).Val;
4215 OS << ".align " << Val;
4217 // Skip the original immediate.
4218 assert (Val < 10 && "Expected alignment less then 2^10.");
4219 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4222 case AOK_DotOperator:
4227 // Skip the original expression.
4228 if (Kind != AOK_SizeDirective)
4229 Start = Loc + (*I).Len + AdditionalSkip;
4232 // Emit the remainder of the asm string.
4233 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4234 if (Start != AsmEnd)
4235 OS << StringRef(Start, AsmEnd - Start);
4237 AsmString = OS.str();
4241 /// \brief Create an MCAsmParser instance.
4242 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
4243 MCContext &C, MCStreamer &Out,
4244 const MCAsmInfo &MAI) {
4245 return new AsmParser(SM, C, Out, MAI);