1//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class implements the parser for assembly files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SmallString.h"
17#include "llvm/ADT/StringMap.h"
18#include "llvm/ADT/Twine.h"
19#include "llvm/MC/MCAsmInfo.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCDwarf.h"
22#include "llvm/MC/MCExpr.h"
23#include "llvm/MC/MCInstPrinter.h"
24#include "llvm/MC/MCInstrInfo.h"
25#include "llvm/MC/MCObjectFileInfo.h"
26#include "llvm/MC/MCParser/AsmCond.h"
27#include "llvm/MC/MCParser/AsmLexer.h"
28#include "llvm/MC/MCParser/MCAsmParser.h"
29#include "llvm/MC/MCParser/MCAsmParserUtils.h"
30#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
31#include "llvm/MC/MCRegisterInfo.h"
32#include "llvm/MC/MCSectionMachO.h"
33#include "llvm/MC/MCStreamer.h"
34#include "llvm/MC/MCSymbol.h"
35#include "llvm/MC/MCTargetAsmParser.h"
36#include "llvm/MC/MCValue.h"
37#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/ErrorHandling.h"
39#include "llvm/Support/MathExtras.h"
40#include "llvm/Support/MemoryBuffer.h"
41#include "llvm/Support/SourceMgr.h"
42#include "llvm/Support/raw_ostream.h"
43#include <cctype>
44#include <deque>
45#include <set>
46#include <string>
47#include <vector>
48using namespace llvm;
49
50MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
51
52namespace {
53/// \brief Helper types for tracking macro definitions.
54typedef std::vector<AsmToken> MCAsmMacroArgument;
55typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
56
57struct MCAsmMacroParameter {
58  StringRef Name;
59  MCAsmMacroArgument Value;
60  bool Required;
61  bool Vararg;
62
63  MCAsmMacroParameter() : Required(false), Vararg(false) {}
64};
65
66typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
67
68struct MCAsmMacro {
69  StringRef Name;
70  StringRef Body;
71  MCAsmMacroParameters Parameters;
72
73public:
74  MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
75      : Name(N), Body(B), Parameters(std::move(P)) {}
76};
77
78/// \brief Helper class for storing information about an active macro
79/// instantiation.
80struct MacroInstantiation {
81  /// The location of the instantiation.
82  SMLoc InstantiationLoc;
83
84  /// The buffer where parsing should resume upon instantiation completion.
85  int ExitBuffer;
86
87  /// The location where parsing should resume upon instantiation completion.
88  SMLoc ExitLoc;
89
90  /// The depth of TheCondStack at the start of the instantiation.
91  size_t CondStackDepth;
92
93public:
94  MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
95};
96
97struct ParseStatementInfo {
98  /// \brief The parsed operands from the last parsed statement.
99  SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
100
101  /// \brief The opcode from the last parsed instruction.
102  unsigned Opcode;
103
104  /// \brief Was there an error parsing the inline assembly?
105  bool ParseError;
106
107  SmallVectorImpl<AsmRewrite> *AsmRewrites;
108
109  ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
110  ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
111    : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
112};
113
114/// \brief The concrete assembly parser instance.
115class AsmParser : public MCAsmParser {
116  AsmParser(const AsmParser &) = delete;
117  void operator=(const AsmParser &) = delete;
118private:
119  AsmLexer Lexer;
120  MCContext &Ctx;
121  MCStreamer &Out;
122  const MCAsmInfo &MAI;
123  SourceMgr &SrcMgr;
124  SourceMgr::DiagHandlerTy SavedDiagHandler;
125  void *SavedDiagContext;
126  std::unique_ptr<MCAsmParserExtension> PlatformParser;
127
128  /// This is the current buffer index we're lexing from as managed by the
129  /// SourceMgr object.
130  unsigned CurBuffer;
131
132  AsmCond TheCondState;
133  std::vector<AsmCond> TheCondStack;
134
135  /// \brief maps directive names to handler methods in parser
136  /// extensions. Extensions register themselves in this map by calling
137  /// addDirectiveHandler.
138  StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
139
140  /// \brief Map of currently defined macros.
141  StringMap<MCAsmMacro> MacroMap;
142
143  /// \brief Stack of active macro instantiations.
144  std::vector<MacroInstantiation*> ActiveMacros;
145
146  /// \brief List of bodies of anonymous macros.
147  std::deque<MCAsmMacro> MacroLikeBodies;
148
149  /// Boolean tracking whether macro substitution is enabled.
150  unsigned MacrosEnabledFlag : 1;
151
152  /// \brief Keeps track of how many .macro's have been instantiated.
153  unsigned NumOfMacroInstantiations;
154
155  /// Flag tracking whether any errors have been encountered.
156  unsigned HadError : 1;
157
158  /// The values from the last parsed cpp hash file line comment if any.
159  StringRef CppHashFilename;
160  int64_t CppHashLineNumber;
161  SMLoc CppHashLoc;
162  unsigned CppHashBuf;
163  /// When generating dwarf for assembly source files we need to calculate the
164  /// logical line number based on the last parsed cpp hash file line comment
165  /// and current line. Since this is slow and messes up the SourceMgr's
166  /// cache we save the last info we queried with SrcMgr.FindLineNumber().
167  SMLoc LastQueryIDLoc;
168  unsigned LastQueryBuffer;
169  unsigned LastQueryLine;
170
171  /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
172  unsigned AssemblerDialect;
173
174  /// \brief is Darwin compatibility enabled?
175  bool IsDarwin;
176
177  /// \brief Are we parsing ms-style inline assembly?
178  bool ParsingInlineAsm;
179
180public:
181  AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
182            const MCAsmInfo &MAI);
183  ~AsmParser() override;
184
185  bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
186
187  void addDirectiveHandler(StringRef Directive,
188                           ExtensionDirectiveHandler Handler) override {
189    ExtensionDirectiveMap[Directive] = Handler;
190  }
191
192  void addAliasForDirective(StringRef Directive, StringRef Alias) override {
193    DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
194  }
195
196public:
197  /// @name MCAsmParser Interface
198  /// {
199
200  SourceMgr &getSourceManager() override { return SrcMgr; }
201  MCAsmLexer &getLexer() override { return Lexer; }
202  MCContext &getContext() override { return Ctx; }
203  MCStreamer &getStreamer() override { return Out; }
204  unsigned getAssemblerDialect() override {
205    if (AssemblerDialect == ~0U)
206      return MAI.getAssemblerDialect();
207    else
208      return AssemblerDialect;
209  }
210  void setAssemblerDialect(unsigned i) override {
211    AssemblerDialect = i;
212  }
213
214  void Note(SMLoc L, const Twine &Msg,
215            ArrayRef<SMRange> Ranges = None) override;
216  bool Warning(SMLoc L, const Twine &Msg,
217               ArrayRef<SMRange> Ranges = None) override;
218  bool Error(SMLoc L, const Twine &Msg,
219             ArrayRef<SMRange> Ranges = None) override;
220
221  const AsmToken &Lex() override;
222
223  void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
224  bool isParsingInlineAsm() override { return ParsingInlineAsm; }
225
226  bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
227                        unsigned &NumOutputs, unsigned &NumInputs,
228                        SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
229                        SmallVectorImpl<std::string> &Constraints,
230                        SmallVectorImpl<std::string> &Clobbers,
231                        const MCInstrInfo *MII, const MCInstPrinter *IP,
232                        MCAsmParserSemaCallback &SI) override;
233
234  bool parseExpression(const MCExpr *&Res);
235  bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
236  bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
237  bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
238  bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
239                             SMLoc &EndLoc) override;
240  bool parseAbsoluteExpression(int64_t &Res) override;
241
242  /// \brief Parse an identifier or string (as a quoted identifier)
243  /// and set \p Res to the identifier contents.
244  bool parseIdentifier(StringRef &Res) override;
245  void eatToEndOfStatement() override;
246
247  void checkForValidSection() override;
248  /// }
249
250private:
251
252  bool parseStatement(ParseStatementInfo &Info,
253                      MCAsmParserSemaCallback *SI);
254  void eatToEndOfLine();
255  bool parseCppHashLineFilenameComment(SMLoc L);
256
257  void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
258                        ArrayRef<MCAsmMacroParameter> Parameters);
259  bool expandMacro(raw_svector_ostream &OS, StringRef Body,
260                   ArrayRef<MCAsmMacroParameter> Parameters,
261                   ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
262                   SMLoc L);
263
264  /// \brief Are macros enabled in the parser?
265  bool areMacrosEnabled() {return MacrosEnabledFlag;}
266
267  /// \brief Control a flag in the parser that enables or disables macros.
268  void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
269
270  /// \brief Lookup a previously defined macro.
271  /// \param Name Macro name.
272  /// \returns Pointer to macro. NULL if no such macro was defined.
273  const MCAsmMacro* lookupMacro(StringRef Name);
274
275  /// \brief Define a new macro with the given name and information.
276  void defineMacro(StringRef Name, MCAsmMacro Macro);
277
278  /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
279  void undefineMacro(StringRef Name);
280
281  /// \brief Are we inside a macro instantiation?
282  bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
283
284  /// \brief Handle entry to macro instantiation.
285  ///
286  /// \param M The macro.
287  /// \param NameLoc Instantiation location.
288  bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
289
290  /// \brief Handle exit from macro instantiation.
291  void handleMacroExit();
292
293  /// \brief Extract AsmTokens for a macro argument.
294  bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
295
296  /// \brief Parse all macro arguments for a given macro.
297  bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
298
299  void printMacroInstantiations();
300  void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
301                    ArrayRef<SMRange> Ranges = None) const {
302    SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
303  }
304  static void DiagHandler(const SMDiagnostic &Diag, void *Context);
305
306  /// \brief Enter the specified file. This returns true on failure.
307  bool enterIncludeFile(const std::string &Filename);
308
309  /// \brief Process the specified file for the .incbin directive.
310  /// This returns true on failure.
311  bool processIncbinFile(const std::string &Filename);
312
313  /// \brief Reset the current lexer position to that given by \p Loc. The
314  /// current token is not set; clients should ensure Lex() is called
315  /// subsequently.
316  ///
317  /// \param InBuffer If not 0, should be the known buffer id that contains the
318  /// location.
319  void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
320
321  /// \brief Parse up to the end of statement and a return the contents from the
322  /// current token until the end of the statement; the current token on exit
323  /// will be either the EndOfStatement or EOF.
324  StringRef parseStringToEndOfStatement() override;
325
326  /// \brief Parse until the end of a statement or a comma is encountered,
327  /// return the contents from the current token up to the end or comma.
328  StringRef parseStringToComma();
329
330  bool parseAssignment(StringRef Name, bool allow_redef,
331                       bool NoDeadStrip = false);
332
333  unsigned getBinOpPrecedence(AsmToken::TokenKind K,
334                              MCBinaryExpr::Opcode &Kind);
335
336  bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
337  bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
338  bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
339
340  bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
341
342  // Generic (target and platform independent) directive parsing.
343  enum DirectiveKind {
344    DK_NO_DIRECTIVE, // Placeholder
345    DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
346    DK_RELOC,
347    DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
348    DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
349    DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
350    DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
351    DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
352    DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
353    DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
354    DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
355    DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
356    DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
357    DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
358    DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
359    DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
360    DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
361    DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
362    DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
363    DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
364    DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
365    DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
366    DK_MACROS_ON, DK_MACROS_OFF,
367    DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
368    DK_SLEB128, DK_ULEB128,
369    DK_ERR, DK_ERROR, DK_WARNING,
370    DK_END
371  };
372
373  /// \brief Maps directive name --> DirectiveKind enum, for
374  /// directives parsed by this class.
375  StringMap<DirectiveKind> DirectiveKindMap;
376
377  // ".ascii", ".asciz", ".string"
378  bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
379  bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
380  bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
381  bool parseDirectiveOctaValue(); // ".octa"
382  bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
383  bool parseDirectiveFill(); // ".fill"
384  bool parseDirectiveZero(); // ".zero"
385  // ".set", ".equ", ".equiv"
386  bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
387  bool parseDirectiveOrg(); // ".org"
388  // ".align{,32}", ".p2align{,w,l}"
389  bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
390
391  // ".file", ".line", ".loc", ".stabs"
392  bool parseDirectiveFile(SMLoc DirectiveLoc);
393  bool parseDirectiveLine();
394  bool parseDirectiveLoc();
395  bool parseDirectiveStabs();
396
397  // .cfi directives
398  bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
399  bool parseDirectiveCFIWindowSave();
400  bool parseDirectiveCFISections();
401  bool parseDirectiveCFIStartProc();
402  bool parseDirectiveCFIEndProc();
403  bool parseDirectiveCFIDefCfaOffset();
404  bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
405  bool parseDirectiveCFIAdjustCfaOffset();
406  bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
407  bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
408  bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
409  bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
410  bool parseDirectiveCFIRememberState();
411  bool parseDirectiveCFIRestoreState();
412  bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
413  bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
414  bool parseDirectiveCFIEscape();
415  bool parseDirectiveCFISignalFrame();
416  bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
417
418  // macro directives
419  bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
420  bool parseDirectiveExitMacro(StringRef Directive);
421  bool parseDirectiveEndMacro(StringRef Directive);
422  bool parseDirectiveMacro(SMLoc DirectiveLoc);
423  bool parseDirectiveMacrosOnOff(StringRef Directive);
424
425  // ".bundle_align_mode"
426  bool parseDirectiveBundleAlignMode();
427  // ".bundle_lock"
428  bool parseDirectiveBundleLock();
429  // ".bundle_unlock"
430  bool parseDirectiveBundleUnlock();
431
432  // ".space", ".skip"
433  bool parseDirectiveSpace(StringRef IDVal);
434
435  // .sleb128 (Signed=true) and .uleb128 (Signed=false)
436  bool parseDirectiveLEB128(bool Signed);
437
438  /// \brief Parse a directive like ".globl" which
439  /// accepts a single symbol (which should be a label or an external).
440  bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
441
442  bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
443
444  bool parseDirectiveAbort(); // ".abort"
445  bool parseDirectiveInclude(); // ".include"
446  bool parseDirectiveIncbin(); // ".incbin"
447
448  // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
449  bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
450  // ".ifb" or ".ifnb", depending on ExpectBlank.
451  bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
452  // ".ifc" or ".ifnc", depending on ExpectEqual.
453  bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
454  // ".ifeqs" or ".ifnes", depending on ExpectEqual.
455  bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
456  // ".ifdef" or ".ifndef", depending on expect_defined
457  bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
458  bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
459  bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
460  bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
461  bool parseEscapedString(std::string &Data) override;
462
463  const MCExpr *applyModifierToExpr(const MCExpr *E,
464                                    MCSymbolRefExpr::VariantKind Variant);
465
466  // Macro-like directives
467  MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
468  void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
469                                raw_svector_ostream &OS);
470  bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
471  bool parseDirectiveIrp(SMLoc DirectiveLoc);  // ".irp"
472  bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
473  bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
474
475  // "_emit" or "__emit"
476  bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
477                            size_t Len);
478
479  // "align"
480  bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
481
482  // "end"
483  bool parseDirectiveEnd(SMLoc DirectiveLoc);
484
485  // ".err" or ".error"
486  bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
487
488  // ".warning"
489  bool parseDirectiveWarning(SMLoc DirectiveLoc);
490
491  void initializeDirectiveKindMap();
492};
493}
494
495namespace llvm {
496
497extern MCAsmParserExtension *createDarwinAsmParser();
498extern MCAsmParserExtension *createELFAsmParser();
499extern MCAsmParserExtension *createCOFFAsmParser();
500
501}
502
503enum { DEFAULT_ADDRSPACE = 0 };
504
505AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
506                     const MCAsmInfo &MAI)
507    : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
508      PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
509      MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
510      AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
511  // Save the old handler.
512  SavedDiagHandler = SrcMgr.getDiagHandler();
513  SavedDiagContext = SrcMgr.getDiagContext();
514  // Set our own handler which calls the saved handler.
515  SrcMgr.setDiagHandler(DiagHandler, this);
516  Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
517
518  // Initialize the platform / file format parser.
519  switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
520  case MCObjectFileInfo::IsCOFF:
521    PlatformParser.reset(createCOFFAsmParser());
522    break;
523  case MCObjectFileInfo::IsMachO:
524    PlatformParser.reset(createDarwinAsmParser());
525    IsDarwin = true;
526    break;
527  case MCObjectFileInfo::IsELF:
528    PlatformParser.reset(createELFAsmParser());
529    break;
530  }
531
532  PlatformParser->Initialize(*this);
533  initializeDirectiveKindMap();
534
535  NumOfMacroInstantiations = 0;
536}
537
538AsmParser::~AsmParser() {
539  assert((HadError || ActiveMacros.empty()) &&
540         "Unexpected active macro instantiation!");
541}
542
543void AsmParser::printMacroInstantiations() {
544  // Print the active macro instantiation stack.
545  for (std::vector<MacroInstantiation *>::const_reverse_iterator
546           it = ActiveMacros.rbegin(),
547           ie = ActiveMacros.rend();
548       it != ie; ++it)
549    printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
550                 "while in macro instantiation");
551}
552
553void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
554  printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
555  printMacroInstantiations();
556}
557
558bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
559  if(getTargetParser().getTargetOptions().MCNoWarn)
560    return false;
561  if (getTargetParser().getTargetOptions().MCFatalWarnings)
562    return Error(L, Msg, Ranges);
563  printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
564  printMacroInstantiations();
565  return false;
566}
567
568bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
569  HadError = true;
570  printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
571  printMacroInstantiations();
572  return true;
573}
574
575bool AsmParser::enterIncludeFile(const std::string &Filename) {
576  std::string IncludedFile;
577  unsigned NewBuf =
578      SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
579  if (!NewBuf)
580    return true;
581
582  CurBuffer = NewBuf;
583  Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
584  return false;
585}
586
587/// Process the specified .incbin file by searching for it in the include paths
588/// then just emitting the byte contents of the file to the streamer. This
589/// returns true on failure.
590bool AsmParser::processIncbinFile(const std::string &Filename) {
591  std::string IncludedFile;
592  unsigned NewBuf =
593      SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
594  if (!NewBuf)
595    return true;
596
597  // Pick up the bytes from the file and emit them.
598  getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
599  return false;
600}
601
602void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
603  CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
604  Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
605                  Loc.getPointer());
606}
607
608const AsmToken &AsmParser::Lex() {
609  const AsmToken *tok = &Lexer.Lex();
610
611  if (tok->is(AsmToken::Eof)) {
612    // If this is the end of an included file, pop the parent file off the
613    // include stack.
614    SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
615    if (ParentIncludeLoc != SMLoc()) {
616      jumpToLoc(ParentIncludeLoc);
617      tok = &Lexer.Lex();
618    }
619  }
620
621  if (tok->is(AsmToken::Error))
622    Error(Lexer.getErrLoc(), Lexer.getErr());
623
624  return *tok;
625}
626
627bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
628  // Create the initial section, if requested.
629  if (!NoInitialTextSection)
630    Out.InitSections(false);
631
632  // Prime the lexer.
633  Lex();
634
635  HadError = false;
636  AsmCond StartingCondState = TheCondState;
637
638  // If we are generating dwarf for assembly source files save the initial text
639  // section and generate a .file directive.
640  if (getContext().getGenDwarfForAssembly()) {
641    MCSection *Sec = getStreamer().getCurrentSection().first;
642    if (!Sec->getBeginSymbol()) {
643      MCSymbol *SectionStartSym = getContext().createTempSymbol();
644      getStreamer().EmitLabel(SectionStartSym);
645      Sec->setBeginSymbol(SectionStartSym);
646    }
647    bool InsertResult = getContext().addGenDwarfSection(Sec);
648    assert(InsertResult && ".text section should not have debug info yet");
649    (void)InsertResult;
650    getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
651        0, StringRef(), getContext().getMainFileName()));
652  }
653
654  // While we have input, parse each statement.
655  while (Lexer.isNot(AsmToken::Eof)) {
656    ParseStatementInfo Info;
657    if (!parseStatement(Info, nullptr))
658      continue;
659
660    // We had an error, validate that one was emitted and recover by skipping to
661    // the next line.
662    assert(HadError && "Parse statement returned an error, but none emitted!");
663    eatToEndOfStatement();
664  }
665
666  if (TheCondState.TheCond != StartingCondState.TheCond ||
667      TheCondState.Ignore != StartingCondState.Ignore)
668    return TokError("unmatched .ifs or .elses");
669
670  // Check to see there are no empty DwarfFile slots.
671  const auto &LineTables = getContext().getMCDwarfLineTables();
672  if (!LineTables.empty()) {
673    unsigned Index = 0;
674    for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
675      if (File.Name.empty() && Index != 0)
676        TokError("unassigned file number: " + Twine(Index) +
677                 " for .file directives");
678      ++Index;
679    }
680  }
681
682  // Check to see that all assembler local symbols were actually defined.
683  // Targets that don't do subsections via symbols may not want this, though,
684  // so conservatively exclude them. Only do this if we're finalizing, though,
685  // as otherwise we won't necessarilly have seen everything yet.
686  if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
687    for (const auto &TableEntry : getContext().getSymbols()) {
688      MCSymbol *Sym = TableEntry.getValue();
689      // Variable symbols may not be marked as defined, so check those
690      // explicitly. If we know it's a variable, we have a definition for
691      // the purposes of this check.
692      if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
693        // FIXME: We would really like to refer back to where the symbol was
694        // first referenced for a source location. We need to add something
695        // to track that. Currently, we just point to the end of the file.
696        return Error(getLexer().getLoc(), "assembler local symbol '" +
697                                              Sym->getName() + "' not defined");
698    }
699  }
700
701  // Finalize the output stream if there are no errors and if the client wants
702  // us to.
703  if (!HadError && !NoFinalize)
704    Out.Finish();
705
706  return HadError || getContext().hadError();
707}
708
709void AsmParser::checkForValidSection() {
710  if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
711    TokError("expected section directive before assembly directive");
712    Out.InitSections(false);
713  }
714}
715
716/// \brief Throw away the rest of the line for testing purposes.
717void AsmParser::eatToEndOfStatement() {
718  while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
719    Lex();
720
721  // Eat EOL.
722  if (Lexer.is(AsmToken::EndOfStatement))
723    Lex();
724}
725
726StringRef AsmParser::parseStringToEndOfStatement() {
727  const char *Start = getTok().getLoc().getPointer();
728
729  while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
730    Lex();
731
732  const char *End = getTok().getLoc().getPointer();
733  return StringRef(Start, End - Start);
734}
735
736StringRef AsmParser::parseStringToComma() {
737  const char *Start = getTok().getLoc().getPointer();
738
739  while (Lexer.isNot(AsmToken::EndOfStatement) &&
740         Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
741    Lex();
742
743  const char *End = getTok().getLoc().getPointer();
744  return StringRef(Start, End - Start);
745}
746
747/// \brief Parse a paren expression and return it.
748/// NOTE: This assumes the leading '(' has already been consumed.
749///
750/// parenexpr ::= expr)
751///
752bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
753  if (parseExpression(Res))
754    return true;
755  if (Lexer.isNot(AsmToken::RParen))
756    return TokError("expected ')' in parentheses expression");
757  EndLoc = Lexer.getTok().getEndLoc();
758  Lex();
759  return false;
760}
761
762/// \brief Parse a bracket expression and return it.
763/// NOTE: This assumes the leading '[' has already been consumed.
764///
765/// bracketexpr ::= expr]
766///
767bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
768  if (parseExpression(Res))
769    return true;
770  if (Lexer.isNot(AsmToken::RBrac))
771    return TokError("expected ']' in brackets expression");
772  EndLoc = Lexer.getTok().getEndLoc();
773  Lex();
774  return false;
775}
776
777/// \brief Parse a primary expression and return it.
778///  primaryexpr ::= (parenexpr
779///  primaryexpr ::= symbol
780///  primaryexpr ::= number
781///  primaryexpr ::= '.'
782///  primaryexpr ::= ~,+,- primaryexpr
783bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
784  SMLoc FirstTokenLoc = getLexer().getLoc();
785  AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
786  switch (FirstTokenKind) {
787  default:
788    return TokError("unknown token in expression");
789  // If we have an error assume that we've already handled it.
790  case AsmToken::Error:
791    return true;
792  case AsmToken::Exclaim:
793    Lex(); // Eat the operator.
794    if (parsePrimaryExpr(Res, EndLoc))
795      return true;
796    Res = MCUnaryExpr::createLNot(Res, getContext());
797    return false;
798  case AsmToken::Dollar:
799  case AsmToken::At:
800  case AsmToken::String:
801  case AsmToken::Identifier: {
802    StringRef Identifier;
803    if (parseIdentifier(Identifier)) {
804      if (FirstTokenKind == AsmToken::Dollar) {
805        if (Lexer.getMAI().getDollarIsPC()) {
806          // This is a '$' reference, which references the current PC.  Emit a
807          // temporary label to the streamer and refer to it.
808          MCSymbol *Sym = Ctx.createTempSymbol();
809          Out.EmitLabel(Sym);
810          Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
811                                        getContext());
812          EndLoc = FirstTokenLoc;
813          return false;
814        }
815        return Error(FirstTokenLoc, "invalid token in expression");
816      }
817    }
818    // Parse symbol variant
819    std::pair<StringRef, StringRef> Split;
820    if (!MAI.useParensForSymbolVariant()) {
821      if (FirstTokenKind == AsmToken::String) {
822        if (Lexer.is(AsmToken::At)) {
823          Lexer.Lex(); // eat @
824          SMLoc AtLoc = getLexer().getLoc();
825          StringRef VName;
826          if (parseIdentifier(VName))
827            return Error(AtLoc, "expected symbol variant after '@'");
828
829          Split = std::make_pair(Identifier, VName);
830        }
831      } else {
832        Split = Identifier.split('@');
833      }
834    } else if (Lexer.is(AsmToken::LParen)) {
835      Lexer.Lex(); // eat (
836      StringRef VName;
837      parseIdentifier(VName);
838      if (Lexer.isNot(AsmToken::RParen)) {
839          return Error(Lexer.getTok().getLoc(),
840                       "unexpected token in variant, expected ')'");
841      }
842      Lexer.Lex(); // eat )
843      Split = std::make_pair(Identifier, VName);
844    }
845
846    EndLoc = SMLoc::getFromPointer(Identifier.end());
847
848    // This is a symbol reference.
849    StringRef SymbolName = Identifier;
850    MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
851
852    // Lookup the symbol variant if used.
853    if (Split.second.size()) {
854      Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
855      if (Variant != MCSymbolRefExpr::VK_Invalid) {
856        SymbolName = Split.first;
857      } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
858        Variant = MCSymbolRefExpr::VK_None;
859      } else {
860        return Error(SMLoc::getFromPointer(Split.second.begin()),
861                     "invalid variant '" + Split.second + "'");
862      }
863    }
864
865    MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
866
867    // If this is an absolute variable reference, substitute it now to preserve
868    // semantics in the face of reassignment.
869    if (Sym->isVariable() &&
870        isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
871      if (Variant)
872        return Error(EndLoc, "unexpected modifier on variable reference");
873
874      Res = Sym->getVariableValue(/*SetUsed*/ false);
875      return false;
876    }
877
878    // Otherwise create a symbol ref.
879    Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
880    return false;
881  }
882  case AsmToken::BigNum:
883    return TokError("literal value out of range for directive");
884  case AsmToken::Integer: {
885    SMLoc Loc = getTok().getLoc();
886    int64_t IntVal = getTok().getIntVal();
887    Res = MCConstantExpr::create(IntVal, getContext());
888    EndLoc = Lexer.getTok().getEndLoc();
889    Lex(); // Eat token.
890    // Look for 'b' or 'f' following an Integer as a directional label
891    if (Lexer.getKind() == AsmToken::Identifier) {
892      StringRef IDVal = getTok().getString();
893      // Lookup the symbol variant if used.
894      std::pair<StringRef, StringRef> Split = IDVal.split('@');
895      MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
896      if (Split.first.size() != IDVal.size()) {
897        Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
898        if (Variant == MCSymbolRefExpr::VK_Invalid)
899          return TokError("invalid variant '" + Split.second + "'");
900        IDVal = Split.first;
901      }
902      if (IDVal == "f" || IDVal == "b") {
903        MCSymbol *Sym =
904            Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
905        Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
906        if (IDVal == "b" && Sym->isUndefined())
907          return Error(Loc, "invalid reference to undefined symbol");
908        EndLoc = Lexer.getTok().getEndLoc();
909        Lex(); // Eat identifier.
910      }
911    }
912    return false;
913  }
914  case AsmToken::Real: {
915    APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
916    uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
917    Res = MCConstantExpr::create(IntVal, getContext());
918    EndLoc = Lexer.getTok().getEndLoc();
919    Lex(); // Eat token.
920    return false;
921  }
922  case AsmToken::Dot: {
923    // This is a '.' reference, which references the current PC.  Emit a
924    // temporary label to the streamer and refer to it.
925    MCSymbol *Sym = Ctx.createTempSymbol();
926    Out.EmitLabel(Sym);
927    Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
928    EndLoc = Lexer.getTok().getEndLoc();
929    Lex(); // Eat identifier.
930    return false;
931  }
932  case AsmToken::LParen:
933    Lex(); // Eat the '('.
934    return parseParenExpr(Res, EndLoc);
935  case AsmToken::LBrac:
936    if (!PlatformParser->HasBracketExpressions())
937      return TokError("brackets expression not supported on this target");
938    Lex(); // Eat the '['.
939    return parseBracketExpr(Res, EndLoc);
940  case AsmToken::Minus:
941    Lex(); // Eat the operator.
942    if (parsePrimaryExpr(Res, EndLoc))
943      return true;
944    Res = MCUnaryExpr::createMinus(Res, getContext());
945    return false;
946  case AsmToken::Plus:
947    Lex(); // Eat the operator.
948    if (parsePrimaryExpr(Res, EndLoc))
949      return true;
950    Res = MCUnaryExpr::createPlus(Res, getContext());
951    return false;
952  case AsmToken::Tilde:
953    Lex(); // Eat the operator.
954    if (parsePrimaryExpr(Res, EndLoc))
955      return true;
956    Res = MCUnaryExpr::createNot(Res, getContext());
957    return false;
958  }
959}
960
961bool AsmParser::parseExpression(const MCExpr *&Res) {
962  SMLoc EndLoc;
963  return parseExpression(Res, EndLoc);
964}
965
966const MCExpr *
967AsmParser::applyModifierToExpr(const MCExpr *E,
968                               MCSymbolRefExpr::VariantKind Variant) {
969  // Ask the target implementation about this expression first.
970  const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
971  if (NewE)
972    return NewE;
973  // Recurse over the given expression, rebuilding it to apply the given variant
974  // if there is exactly one symbol.
975  switch (E->getKind()) {
976  case MCExpr::Target:
977  case MCExpr::Constant:
978    return nullptr;
979
980  case MCExpr::SymbolRef: {
981    const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
982
983    if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
984      TokError("invalid variant on expression '" + getTok().getIdentifier() +
985               "' (already modified)");
986      return E;
987    }
988
989    return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
990  }
991
992  case MCExpr::Unary: {
993    const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
994    const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
995    if (!Sub)
996      return nullptr;
997    return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
998  }
999
1000  case MCExpr::Binary: {
1001    const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1002    const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1003    const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1004
1005    if (!LHS && !RHS)
1006      return nullptr;
1007
1008    if (!LHS)
1009      LHS = BE->getLHS();
1010    if (!RHS)
1011      RHS = BE->getRHS();
1012
1013    return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1014  }
1015  }
1016
1017  llvm_unreachable("Invalid expression kind!");
1018}
1019
1020/// \brief Parse an expression and return it.
1021///
1022///  expr ::= expr &&,|| expr               -> lowest.
1023///  expr ::= expr |,^,&,! expr
1024///  expr ::= expr ==,!=,<>,<,<=,>,>= expr
1025///  expr ::= expr <<,>> expr
1026///  expr ::= expr +,- expr
1027///  expr ::= expr *,/,% expr               -> highest.
1028///  expr ::= primaryexpr
1029///
1030bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1031  // Parse the expression.
1032  Res = nullptr;
1033  if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1034    return true;
1035
1036  // As a special case, we support 'a op b @ modifier' by rewriting the
1037  // expression to include the modifier. This is inefficient, but in general we
1038  // expect users to use 'a@modifier op b'.
1039  if (Lexer.getKind() == AsmToken::At) {
1040    Lex();
1041
1042    if (Lexer.isNot(AsmToken::Identifier))
1043      return TokError("unexpected symbol modifier following '@'");
1044
1045    MCSymbolRefExpr::VariantKind Variant =
1046        MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1047    if (Variant == MCSymbolRefExpr::VK_Invalid)
1048      return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1049
1050    const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1051    if (!ModifiedRes) {
1052      return TokError("invalid modifier '" + getTok().getIdentifier() +
1053                      "' (no symbols present)");
1054    }
1055
1056    Res = ModifiedRes;
1057    Lex();
1058  }
1059
1060  // Try to constant fold it up front, if possible.
1061  int64_t Value;
1062  if (Res->evaluateAsAbsolute(Value))
1063    Res = MCConstantExpr::create(Value, getContext());
1064
1065  return false;
1066}
1067
1068bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1069  Res = nullptr;
1070  return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1071}
1072
1073bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1074                                      SMLoc &EndLoc) {
1075  if (parseParenExpr(Res, EndLoc))
1076    return true;
1077
1078  for (; ParenDepth > 0; --ParenDepth) {
1079    if (parseBinOpRHS(1, Res, EndLoc))
1080      return true;
1081
1082    // We don't Lex() the last RParen.
1083    // This is the same behavior as parseParenExpression().
1084    if (ParenDepth - 1 > 0) {
1085      if (Lexer.isNot(AsmToken::RParen))
1086        return TokError("expected ')' in parentheses expression");
1087      EndLoc = Lexer.getTok().getEndLoc();
1088      Lex();
1089    }
1090  }
1091  return false;
1092}
1093
1094bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1095  const MCExpr *Expr;
1096
1097  SMLoc StartLoc = Lexer.getLoc();
1098  if (parseExpression(Expr))
1099    return true;
1100
1101  if (!Expr->evaluateAsAbsolute(Res))
1102    return Error(StartLoc, "expected absolute expression");
1103
1104  return false;
1105}
1106
1107static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1108                                         MCBinaryExpr::Opcode &Kind,
1109                                         bool ShouldUseLogicalShr) {
1110  switch (K) {
1111  default:
1112    return 0; // not a binop.
1113
1114  // Lowest Precedence: &&, ||
1115  case AsmToken::AmpAmp:
1116    Kind = MCBinaryExpr::LAnd;
1117    return 1;
1118  case AsmToken::PipePipe:
1119    Kind = MCBinaryExpr::LOr;
1120    return 1;
1121
1122  // Low Precedence: |, &, ^
1123  //
1124  // FIXME: gas seems to support '!' as an infix operator?
1125  case AsmToken::Pipe:
1126    Kind = MCBinaryExpr::Or;
1127    return 2;
1128  case AsmToken::Caret:
1129    Kind = MCBinaryExpr::Xor;
1130    return 2;
1131  case AsmToken::Amp:
1132    Kind = MCBinaryExpr::And;
1133    return 2;
1134
1135  // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1136  case AsmToken::EqualEqual:
1137    Kind = MCBinaryExpr::EQ;
1138    return 3;
1139  case AsmToken::ExclaimEqual:
1140  case AsmToken::LessGreater:
1141    Kind = MCBinaryExpr::NE;
1142    return 3;
1143  case AsmToken::Less:
1144    Kind = MCBinaryExpr::LT;
1145    return 3;
1146  case AsmToken::LessEqual:
1147    Kind = MCBinaryExpr::LTE;
1148    return 3;
1149  case AsmToken::Greater:
1150    Kind = MCBinaryExpr::GT;
1151    return 3;
1152  case AsmToken::GreaterEqual:
1153    Kind = MCBinaryExpr::GTE;
1154    return 3;
1155
1156  // Intermediate Precedence: <<, >>
1157  case AsmToken::LessLess:
1158    Kind = MCBinaryExpr::Shl;
1159    return 4;
1160  case AsmToken::GreaterGreater:
1161    Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1162    return 4;
1163
1164  // High Intermediate Precedence: +, -
1165  case AsmToken::Plus:
1166    Kind = MCBinaryExpr::Add;
1167    return 5;
1168  case AsmToken::Minus:
1169    Kind = MCBinaryExpr::Sub;
1170    return 5;
1171
1172  // Highest Precedence: *, /, %
1173  case AsmToken::Star:
1174    Kind = MCBinaryExpr::Mul;
1175    return 6;
1176  case AsmToken::Slash:
1177    Kind = MCBinaryExpr::Div;
1178    return 6;
1179  case AsmToken::Percent:
1180    Kind = MCBinaryExpr::Mod;
1181    return 6;
1182  }
1183}
1184
1185static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1186                                      MCBinaryExpr::Opcode &Kind,
1187                                      bool ShouldUseLogicalShr) {
1188  switch (K) {
1189  default:
1190    return 0; // not a binop.
1191
1192  // Lowest Precedence: &&, ||
1193  case AsmToken::AmpAmp:
1194    Kind = MCBinaryExpr::LAnd;
1195    return 2;
1196  case AsmToken::PipePipe:
1197    Kind = MCBinaryExpr::LOr;
1198    return 1;
1199
1200  // Low Precedence: ==, !=, <>, <, <=, >, >=
1201  case AsmToken::EqualEqual:
1202    Kind = MCBinaryExpr::EQ;
1203    return 3;
1204  case AsmToken::ExclaimEqual:
1205  case AsmToken::LessGreater:
1206    Kind = MCBinaryExpr::NE;
1207    return 3;
1208  case AsmToken::Less:
1209    Kind = MCBinaryExpr::LT;
1210    return 3;
1211  case AsmToken::LessEqual:
1212    Kind = MCBinaryExpr::LTE;
1213    return 3;
1214  case AsmToken::Greater:
1215    Kind = MCBinaryExpr::GT;
1216    return 3;
1217  case AsmToken::GreaterEqual:
1218    Kind = MCBinaryExpr::GTE;
1219    return 3;
1220
1221  // Low Intermediate Precedence: +, -
1222  case AsmToken::Plus:
1223    Kind = MCBinaryExpr::Add;
1224    return 4;
1225  case AsmToken::Minus:
1226    Kind = MCBinaryExpr::Sub;
1227    return 4;
1228
1229  // High Intermediate Precedence: |, &, ^
1230  //
1231  // FIXME: gas seems to support '!' as an infix operator?
1232  case AsmToken::Pipe:
1233    Kind = MCBinaryExpr::Or;
1234    return 5;
1235  case AsmToken::Caret:
1236    Kind = MCBinaryExpr::Xor;
1237    return 5;
1238  case AsmToken::Amp:
1239    Kind = MCBinaryExpr::And;
1240    return 5;
1241
1242  // Highest Precedence: *, /, %, <<, >>
1243  case AsmToken::Star:
1244    Kind = MCBinaryExpr::Mul;
1245    return 6;
1246  case AsmToken::Slash:
1247    Kind = MCBinaryExpr::Div;
1248    return 6;
1249  case AsmToken::Percent:
1250    Kind = MCBinaryExpr::Mod;
1251    return 6;
1252  case AsmToken::LessLess:
1253    Kind = MCBinaryExpr::Shl;
1254    return 6;
1255  case AsmToken::GreaterGreater:
1256    Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1257    return 6;
1258  }
1259}
1260
1261unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1262                                       MCBinaryExpr::Opcode &Kind) {
1263  bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1264  return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1265                  : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1266}
1267
1268/// \brief Parse all binary operators with precedence >= 'Precedence'.
1269/// Res contains the LHS of the expression on input.
1270bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1271                              SMLoc &EndLoc) {
1272  while (1) {
1273    MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1274    unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1275
1276    // If the next token is lower precedence than we are allowed to eat, return
1277    // successfully with what we ate already.
1278    if (TokPrec < Precedence)
1279      return false;
1280
1281    Lex();
1282
1283    // Eat the next primary expression.
1284    const MCExpr *RHS;
1285    if (parsePrimaryExpr(RHS, EndLoc))
1286      return true;
1287
1288    // If BinOp binds less tightly with RHS than the operator after RHS, let
1289    // the pending operator take RHS as its LHS.
1290    MCBinaryExpr::Opcode Dummy;
1291    unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1292    if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1293      return true;
1294
1295    // Merge LHS and RHS according to operator.
1296    Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
1297  }
1298}
1299
1300/// ParseStatement:
1301///   ::= EndOfStatement
1302///   ::= Label* Directive ...Operands... EndOfStatement
1303///   ::= Label* Identifier OperandList* EndOfStatement
1304bool AsmParser::parseStatement(ParseStatementInfo &Info,
1305                               MCAsmParserSemaCallback *SI) {
1306  if (Lexer.is(AsmToken::EndOfStatement)) {
1307    Out.AddBlankLine();
1308    Lex();
1309    return false;
1310  }
1311
1312  // Statements always start with an identifier or are a full line comment.
1313  AsmToken ID = getTok();
1314  SMLoc IDLoc = ID.getLoc();
1315  StringRef IDVal;
1316  int64_t LocalLabelVal = -1;
1317  // A full line comment is a '#' as the first token.
1318  if (Lexer.is(AsmToken::Hash))
1319    return parseCppHashLineFilenameComment(IDLoc);
1320
1321  // Allow an integer followed by a ':' as a directional local label.
1322  if (Lexer.is(AsmToken::Integer)) {
1323    LocalLabelVal = getTok().getIntVal();
1324    if (LocalLabelVal < 0) {
1325      if (!TheCondState.Ignore)
1326        return TokError("unexpected token at start of statement");
1327      IDVal = "";
1328    } else {
1329      IDVal = getTok().getString();
1330      Lex(); // Consume the integer token to be used as an identifier token.
1331      if (Lexer.getKind() != AsmToken::Colon) {
1332        if (!TheCondState.Ignore)
1333          return TokError("unexpected token at start of statement");
1334      }
1335    }
1336  } else if (Lexer.is(AsmToken::Dot)) {
1337    // Treat '.' as a valid identifier in this context.
1338    Lex();
1339    IDVal = ".";
1340  } else if (Lexer.is(AsmToken::LCurly)) {
1341    // Treat '{' as a valid identifier in this context.
1342    Lex();
1343    IDVal = "{";
1344
1345  } else if (Lexer.is(AsmToken::RCurly)) {
1346    // Treat '}' as a valid identifier in this context.
1347    Lex();
1348    IDVal = "}";
1349  } else if (parseIdentifier(IDVal)) {
1350    if (!TheCondState.Ignore)
1351      return TokError("unexpected token at start of statement");
1352    IDVal = "";
1353  }
1354
1355  // Handle conditional assembly here before checking for skipping.  We
1356  // have to do this so that .endif isn't skipped in a ".if 0" block for
1357  // example.
1358  StringMap<DirectiveKind>::const_iterator DirKindIt =
1359      DirectiveKindMap.find(IDVal);
1360  DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1361                              ? DK_NO_DIRECTIVE
1362                              : DirKindIt->getValue();
1363  switch (DirKind) {
1364  default:
1365    break;
1366  case DK_IF:
1367  case DK_IFEQ:
1368  case DK_IFGE:
1369  case DK_IFGT:
1370  case DK_IFLE:
1371  case DK_IFLT:
1372  case DK_IFNE:
1373    return parseDirectiveIf(IDLoc, DirKind);
1374  case DK_IFB:
1375    return parseDirectiveIfb(IDLoc, true);
1376  case DK_IFNB:
1377    return parseDirectiveIfb(IDLoc, false);
1378  case DK_IFC:
1379    return parseDirectiveIfc(IDLoc, true);
1380  case DK_IFEQS:
1381    return parseDirectiveIfeqs(IDLoc, true);
1382  case DK_IFNC:
1383    return parseDirectiveIfc(IDLoc, false);
1384  case DK_IFNES:
1385    return parseDirectiveIfeqs(IDLoc, false);
1386  case DK_IFDEF:
1387    return parseDirectiveIfdef(IDLoc, true);
1388  case DK_IFNDEF:
1389  case DK_IFNOTDEF:
1390    return parseDirectiveIfdef(IDLoc, false);
1391  case DK_ELSEIF:
1392    return parseDirectiveElseIf(IDLoc);
1393  case DK_ELSE:
1394    return parseDirectiveElse(IDLoc);
1395  case DK_ENDIF:
1396    return parseDirectiveEndIf(IDLoc);
1397  }
1398
1399  // Ignore the statement if in the middle of inactive conditional
1400  // (e.g. ".if 0").
1401  if (TheCondState.Ignore) {
1402    eatToEndOfStatement();
1403    return false;
1404  }
1405
1406  // FIXME: Recurse on local labels?
1407
1408  // See what kind of statement we have.
1409  switch (Lexer.getKind()) {
1410  case AsmToken::Colon: {
1411    if (!getTargetParser().isLabel(ID))
1412      break;
1413    checkForValidSection();
1414
1415    // identifier ':'   -> Label.
1416    Lex();
1417
1418    // Diagnose attempt to use '.' as a label.
1419    if (IDVal == ".")
1420      return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1421
1422    // Diagnose attempt to use a variable as a label.
1423    //
1424    // FIXME: Diagnostics. Note the location of the definition as a label.
1425    // FIXME: This doesn't diagnose assignment to a symbol which has been
1426    // implicitly marked as external.
1427    MCSymbol *Sym;
1428    if (LocalLabelVal == -1) {
1429      if (ParsingInlineAsm && SI) {
1430        StringRef RewrittenLabel =
1431            SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1432        assert(RewrittenLabel.size() &&
1433               "We should have an internal name here.");
1434        Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1435                                       RewrittenLabel);
1436        IDVal = RewrittenLabel;
1437      }
1438      Sym = getContext().getOrCreateSymbol(IDVal);
1439    } else
1440      Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1441
1442    Sym->redefineIfPossible();
1443
1444    if (!Sym->isUndefined() || Sym->isVariable())
1445      return Error(IDLoc, "invalid symbol redefinition");
1446
1447    // Emit the label.
1448    if (!ParsingInlineAsm)
1449      Out.EmitLabel(Sym);
1450
1451    // If we are generating dwarf for assembly source files then gather the
1452    // info to make a dwarf label entry for this label if needed.
1453    if (getContext().getGenDwarfForAssembly())
1454      MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1455                                 IDLoc);
1456
1457    getTargetParser().onLabelParsed(Sym);
1458
1459    // Consume any end of statement token, if present, to avoid spurious
1460    // AddBlankLine calls().
1461    if (Lexer.is(AsmToken::EndOfStatement)) {
1462      Lex();
1463      if (Lexer.is(AsmToken::Eof))
1464        return false;
1465    }
1466
1467    return false;
1468  }
1469
1470  case AsmToken::Equal:
1471    if (!getTargetParser().equalIsAsmAssignment())
1472      break;
1473    // identifier '=' ... -> assignment statement
1474    Lex();
1475
1476    return parseAssignment(IDVal, true);
1477
1478  default: // Normal instruction or directive.
1479    break;
1480  }
1481
1482  // If macros are enabled, check to see if this is a macro instantiation.
1483  if (areMacrosEnabled())
1484    if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1485      return handleMacroEntry(M, IDLoc);
1486    }
1487
1488  // Otherwise, we have a normal instruction or directive.
1489
1490  // Directives start with "."
1491  if (IDVal[0] == '.' && IDVal != ".") {
1492    // There are several entities interested in parsing directives:
1493    //
1494    // 1. The target-specific assembly parser. Some directives are target
1495    //    specific or may potentially behave differently on certain targets.
1496    // 2. Asm parser extensions. For example, platform-specific parsers
1497    //    (like the ELF parser) register themselves as extensions.
1498    // 3. The generic directive parser implemented by this class. These are
1499    //    all the directives that behave in a target and platform independent
1500    //    manner, or at least have a default behavior that's shared between
1501    //    all targets and platforms.
1502
1503    // First query the target-specific parser. It will return 'true' if it
1504    // isn't interested in this directive.
1505    if (!getTargetParser().ParseDirective(ID))
1506      return false;
1507
1508    // Next, check the extension directive map to see if any extension has
1509    // registered itself to parse this directive.
1510    std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1511        ExtensionDirectiveMap.lookup(IDVal);
1512    if (Handler.first)
1513      return (*Handler.second)(Handler.first, IDVal, IDLoc);
1514
1515    // Finally, if no one else is interested in this directive, it must be
1516    // generic and familiar to this class.
1517    switch (DirKind) {
1518    default:
1519      break;
1520    case DK_SET:
1521    case DK_EQU:
1522      return parseDirectiveSet(IDVal, true);
1523    case DK_EQUIV:
1524      return parseDirectiveSet(IDVal, false);
1525    case DK_ASCII:
1526      return parseDirectiveAscii(IDVal, false);
1527    case DK_ASCIZ:
1528    case DK_STRING:
1529      return parseDirectiveAscii(IDVal, true);
1530    case DK_BYTE:
1531      return parseDirectiveValue(1);
1532    case DK_SHORT:
1533    case DK_VALUE:
1534    case DK_2BYTE:
1535      return parseDirectiveValue(2);
1536    case DK_LONG:
1537    case DK_INT:
1538    case DK_4BYTE:
1539      return parseDirectiveValue(4);
1540    case DK_QUAD:
1541    case DK_8BYTE:
1542      return parseDirectiveValue(8);
1543    case DK_OCTA:
1544      return parseDirectiveOctaValue();
1545    case DK_SINGLE:
1546    case DK_FLOAT:
1547      return parseDirectiveRealValue(APFloat::IEEEsingle);
1548    case DK_DOUBLE:
1549      return parseDirectiveRealValue(APFloat::IEEEdouble);
1550    case DK_ALIGN: {
1551      bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1552      return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1553    }
1554    case DK_ALIGN32: {
1555      bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1556      return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1557    }
1558    case DK_BALIGN:
1559      return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1560    case DK_BALIGNW:
1561      return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1562    case DK_BALIGNL:
1563      return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1564    case DK_P2ALIGN:
1565      return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1566    case DK_P2ALIGNW:
1567      return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1568    case DK_P2ALIGNL:
1569      return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1570    case DK_ORG:
1571      return parseDirectiveOrg();
1572    case DK_FILL:
1573      return parseDirectiveFill();
1574    case DK_ZERO:
1575      return parseDirectiveZero();
1576    case DK_EXTERN:
1577      eatToEndOfStatement(); // .extern is the default, ignore it.
1578      return false;
1579    case DK_GLOBL:
1580    case DK_GLOBAL:
1581      return parseDirectiveSymbolAttribute(MCSA_Global);
1582    case DK_LAZY_REFERENCE:
1583      return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1584    case DK_NO_DEAD_STRIP:
1585      return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1586    case DK_SYMBOL_RESOLVER:
1587      return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1588    case DK_PRIVATE_EXTERN:
1589      return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1590    case DK_REFERENCE:
1591      return parseDirectiveSymbolAttribute(MCSA_Reference);
1592    case DK_WEAK_DEFINITION:
1593      return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1594    case DK_WEAK_REFERENCE:
1595      return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1596    case DK_WEAK_DEF_CAN_BE_HIDDEN:
1597      return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1598    case DK_COMM:
1599    case DK_COMMON:
1600      return parseDirectiveComm(/*IsLocal=*/false);
1601    case DK_LCOMM:
1602      return parseDirectiveComm(/*IsLocal=*/true);
1603    case DK_ABORT:
1604      return parseDirectiveAbort();
1605    case DK_INCLUDE:
1606      return parseDirectiveInclude();
1607    case DK_INCBIN:
1608      return parseDirectiveIncbin();
1609    case DK_CODE16:
1610    case DK_CODE16GCC:
1611      return TokError(Twine(IDVal) + " not supported yet");
1612    case DK_REPT:
1613      return parseDirectiveRept(IDLoc, IDVal);
1614    case DK_IRP:
1615      return parseDirectiveIrp(IDLoc);
1616    case DK_IRPC:
1617      return parseDirectiveIrpc(IDLoc);
1618    case DK_ENDR:
1619      return parseDirectiveEndr(IDLoc);
1620    case DK_BUNDLE_ALIGN_MODE:
1621      return parseDirectiveBundleAlignMode();
1622    case DK_BUNDLE_LOCK:
1623      return parseDirectiveBundleLock();
1624    case DK_BUNDLE_UNLOCK:
1625      return parseDirectiveBundleUnlock();
1626    case DK_SLEB128:
1627      return parseDirectiveLEB128(true);
1628    case DK_ULEB128:
1629      return parseDirectiveLEB128(false);
1630    case DK_SPACE:
1631    case DK_SKIP:
1632      return parseDirectiveSpace(IDVal);
1633    case DK_FILE:
1634      return parseDirectiveFile(IDLoc);
1635    case DK_LINE:
1636      return parseDirectiveLine();
1637    case DK_LOC:
1638      return parseDirectiveLoc();
1639    case DK_STABS:
1640      return parseDirectiveStabs();
1641    case DK_CFI_SECTIONS:
1642      return parseDirectiveCFISections();
1643    case DK_CFI_STARTPROC:
1644      return parseDirectiveCFIStartProc();
1645    case DK_CFI_ENDPROC:
1646      return parseDirectiveCFIEndProc();
1647    case DK_CFI_DEF_CFA:
1648      return parseDirectiveCFIDefCfa(IDLoc);
1649    case DK_CFI_DEF_CFA_OFFSET:
1650      return parseDirectiveCFIDefCfaOffset();
1651    case DK_CFI_ADJUST_CFA_OFFSET:
1652      return parseDirectiveCFIAdjustCfaOffset();
1653    case DK_CFI_DEF_CFA_REGISTER:
1654      return parseDirectiveCFIDefCfaRegister(IDLoc);
1655    case DK_CFI_OFFSET:
1656      return parseDirectiveCFIOffset(IDLoc);
1657    case DK_CFI_REL_OFFSET:
1658      return parseDirectiveCFIRelOffset(IDLoc);
1659    case DK_CFI_PERSONALITY:
1660      return parseDirectiveCFIPersonalityOrLsda(true);
1661    case DK_CFI_LSDA:
1662      return parseDirectiveCFIPersonalityOrLsda(false);
1663    case DK_CFI_REMEMBER_STATE:
1664      return parseDirectiveCFIRememberState();
1665    case DK_CFI_RESTORE_STATE:
1666      return parseDirectiveCFIRestoreState();
1667    case DK_CFI_SAME_VALUE:
1668      return parseDirectiveCFISameValue(IDLoc);
1669    case DK_CFI_RESTORE:
1670      return parseDirectiveCFIRestore(IDLoc);
1671    case DK_CFI_ESCAPE:
1672      return parseDirectiveCFIEscape();
1673    case DK_CFI_SIGNAL_FRAME:
1674      return parseDirectiveCFISignalFrame();
1675    case DK_CFI_UNDEFINED:
1676      return parseDirectiveCFIUndefined(IDLoc);
1677    case DK_CFI_REGISTER:
1678      return parseDirectiveCFIRegister(IDLoc);
1679    case DK_CFI_WINDOW_SAVE:
1680      return parseDirectiveCFIWindowSave();
1681    case DK_MACROS_ON:
1682    case DK_MACROS_OFF:
1683      return parseDirectiveMacrosOnOff(IDVal);
1684    case DK_MACRO:
1685      return parseDirectiveMacro(IDLoc);
1686    case DK_EXITM:
1687      return parseDirectiveExitMacro(IDVal);
1688    case DK_ENDM:
1689    case DK_ENDMACRO:
1690      return parseDirectiveEndMacro(IDVal);
1691    case DK_PURGEM:
1692      return parseDirectivePurgeMacro(IDLoc);
1693    case DK_END:
1694      return parseDirectiveEnd(IDLoc);
1695    case DK_ERR:
1696      return parseDirectiveError(IDLoc, false);
1697    case DK_ERROR:
1698      return parseDirectiveError(IDLoc, true);
1699    case DK_WARNING:
1700      return parseDirectiveWarning(IDLoc);
1701    case DK_RELOC:
1702      return parseDirectiveReloc(IDLoc);
1703    }
1704
1705    return Error(IDLoc, "unknown directive");
1706  }
1707
1708  // __asm _emit or __asm __emit
1709  if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1710                           IDVal == "_EMIT" || IDVal == "__EMIT"))
1711    return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1712
1713  // __asm align
1714  if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1715    return parseDirectiveMSAlign(IDLoc, Info);
1716
1717  if (ParsingInlineAsm && (IDVal == "even"))
1718    Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
1719  checkForValidSection();
1720
1721  // Canonicalize the opcode to lower case.
1722  std::string OpcodeStr = IDVal.lower();
1723  ParseInstructionInfo IInfo(Info.AsmRewrites);
1724  bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
1725                                                     Info.ParsedOperands);
1726  Info.ParseError = HadError;
1727
1728  // Dump the parsed representation, if requested.
1729  if (getShowParsedOperands()) {
1730    SmallString<256> Str;
1731    raw_svector_ostream OS(Str);
1732    OS << "parsed instruction: [";
1733    for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1734      if (i != 0)
1735        OS << ", ";
1736      Info.ParsedOperands[i]->print(OS);
1737    }
1738    OS << "]";
1739
1740    printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1741  }
1742
1743  // If we are generating dwarf for the current section then generate a .loc
1744  // directive for the instruction.
1745  if (!HadError && getContext().getGenDwarfForAssembly() &&
1746      getContext().getGenDwarfSectionSyms().count(
1747          getStreamer().getCurrentSection().first)) {
1748    unsigned Line;
1749    if (ActiveMacros.empty())
1750      Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1751    else
1752      Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
1753                                   ActiveMacros.front()->ExitBuffer);
1754
1755    // If we previously parsed a cpp hash file line comment then make sure the
1756    // current Dwarf File is for the CppHashFilename if not then emit the
1757    // Dwarf File table for it and adjust the line number for the .loc.
1758    if (CppHashFilename.size()) {
1759      unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1760          0, StringRef(), CppHashFilename);
1761      getContext().setGenDwarfFileNumber(FileNumber);
1762
1763      // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1764      // cache with the different Loc from the call above we save the last
1765      // info we queried here with SrcMgr.FindLineNumber().
1766      unsigned CppHashLocLineNo;
1767      if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1768        CppHashLocLineNo = LastQueryLine;
1769      else {
1770        CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1771        LastQueryLine = CppHashLocLineNo;
1772        LastQueryIDLoc = CppHashLoc;
1773        LastQueryBuffer = CppHashBuf;
1774      }
1775      Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1776    }
1777
1778    getStreamer().EmitDwarfLocDirective(
1779        getContext().getGenDwarfFileNumber(), Line, 0,
1780        DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1781        StringRef());
1782  }
1783
1784  // If parsing succeeded, match the instruction.
1785  if (!HadError) {
1786    uint64_t ErrorInfo;
1787    getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1788                                              Info.ParsedOperands, Out,
1789                                              ErrorInfo, ParsingInlineAsm);
1790  }
1791
1792  // Don't skip the rest of the line, the instruction parser is responsible for
1793  // that.
1794  return false;
1795}
1796
1797/// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1798/// since they may not be able to be tokenized to get to the end of line token.
1799void AsmParser::eatToEndOfLine() {
1800  if (!Lexer.is(AsmToken::EndOfStatement))
1801    Lexer.LexUntilEndOfLine();
1802  // Eat EOL.
1803  Lex();
1804}
1805
1806/// parseCppHashLineFilenameComment as this:
1807///   ::= # number "filename"
1808/// or just as a full line comment if it doesn't have a number and a string.
1809bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
1810  Lex(); // Eat the hash token.
1811
1812  if (getLexer().isNot(AsmToken::Integer)) {
1813    // Consume the line since in cases it is not a well-formed line directive,
1814    // as if were simply a full line comment.
1815    eatToEndOfLine();
1816    return false;
1817  }
1818
1819  int64_t LineNumber = getTok().getIntVal();
1820  Lex();
1821
1822  if (getLexer().isNot(AsmToken::String)) {
1823    eatToEndOfLine();
1824    return false;
1825  }
1826
1827  StringRef Filename = getTok().getString();
1828  // Get rid of the enclosing quotes.
1829  Filename = Filename.substr(1, Filename.size() - 2);
1830
1831  // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1832  CppHashLoc = L;
1833  CppHashFilename = Filename;
1834  CppHashLineNumber = LineNumber;
1835  CppHashBuf = CurBuffer;
1836
1837  // Ignore any trailing characters, they're just comment.
1838  eatToEndOfLine();
1839  return false;
1840}
1841
1842/// \brief will use the last parsed cpp hash line filename comment
1843/// for the Filename and LineNo if any in the diagnostic.
1844void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1845  const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1846  raw_ostream &OS = errs();
1847
1848  const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1849  SMLoc DiagLoc = Diag.getLoc();
1850  unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1851  unsigned CppHashBuf =
1852      Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1853
1854  // Like SourceMgr::printMessage() we need to print the include stack if any
1855  // before printing the message.
1856  unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1857  if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1858      DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
1859    SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1860    DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1861  }
1862
1863  // If we have not parsed a cpp hash line filename comment or the source
1864  // manager changed or buffer changed (like in a nested include) then just
1865  // print the normal diagnostic using its Filename and LineNo.
1866  if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1867      DiagBuf != CppHashBuf) {
1868    if (Parser->SavedDiagHandler)
1869      Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1870    else
1871      Diag.print(nullptr, OS);
1872    return;
1873  }
1874
1875  // Use the CppHashFilename and calculate a line number based on the
1876  // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1877  // the diagnostic.
1878  const std::string &Filename = Parser->CppHashFilename;
1879
1880  int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1881  int CppHashLocLineNo =
1882      Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1883  int LineNo =
1884      Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1885
1886  SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1887                       Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1888                       Diag.getLineContents(), Diag.getRanges());
1889
1890  if (Parser->SavedDiagHandler)
1891    Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1892  else
1893    NewDiag.print(nullptr, OS);
1894}
1895
1896// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1897// difference being that that function accepts '@' as part of identifiers and
1898// we can't do that. AsmLexer.cpp should probably be changed to handle
1899// '@' as a special case when needed.
1900static bool isIdentifierChar(char c) {
1901  return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1902         c == '.';
1903}
1904
1905bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1906                            ArrayRef<MCAsmMacroParameter> Parameters,
1907                            ArrayRef<MCAsmMacroArgument> A,
1908                            bool EnableAtPseudoVariable, SMLoc L) {
1909  unsigned NParameters = Parameters.size();
1910  bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1911  if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1912    return Error(L, "Wrong number of arguments");
1913
1914  // A macro without parameters is handled differently on Darwin:
1915  // gas accepts no arguments and does no substitutions
1916  while (!Body.empty()) {
1917    // Scan for the next substitution.
1918    std::size_t End = Body.size(), Pos = 0;
1919    for (; Pos != End; ++Pos) {
1920      // Check for a substitution or escape.
1921      if (IsDarwin && !NParameters) {
1922        // This macro has no parameters, look for $0, $1, etc.
1923        if (Body[Pos] != '$' || Pos + 1 == End)
1924          continue;
1925
1926        char Next = Body[Pos + 1];
1927        if (Next == '$' || Next == 'n' ||
1928            isdigit(static_cast<unsigned char>(Next)))
1929          break;
1930      } else {
1931        // This macro has parameters, look for \foo, \bar, etc.
1932        if (Body[Pos] == '\\' && Pos + 1 != End)
1933          break;
1934      }
1935    }
1936
1937    // Add the prefix.
1938    OS << Body.slice(0, Pos);
1939
1940    // Check if we reached the end.
1941    if (Pos == End)
1942      break;
1943
1944    if (IsDarwin && !NParameters) {
1945      switch (Body[Pos + 1]) {
1946      // $$ => $
1947      case '$':
1948        OS << '$';
1949        break;
1950
1951      // $n => number of arguments
1952      case 'n':
1953        OS << A.size();
1954        break;
1955
1956      // $[0-9] => argument
1957      default: {
1958        // Missing arguments are ignored.
1959        unsigned Index = Body[Pos + 1] - '0';
1960        if (Index >= A.size())
1961          break;
1962
1963        // Otherwise substitute with the token values, with spaces eliminated.
1964        for (const AsmToken &Token : A[Index])
1965          OS << Token.getString();
1966        break;
1967      }
1968      }
1969      Pos += 2;
1970    } else {
1971      unsigned I = Pos + 1;
1972
1973      // Check for the \@ pseudo-variable.
1974      if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
1975        ++I;
1976      else
1977        while (isIdentifierChar(Body[I]) && I + 1 != End)
1978          ++I;
1979
1980      const char *Begin = Body.data() + Pos + 1;
1981      StringRef Argument(Begin, I - (Pos + 1));
1982      unsigned Index = 0;
1983
1984      if (Argument == "@") {
1985        OS << NumOfMacroInstantiations;
1986        Pos += 2;
1987      } else {
1988        for (; Index < NParameters; ++Index)
1989          if (Parameters[Index].Name == Argument)
1990            break;
1991
1992        if (Index == NParameters) {
1993          if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1994            Pos += 3;
1995          else {
1996            OS << '\\' << Argument;
1997            Pos = I;
1998          }
1999        } else {
2000          bool VarargParameter = HasVararg && Index == (NParameters - 1);
2001          for (const AsmToken &Token : A[Index])
2002            // We expect no quotes around the string's contents when
2003            // parsing for varargs.
2004            if (Token.getKind() != AsmToken::String || VarargParameter)
2005              OS << Token.getString();
2006            else
2007              OS << Token.getStringContents();
2008
2009          Pos += 1 + Argument.size();
2010        }
2011      }
2012    }
2013    // Update the scan point.
2014    Body = Body.substr(Pos);
2015  }
2016
2017  return false;
2018}
2019
2020MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
2021                                       size_t CondStackDepth)
2022    : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
2023      CondStackDepth(CondStackDepth) {}
2024
2025static bool isOperator(AsmToken::TokenKind kind) {
2026  switch (kind) {
2027  default:
2028    return false;
2029  case AsmToken::Plus:
2030  case AsmToken::Minus:
2031  case AsmToken::Tilde:
2032  case AsmToken::Slash:
2033  case AsmToken::Star:
2034  case AsmToken::Dot:
2035  case AsmToken::Equal:
2036  case AsmToken::EqualEqual:
2037  case AsmToken::Pipe:
2038  case AsmToken::PipePipe:
2039  case AsmToken::Caret:
2040  case AsmToken::Amp:
2041  case AsmToken::AmpAmp:
2042  case AsmToken::Exclaim:
2043  case AsmToken::ExclaimEqual:
2044  case AsmToken::Percent:
2045  case AsmToken::Less:
2046  case AsmToken::LessEqual:
2047  case AsmToken::LessLess:
2048  case AsmToken::LessGreater:
2049  case AsmToken::Greater:
2050  case AsmToken::GreaterEqual:
2051  case AsmToken::GreaterGreater:
2052    return true;
2053  }
2054}
2055
2056namespace {
2057class AsmLexerSkipSpaceRAII {
2058public:
2059  AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2060    Lexer.setSkipSpace(SkipSpace);
2061  }
2062
2063  ~AsmLexerSkipSpaceRAII() {
2064    Lexer.setSkipSpace(true);
2065  }
2066
2067private:
2068  AsmLexer &Lexer;
2069};
2070}
2071
2072bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2073
2074  if (Vararg) {
2075    if (Lexer.isNot(AsmToken::EndOfStatement)) {
2076      StringRef Str = parseStringToEndOfStatement();
2077      MA.emplace_back(AsmToken::String, Str);
2078    }
2079    return false;
2080  }
2081
2082  unsigned ParenLevel = 0;
2083  unsigned AddTokens = 0;
2084
2085  // Darwin doesn't use spaces to delmit arguments.
2086  AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
2087
2088  for (;;) {
2089    if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
2090      return TokError("unexpected token in macro instantiation");
2091
2092    if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
2093      break;
2094
2095    if (Lexer.is(AsmToken::Space)) {
2096      Lex(); // Eat spaces
2097
2098      // Spaces can delimit parameters, but could also be part an expression.
2099      // If the token after a space is an operator, add the token and the next
2100      // one into this argument
2101      if (!IsDarwin) {
2102        if (isOperator(Lexer.getKind())) {
2103          // Check to see whether the token is used as an operator,
2104          // or part of an identifier
2105          const char *NextChar = getTok().getEndLoc().getPointer();
2106          if (*NextChar == ' ')
2107            AddTokens = 2;
2108        }
2109
2110        if (!AddTokens && ParenLevel == 0) {
2111          break;
2112        }
2113      }
2114    }
2115
2116    // handleMacroEntry relies on not advancing the lexer here
2117    // to be able to fill in the remaining default parameter values
2118    if (Lexer.is(AsmToken::EndOfStatement))
2119      break;
2120
2121    // Adjust the current parentheses level.
2122    if (Lexer.is(AsmToken::LParen))
2123      ++ParenLevel;
2124    else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2125      --ParenLevel;
2126
2127    // Append the token to the current argument list.
2128    MA.push_back(getTok());
2129    if (AddTokens)
2130      AddTokens--;
2131    Lex();
2132  }
2133
2134  if (ParenLevel != 0)
2135    return TokError("unbalanced parentheses in macro argument");
2136  return false;
2137}
2138
2139// Parse the macro instantiation arguments.
2140bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2141                                    MCAsmMacroArguments &A) {
2142  const unsigned NParameters = M ? M->Parameters.size() : 0;
2143  bool NamedParametersFound = false;
2144  SmallVector<SMLoc, 4> FALocs;
2145
2146  A.resize(NParameters);
2147  FALocs.resize(NParameters);
2148
2149  // Parse two kinds of macro invocations:
2150  // - macros defined without any parameters accept an arbitrary number of them
2151  // - macros defined with parameters accept at most that many of them
2152  bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2153  for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2154       ++Parameter) {
2155    SMLoc IDLoc = Lexer.getLoc();
2156    MCAsmMacroParameter FA;
2157
2158    if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2159      if (parseIdentifier(FA.Name)) {
2160        Error(IDLoc, "invalid argument identifier for formal argument");
2161        eatToEndOfStatement();
2162        return true;
2163      }
2164
2165      if (!Lexer.is(AsmToken::Equal)) {
2166        TokError("expected '=' after formal parameter identifier");
2167        eatToEndOfStatement();
2168        return true;
2169      }
2170      Lex();
2171
2172      NamedParametersFound = true;
2173    }
2174
2175    if (NamedParametersFound && FA.Name.empty()) {
2176      Error(IDLoc, "cannot mix positional and keyword arguments");
2177      eatToEndOfStatement();
2178      return true;
2179    }
2180
2181    bool Vararg = HasVararg && Parameter == (NParameters - 1);
2182    if (parseMacroArgument(FA.Value, Vararg))
2183      return true;
2184
2185    unsigned PI = Parameter;
2186    if (!FA.Name.empty()) {
2187      unsigned FAI = 0;
2188      for (FAI = 0; FAI < NParameters; ++FAI)
2189        if (M->Parameters[FAI].Name == FA.Name)
2190          break;
2191
2192      if (FAI >= NParameters) {
2193    assert(M && "expected macro to be defined");
2194        Error(IDLoc,
2195              "parameter named '" + FA.Name + "' does not exist for macro '" +
2196              M->Name + "'");
2197        return true;
2198      }
2199      PI = FAI;
2200    }
2201
2202    if (!FA.Value.empty()) {
2203      if (A.size() <= PI)
2204        A.resize(PI + 1);
2205      A[PI] = FA.Value;
2206
2207      if (FALocs.size() <= PI)
2208        FALocs.resize(PI + 1);
2209
2210      FALocs[PI] = Lexer.getLoc();
2211    }
2212
2213    // At the end of the statement, fill in remaining arguments that have
2214    // default values. If there aren't any, then the next argument is
2215    // required but missing
2216    if (Lexer.is(AsmToken::EndOfStatement)) {
2217      bool Failure = false;
2218      for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2219        if (A[FAI].empty()) {
2220          if (M->Parameters[FAI].Required) {
2221            Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2222                  "missing value for required parameter "
2223                  "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2224            Failure = true;
2225          }
2226
2227          if (!M->Parameters[FAI].Value.empty())
2228            A[FAI] = M->Parameters[FAI].Value;
2229        }
2230      }
2231      return Failure;
2232    }
2233
2234    if (Lexer.is(AsmToken::Comma))
2235      Lex();
2236  }
2237
2238  return TokError("too many positional arguments");
2239}
2240
2241const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2242  StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2243  return (I == MacroMap.end()) ? nullptr : &I->getValue();
2244}
2245
2246void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2247  MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2248}
2249
2250void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2251
2252bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2253  // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2254  // this, although we should protect against infinite loops.
2255  if (ActiveMacros.size() == 20)
2256    return TokError("macros cannot be nested more than 20 levels deep");
2257
2258  MCAsmMacroArguments A;
2259  if (parseMacroArguments(M, A))
2260    return true;
2261
2262  // Macro instantiation is lexical, unfortunately. We construct a new buffer
2263  // to hold the macro body with substitutions.
2264  SmallString<256> Buf;
2265  StringRef Body = M->Body;
2266  raw_svector_ostream OS(Buf);
2267
2268  if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2269    return true;
2270
2271  // We include the .endmacro in the buffer as our cue to exit the macro
2272  // instantiation.
2273  OS << ".endmacro\n";
2274
2275  std::unique_ptr<MemoryBuffer> Instantiation =
2276      MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2277
2278  // Create the macro instantiation object and add to the current macro
2279  // instantiation stack.
2280  MacroInstantiation *MI = new MacroInstantiation(
2281      NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2282  ActiveMacros.push_back(MI);
2283
2284  ++NumOfMacroInstantiations;
2285
2286  // Jump to the macro instantiation and prime the lexer.
2287  CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2288  Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2289  Lex();
2290
2291  return false;
2292}
2293
2294void AsmParser::handleMacroExit() {
2295  // Jump to the EndOfStatement we should return to, and consume it.
2296  jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2297  Lex();
2298
2299  // Pop the instantiation entry.
2300  delete ActiveMacros.back();
2301  ActiveMacros.pop_back();
2302}
2303
2304bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2305                                bool NoDeadStrip) {
2306  MCSymbol *Sym;
2307  const MCExpr *Value;
2308  if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2309                                               Value))
2310    return true;
2311
2312  if (!Sym) {
2313    // In the case where we parse an expression starting with a '.', we will
2314    // not generate an error, nor will we create a symbol.  In this case we
2315    // should just return out.
2316    return false;
2317  }
2318
2319  // Do the assignment.
2320  Out.EmitAssignment(Sym, Value);
2321  if (NoDeadStrip)
2322    Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2323
2324  return false;
2325}
2326
2327/// parseIdentifier:
2328///   ::= identifier
2329///   ::= string
2330bool AsmParser::parseIdentifier(StringRef &Res) {
2331  // The assembler has relaxed rules for accepting identifiers, in particular we
2332  // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2333  // separate tokens. At this level, we have already lexed so we cannot (currently)
2334  // handle this as a context dependent token, instead we detect adjacent tokens
2335  // and return the combined identifier.
2336  if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2337    SMLoc PrefixLoc = getLexer().getLoc();
2338
2339    // Consume the prefix character, and check for a following identifier.
2340    Lex();
2341    if (Lexer.isNot(AsmToken::Identifier))
2342      return true;
2343
2344    // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2345    if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2346      return true;
2347
2348    // Construct the joined identifier and consume the token.
2349    Res =
2350        StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2351    Lex();
2352    return false;
2353  }
2354
2355  if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2356    return true;
2357
2358  Res = getTok().getIdentifier();
2359
2360  Lex(); // Consume the identifier token.
2361
2362  return false;
2363}
2364
2365/// parseDirectiveSet:
2366///   ::= .equ identifier ',' expression
2367///   ::= .equiv identifier ',' expression
2368///   ::= .set identifier ',' expression
2369bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2370  StringRef Name;
2371
2372  if (parseIdentifier(Name))
2373    return TokError("expected identifier after '" + Twine(IDVal) + "'");
2374
2375  if (getLexer().isNot(AsmToken::Comma))
2376    return TokError("unexpected token in '" + Twine(IDVal) + "'");
2377  Lex();
2378
2379  return parseAssignment(Name, allow_redef, true);
2380}
2381
2382bool AsmParser::parseEscapedString(std::string &Data) {
2383  assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2384
2385  Data = "";
2386  StringRef Str = getTok().getStringContents();
2387  for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2388    if (Str[i] != '\\') {
2389      Data += Str[i];
2390      continue;
2391    }
2392
2393    // Recognize escaped characters. Note that this escape semantics currently
2394    // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2395    ++i;
2396    if (i == e)
2397      return TokError("unexpected backslash at end of string");
2398
2399    // Recognize octal sequences.
2400    if ((unsigned)(Str[i] - '0') <= 7) {
2401      // Consume up to three octal characters.
2402      unsigned Value = Str[i] - '0';
2403
2404      if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2405        ++i;
2406        Value = Value * 8 + (Str[i] - '0');
2407
2408        if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2409          ++i;
2410          Value = Value * 8 + (Str[i] - '0');
2411        }
2412      }
2413
2414      if (Value > 255)
2415        return TokError("invalid octal escape sequence (out of range)");
2416
2417      Data += (unsigned char)Value;
2418      continue;
2419    }
2420
2421    // Otherwise recognize individual escapes.
2422    switch (Str[i]) {
2423    default:
2424      // Just reject invalid escape sequences for now.
2425      return TokError("invalid escape sequence (unrecognized character)");
2426
2427    case 'b': Data += '\b'; break;
2428    case 'f': Data += '\f'; break;
2429    case 'n': Data += '\n'; break;
2430    case 'r': Data += '\r'; break;
2431    case 't': Data += '\t'; break;
2432    case '"': Data += '"'; break;
2433    case '\\': Data += '\\'; break;
2434    }
2435  }
2436
2437  return false;
2438}
2439
2440/// parseDirectiveAscii:
2441///   ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2442bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2443  if (getLexer().isNot(AsmToken::EndOfStatement)) {
2444    checkForValidSection();
2445
2446    for (;;) {
2447      if (getLexer().isNot(AsmToken::String))
2448        return TokError("expected string in '" + Twine(IDVal) + "' directive");
2449
2450      std::string Data;
2451      if (parseEscapedString(Data))
2452        return true;
2453
2454      getStreamer().EmitBytes(Data);
2455      if (ZeroTerminated)
2456        getStreamer().EmitBytes(StringRef("\0", 1));
2457
2458      Lex();
2459
2460      if (getLexer().is(AsmToken::EndOfStatement))
2461        break;
2462
2463      if (getLexer().isNot(AsmToken::Comma))
2464        return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2465      Lex();
2466    }
2467  }
2468
2469  Lex();
2470  return false;
2471}
2472
2473/// parseDirectiveReloc
2474///  ::= .reloc expression , identifier [ , expression ]
2475bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2476  const MCExpr *Offset;
2477  const MCExpr *Expr = nullptr;
2478
2479  SMLoc OffsetLoc = Lexer.getTok().getLoc();
2480  if (parseExpression(Offset))
2481    return true;
2482
2483  // We can only deal with constant expressions at the moment.
2484  int64_t OffsetValue;
2485  if (!Offset->evaluateAsAbsolute(OffsetValue))
2486    return Error(OffsetLoc, "expression is not a constant value");
2487
2488  if (Lexer.isNot(AsmToken::Comma))
2489    return TokError("expected comma");
2490  Lexer.Lex();
2491
2492  if (Lexer.isNot(AsmToken::Identifier))
2493    return TokError("expected relocation name");
2494  SMLoc NameLoc = Lexer.getTok().getLoc();
2495  StringRef Name = Lexer.getTok().getIdentifier();
2496  Lexer.Lex();
2497
2498  if (Lexer.is(AsmToken::Comma)) {
2499    Lexer.Lex();
2500    SMLoc ExprLoc = Lexer.getLoc();
2501    if (parseExpression(Expr))
2502      return true;
2503
2504    MCValue Value;
2505    if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2506      return Error(ExprLoc, "expression must be relocatable");
2507  }
2508
2509  if (Lexer.isNot(AsmToken::EndOfStatement))
2510    return TokError("unexpected token in .reloc directive");
2511
2512  if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2513    return Error(NameLoc, "unknown relocation name");
2514
2515  return false;
2516}
2517
2518/// parseDirectiveValue
2519///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
2520bool AsmParser::parseDirectiveValue(unsigned Size) {
2521  if (getLexer().isNot(AsmToken::EndOfStatement)) {
2522    checkForValidSection();
2523
2524    for (;;) {
2525      const MCExpr *Value;
2526      SMLoc ExprLoc = getLexer().getLoc();
2527      if (parseExpression(Value))
2528        return true;
2529
2530      // Special case constant expressions to match code generator.
2531      if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2532        assert(Size <= 8 && "Invalid size");
2533        uint64_t IntValue = MCE->getValue();
2534        if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2535          return Error(ExprLoc, "literal value out of range for directive");
2536        getStreamer().EmitIntValue(IntValue, Size);
2537      } else
2538        getStreamer().EmitValue(Value, Size, ExprLoc);
2539
2540      if (getLexer().is(AsmToken::EndOfStatement))
2541        break;
2542
2543      // FIXME: Improve diagnostic.
2544      if (getLexer().isNot(AsmToken::Comma))
2545        return TokError("unexpected token in directive");
2546      Lex();
2547    }
2548  }
2549
2550  Lex();
2551  return false;
2552}
2553
2554/// ParseDirectiveOctaValue
2555///  ::= .octa [ hexconstant (, hexconstant)* ]
2556bool AsmParser::parseDirectiveOctaValue() {
2557  if (getLexer().isNot(AsmToken::EndOfStatement)) {
2558    checkForValidSection();
2559
2560    for (;;) {
2561      if (Lexer.getKind() == AsmToken::Error)
2562        return true;
2563      if (Lexer.getKind() != AsmToken::Integer &&
2564          Lexer.getKind() != AsmToken::BigNum)
2565        return TokError("unknown token in expression");
2566
2567      SMLoc ExprLoc = getLexer().getLoc();
2568      APInt IntValue = getTok().getAPIntVal();
2569      Lex();
2570
2571      uint64_t hi, lo;
2572      if (IntValue.isIntN(64)) {
2573        hi = 0;
2574        lo = IntValue.getZExtValue();
2575      } else if (IntValue.isIntN(128)) {
2576        // It might actually have more than 128 bits, but the top ones are zero.
2577        hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2578        lo = IntValue.getLoBits(64).getZExtValue();
2579      } else
2580        return Error(ExprLoc, "literal value out of range for directive");
2581
2582      if (MAI.isLittleEndian()) {
2583        getStreamer().EmitIntValue(lo, 8);
2584        getStreamer().EmitIntValue(hi, 8);
2585      } else {
2586        getStreamer().EmitIntValue(hi, 8);
2587        getStreamer().EmitIntValue(lo, 8);
2588      }
2589
2590      if (getLexer().is(AsmToken::EndOfStatement))
2591        break;
2592
2593      // FIXME: Improve diagnostic.
2594      if (getLexer().isNot(AsmToken::Comma))
2595        return TokError("unexpected token in directive");
2596      Lex();
2597    }
2598  }
2599
2600  Lex();
2601  return false;
2602}
2603
2604/// parseDirectiveRealValue
2605///  ::= (.single | .double) [ expression (, expression)* ]
2606bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2607  if (getLexer().isNot(AsmToken::EndOfStatement)) {
2608    checkForValidSection();
2609
2610    for (;;) {
2611      // We don't truly support arithmetic on floating point expressions, so we
2612      // have to manually parse unary prefixes.
2613      bool IsNeg = false;
2614      if (getLexer().is(AsmToken::Minus)) {
2615        Lex();
2616        IsNeg = true;
2617      } else if (getLexer().is(AsmToken::Plus))
2618        Lex();
2619
2620      if (getLexer().isNot(AsmToken::Integer) &&
2621          getLexer().isNot(AsmToken::Real) &&
2622          getLexer().isNot(AsmToken::Identifier))
2623        return TokError("unexpected token in directive");
2624
2625      // Convert to an APFloat.
2626      APFloat Value(Semantics);
2627      StringRef IDVal = getTok().getString();
2628      if (getLexer().is(AsmToken::Identifier)) {
2629        if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2630          Value = APFloat::getInf(Semantics);
2631        else if (!IDVal.compare_lower("nan"))
2632          Value = APFloat::getNaN(Semantics, false, ~0);
2633        else
2634          return TokError("invalid floating point literal");
2635      } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2636                 APFloat::opInvalidOp)
2637        return TokError("invalid floating point literal");
2638      if (IsNeg)
2639        Value.changeSign();
2640
2641      // Consume the numeric token.
2642      Lex();
2643
2644      // Emit the value as an integer.
2645      APInt AsInt = Value.bitcastToAPInt();
2646      getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2647                                 AsInt.getBitWidth() / 8);
2648
2649      if (getLexer().is(AsmToken::EndOfStatement))
2650        break;
2651
2652      if (getLexer().isNot(AsmToken::Comma))
2653        return TokError("unexpected token in directive");
2654      Lex();
2655    }
2656  }
2657
2658  Lex();
2659  return false;
2660}
2661
2662/// parseDirectiveZero
2663///  ::= .zero expression
2664bool AsmParser::parseDirectiveZero() {
2665  checkForValidSection();
2666
2667  int64_t NumBytes;
2668  if (parseAbsoluteExpression(NumBytes))
2669    return true;
2670
2671  int64_t Val = 0;
2672  if (getLexer().is(AsmToken::Comma)) {
2673    Lex();
2674    if (parseAbsoluteExpression(Val))
2675      return true;
2676  }
2677
2678  if (getLexer().isNot(AsmToken::EndOfStatement))
2679    return TokError("unexpected token in '.zero' directive");
2680
2681  Lex();
2682
2683  getStreamer().EmitFill(NumBytes, Val);
2684
2685  return false;
2686}
2687
2688/// parseDirectiveFill
2689///  ::= .fill expression [ , expression [ , expression ] ]
2690bool AsmParser::parseDirectiveFill() {
2691  checkForValidSection();
2692
2693  SMLoc RepeatLoc = getLexer().getLoc();
2694  int64_t NumValues;
2695  if (parseAbsoluteExpression(NumValues))
2696    return true;
2697
2698  if (NumValues < 0) {
2699    Warning(RepeatLoc,
2700            "'.fill' directive with negative repeat count has no effect");
2701    NumValues = 0;
2702  }
2703
2704  int64_t FillSize = 1;
2705  int64_t FillExpr = 0;
2706
2707  SMLoc SizeLoc, ExprLoc;
2708  if (getLexer().isNot(AsmToken::EndOfStatement)) {
2709    if (getLexer().isNot(AsmToken::Comma))
2710      return TokError("unexpected token in '.fill' directive");
2711    Lex();
2712
2713    SizeLoc = getLexer().getLoc();
2714    if (parseAbsoluteExpression(FillSize))
2715      return true;
2716
2717    if (getLexer().isNot(AsmToken::EndOfStatement)) {
2718      if (getLexer().isNot(AsmToken::Comma))
2719        return TokError("unexpected token in '.fill' directive");
2720      Lex();
2721
2722      ExprLoc = getLexer().getLoc();
2723      if (parseAbsoluteExpression(FillExpr))
2724        return true;
2725
2726      if (getLexer().isNot(AsmToken::EndOfStatement))
2727        return TokError("unexpected token in '.fill' directive");
2728
2729      Lex();
2730    }
2731  }
2732
2733  if (FillSize < 0) {
2734    Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2735    NumValues = 0;
2736  }
2737  if (FillSize > 8) {
2738    Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2739    FillSize = 8;
2740  }
2741
2742  if (!isUInt<32>(FillExpr) && FillSize > 4)
2743    Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2744
2745  if (NumValues > 0) {
2746    int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2747    FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2748    for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2749      getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2750      if (NonZeroFillSize < FillSize)
2751        getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2752    }
2753  }
2754
2755  return false;
2756}
2757
2758/// parseDirectiveOrg
2759///  ::= .org expression [ , expression ]
2760bool AsmParser::parseDirectiveOrg() {
2761  checkForValidSection();
2762
2763  const MCExpr *Offset;
2764  if (parseExpression(Offset))
2765    return true;
2766
2767  // Parse optional fill expression.
2768  int64_t FillExpr = 0;
2769  if (getLexer().isNot(AsmToken::EndOfStatement)) {
2770    if (getLexer().isNot(AsmToken::Comma))
2771      return TokError("unexpected token in '.org' directive");
2772    Lex();
2773
2774    if (parseAbsoluteExpression(FillExpr))
2775      return true;
2776
2777    if (getLexer().isNot(AsmToken::EndOfStatement))
2778      return TokError("unexpected token in '.org' directive");
2779  }
2780
2781  Lex();
2782  getStreamer().emitValueToOffset(Offset, FillExpr);
2783  return false;
2784}
2785
2786/// parseDirectiveAlign
2787///  ::= {.align, ...} expression [ , expression [ , expression ]]
2788bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2789  checkForValidSection();
2790
2791  SMLoc AlignmentLoc = getLexer().getLoc();
2792  int64_t Alignment;
2793  if (parseAbsoluteExpression(Alignment))
2794    return true;
2795
2796  SMLoc MaxBytesLoc;
2797  bool HasFillExpr = false;
2798  int64_t FillExpr = 0;
2799  int64_t MaxBytesToFill = 0;
2800  if (getLexer().isNot(AsmToken::EndOfStatement)) {
2801    if (getLexer().isNot(AsmToken::Comma))
2802      return TokError("unexpected token in directive");
2803    Lex();
2804
2805    // The fill expression can be omitted while specifying a maximum number of
2806    // alignment bytes, e.g:
2807    //  .align 3,,4
2808    if (getLexer().isNot(AsmToken::Comma)) {
2809      HasFillExpr = true;
2810      if (parseAbsoluteExpression(FillExpr))
2811        return true;
2812    }
2813
2814    if (getLexer().isNot(AsmToken::EndOfStatement)) {
2815      if (getLexer().isNot(AsmToken::Comma))
2816        return TokError("unexpected token in directive");
2817      Lex();
2818
2819      MaxBytesLoc = getLexer().getLoc();
2820      if (parseAbsoluteExpression(MaxBytesToFill))
2821        return true;
2822
2823      if (getLexer().isNot(AsmToken::EndOfStatement))
2824        return TokError("unexpected token in directive");
2825    }
2826  }
2827
2828  Lex();
2829
2830  if (!HasFillExpr)
2831    FillExpr = 0;
2832
2833  // Compute alignment in bytes.
2834  if (IsPow2) {
2835    // FIXME: Diagnose overflow.
2836    if (Alignment >= 32) {
2837      Error(AlignmentLoc, "invalid alignment value");
2838      Alignment = 31;
2839    }
2840
2841    Alignment = 1ULL << Alignment;
2842  } else {
2843    // Reject alignments that aren't either a power of two or zero,
2844    // for gas compatibility. Alignment of zero is silently rounded
2845    // up to one.
2846    if (Alignment == 0)
2847      Alignment = 1;
2848    if (!isPowerOf2_64(Alignment))
2849      Error(AlignmentLoc, "alignment must be a power of 2");
2850  }
2851
2852  // Diagnose non-sensical max bytes to align.
2853  if (MaxBytesLoc.isValid()) {
2854    if (MaxBytesToFill < 1) {
2855      Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2856                         "many bytes, ignoring maximum bytes expression");
2857      MaxBytesToFill = 0;
2858    }
2859
2860    if (MaxBytesToFill >= Alignment) {
2861      Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2862                           "has no effect");
2863      MaxBytesToFill = 0;
2864    }
2865  }
2866
2867  // Check whether we should use optimal code alignment for this .align
2868  // directive.
2869  const MCSection *Section = getStreamer().getCurrentSection().first;
2870  assert(Section && "must have section to emit alignment");
2871  bool UseCodeAlign = Section->UseCodeAlign();
2872  if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2873      ValueSize == 1 && UseCodeAlign) {
2874    getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2875  } else {
2876    // FIXME: Target specific behavior about how the "extra" bytes are filled.
2877    getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2878                                       MaxBytesToFill);
2879  }
2880
2881  return false;
2882}
2883
2884/// parseDirectiveFile
2885/// ::= .file [number] filename
2886/// ::= .file number directory filename
2887bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2888  // FIXME: I'm not sure what this is.
2889  int64_t FileNumber = -1;
2890  SMLoc FileNumberLoc = getLexer().getLoc();
2891  if (getLexer().is(AsmToken::Integer)) {
2892    FileNumber = getTok().getIntVal();
2893    Lex();
2894
2895    if (FileNumber < 1)
2896      return TokError("file number less than one");
2897  }
2898
2899  if (getLexer().isNot(AsmToken::String))
2900    return TokError("unexpected token in '.file' directive");
2901
2902  // Usually the directory and filename together, otherwise just the directory.
2903  // Allow the strings to have escaped octal character sequence.
2904  std::string Path = getTok().getString();
2905  if (parseEscapedString(Path))
2906    return true;
2907  Lex();
2908
2909  StringRef Directory;
2910  StringRef Filename;
2911  std::string FilenameData;
2912  if (getLexer().is(AsmToken::String)) {
2913    if (FileNumber == -1)
2914      return TokError("explicit path specified, but no file number");
2915    if (parseEscapedString(FilenameData))
2916      return true;
2917    Filename = FilenameData;
2918    Directory = Path;
2919    Lex();
2920  } else {
2921    Filename = Path;
2922  }
2923
2924  if (getLexer().isNot(AsmToken::EndOfStatement))
2925    return TokError("unexpected token in '.file' directive");
2926
2927  if (FileNumber == -1)
2928    getStreamer().EmitFileDirective(Filename);
2929  else {
2930    if (getContext().getGenDwarfForAssembly())
2931      Error(DirectiveLoc,
2932            "input can't have .file dwarf directives when -g is "
2933            "used to generate dwarf debug info for assembly code");
2934
2935    if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2936        0)
2937      Error(FileNumberLoc, "file number already allocated");
2938  }
2939
2940  return false;
2941}
2942
2943/// parseDirectiveLine
2944/// ::= .line [number]
2945bool AsmParser::parseDirectiveLine() {
2946  if (getLexer().isNot(AsmToken::EndOfStatement)) {
2947    if (getLexer().isNot(AsmToken::Integer))
2948      return TokError("unexpected token in '.line' directive");
2949
2950    int64_t LineNumber = getTok().getIntVal();
2951    (void)LineNumber;
2952    Lex();
2953
2954    // FIXME: Do something with the .line.
2955  }
2956
2957  if (getLexer().isNot(AsmToken::EndOfStatement))
2958    return TokError("unexpected token in '.line' directive");
2959
2960  return false;
2961}
2962
2963/// parseDirectiveLoc
2964/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2965///                                [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2966/// The first number is a file number, must have been previously assigned with
2967/// a .file directive, the second number is the line number and optionally the
2968/// third number is a column position (zero if not specified).  The remaining
2969/// optional items are .loc sub-directives.
2970bool AsmParser::parseDirectiveLoc() {
2971  if (getLexer().isNot(AsmToken::Integer))
2972    return TokError("unexpected token in '.loc' directive");
2973  int64_t FileNumber = getTok().getIntVal();
2974  if (FileNumber < 1)
2975    return TokError("file number less than one in '.loc' directive");
2976  if (!getContext().isValidDwarfFileNumber(FileNumber))
2977    return TokError("unassigned file number in '.loc' directive");
2978  Lex();
2979
2980  int64_t LineNumber = 0;
2981  if (getLexer().is(AsmToken::Integer)) {
2982    LineNumber = getTok().getIntVal();
2983    if (LineNumber < 0)
2984      return TokError("line number less than zero in '.loc' directive");
2985    Lex();
2986  }
2987
2988  int64_t ColumnPos = 0;
2989  if (getLexer().is(AsmToken::Integer)) {
2990    ColumnPos = getTok().getIntVal();
2991    if (ColumnPos < 0)
2992      return TokError("column position less than zero in '.loc' directive");
2993    Lex();
2994  }
2995
2996  unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2997  unsigned Isa = 0;
2998  int64_t Discriminator = 0;
2999  if (getLexer().isNot(AsmToken::EndOfStatement)) {
3000    for (;;) {
3001      if (getLexer().is(AsmToken::EndOfStatement))
3002        break;
3003
3004      StringRef Name;
3005      SMLoc Loc = getTok().getLoc();
3006      if (parseIdentifier(Name))
3007        return TokError("unexpected token in '.loc' directive");
3008
3009      if (Name == "basic_block")
3010        Flags |= DWARF2_FLAG_BASIC_BLOCK;
3011      else if (Name == "prologue_end")
3012        Flags |= DWARF2_FLAG_PROLOGUE_END;
3013      else if (Name == "epilogue_begin")
3014        Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3015      else if (Name == "is_stmt") {
3016        Loc = getTok().getLoc();
3017        const MCExpr *Value;
3018        if (parseExpression(Value))
3019          return true;
3020        // The expression must be the constant 0 or 1.
3021        if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3022          int Value = MCE->getValue();
3023          if (Value == 0)
3024            Flags &= ~DWARF2_FLAG_IS_STMT;
3025          else if (Value == 1)
3026            Flags |= DWARF2_FLAG_IS_STMT;
3027          else
3028            return Error(Loc, "is_stmt value not 0 or 1");
3029        } else {
3030          return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3031        }
3032      } else if (Name == "isa") {
3033        Loc = getTok().getLoc();
3034        const MCExpr *Value;
3035        if (parseExpression(Value))
3036          return true;
3037        // The expression must be a constant greater or equal to 0.
3038        if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3039          int Value = MCE->getValue();
3040          if (Value < 0)
3041            return Error(Loc, "isa number less than zero");
3042          Isa = Value;
3043        } else {
3044          return Error(Loc, "isa number not a constant value");
3045        }
3046      } else if (Name == "discriminator") {
3047        if (parseAbsoluteExpression(Discriminator))
3048          return true;
3049      } else {
3050        return Error(Loc, "unknown sub-directive in '.loc' directive");
3051      }
3052
3053      if (getLexer().is(AsmToken::EndOfStatement))
3054        break;
3055    }
3056  }
3057
3058  getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3059                                      Isa, Discriminator, StringRef());
3060
3061  return false;
3062}
3063
3064/// parseDirectiveStabs
3065/// ::= .stabs string, number, number, number
3066bool AsmParser::parseDirectiveStabs() {
3067  return TokError("unsupported directive '.stabs'");
3068}
3069
3070/// parseDirectiveCFISections
3071/// ::= .cfi_sections section [, section]
3072bool AsmParser::parseDirectiveCFISections() {
3073  StringRef Name;
3074  bool EH = false;
3075  bool Debug = false;
3076
3077  if (parseIdentifier(Name))
3078    return TokError("Expected an identifier");
3079
3080  if (Name == ".eh_frame")
3081    EH = true;
3082  else if (Name == ".debug_frame")
3083    Debug = true;
3084
3085  if (getLexer().is(AsmToken::Comma)) {
3086    Lex();
3087
3088    if (parseIdentifier(Name))
3089      return TokError("Expected an identifier");
3090
3091    if (Name == ".eh_frame")
3092      EH = true;
3093    else if (Name == ".debug_frame")
3094      Debug = true;
3095  }
3096
3097  getStreamer().EmitCFISections(EH, Debug);
3098  return false;
3099}
3100
3101/// parseDirectiveCFIStartProc
3102/// ::= .cfi_startproc [simple]
3103bool AsmParser::parseDirectiveCFIStartProc() {
3104  StringRef Simple;
3105  if (getLexer().isNot(AsmToken::EndOfStatement))
3106    if (parseIdentifier(Simple) || Simple != "simple")
3107      return TokError("unexpected token in .cfi_startproc directive");
3108
3109  getStreamer().EmitCFIStartProc(!Simple.empty());
3110  return false;
3111}
3112
3113/// parseDirectiveCFIEndProc
3114/// ::= .cfi_endproc
3115bool AsmParser::parseDirectiveCFIEndProc() {
3116  getStreamer().EmitCFIEndProc();
3117  return false;
3118}
3119
3120/// \brief parse register name or number.
3121bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
3122                                              SMLoc DirectiveLoc) {
3123  unsigned RegNo;
3124
3125  if (getLexer().isNot(AsmToken::Integer)) {
3126    if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3127      return true;
3128    Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
3129  } else
3130    return parseAbsoluteExpression(Register);
3131
3132  return false;
3133}
3134
3135/// parseDirectiveCFIDefCfa
3136/// ::= .cfi_def_cfa register,  offset
3137bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3138  int64_t Register = 0;
3139  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3140    return true;
3141
3142  if (getLexer().isNot(AsmToken::Comma))
3143    return TokError("unexpected token in directive");
3144  Lex();
3145
3146  int64_t Offset = 0;
3147  if (parseAbsoluteExpression(Offset))
3148    return true;
3149
3150  getStreamer().EmitCFIDefCfa(Register, Offset);
3151  return false;
3152}
3153
3154/// parseDirectiveCFIDefCfaOffset
3155/// ::= .cfi_def_cfa_offset offset
3156bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3157  int64_t Offset = 0;
3158  if (parseAbsoluteExpression(Offset))
3159    return true;
3160
3161  getStreamer().EmitCFIDefCfaOffset(Offset);
3162  return false;
3163}
3164
3165/// parseDirectiveCFIRegister
3166/// ::= .cfi_register register, register
3167bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3168  int64_t Register1 = 0;
3169  if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3170    return true;
3171
3172  if (getLexer().isNot(AsmToken::Comma))
3173    return TokError("unexpected token in directive");
3174  Lex();
3175
3176  int64_t Register2 = 0;
3177  if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3178    return true;
3179
3180  getStreamer().EmitCFIRegister(Register1, Register2);
3181  return false;
3182}
3183
3184/// parseDirectiveCFIWindowSave
3185/// ::= .cfi_window_save
3186bool AsmParser::parseDirectiveCFIWindowSave() {
3187  getStreamer().EmitCFIWindowSave();
3188  return false;
3189}
3190
3191/// parseDirectiveCFIAdjustCfaOffset
3192/// ::= .cfi_adjust_cfa_offset adjustment
3193bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3194  int64_t Adjustment = 0;
3195  if (parseAbsoluteExpression(Adjustment))
3196    return true;
3197
3198  getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3199  return false;
3200}
3201
3202/// parseDirectiveCFIDefCfaRegister
3203/// ::= .cfi_def_cfa_register register
3204bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3205  int64_t Register = 0;
3206  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3207    return true;
3208
3209  getStreamer().EmitCFIDefCfaRegister(Register);
3210  return false;
3211}
3212
3213/// parseDirectiveCFIOffset
3214/// ::= .cfi_offset register, offset
3215bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3216  int64_t Register = 0;
3217  int64_t Offset = 0;
3218
3219  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3220    return true;
3221
3222  if (getLexer().isNot(AsmToken::Comma))
3223    return TokError("unexpected token in directive");
3224  Lex();
3225
3226  if (parseAbsoluteExpression(Offset))
3227    return true;
3228
3229  getStreamer().EmitCFIOffset(Register, Offset);
3230  return false;
3231}
3232
3233/// parseDirectiveCFIRelOffset
3234/// ::= .cfi_rel_offset register, offset
3235bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3236  int64_t Register = 0;
3237
3238  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3239    return true;
3240
3241  if (getLexer().isNot(AsmToken::Comma))
3242    return TokError("unexpected token in directive");
3243  Lex();
3244
3245  int64_t Offset = 0;
3246  if (parseAbsoluteExpression(Offset))
3247    return true;
3248
3249  getStreamer().EmitCFIRelOffset(Register, Offset);
3250  return false;
3251}
3252
3253static bool isValidEncoding(int64_t Encoding) {
3254  if (Encoding & ~0xff)
3255    return false;
3256
3257  if (Encoding == dwarf::DW_EH_PE_omit)
3258    return true;
3259
3260  const unsigned Format = Encoding & 0xf;
3261  if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3262      Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3263      Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3264      Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3265    return false;
3266
3267  const unsigned Application = Encoding & 0x70;
3268  if (Application != dwarf::DW_EH_PE_absptr &&
3269      Application != dwarf::DW_EH_PE_pcrel)
3270    return false;
3271
3272  return true;
3273}
3274
3275/// parseDirectiveCFIPersonalityOrLsda
3276/// IsPersonality true for cfi_personality, false for cfi_lsda
3277/// ::= .cfi_personality encoding, [symbol_name]
3278/// ::= .cfi_lsda encoding, [symbol_name]
3279bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3280  int64_t Encoding = 0;
3281  if (parseAbsoluteExpression(Encoding))
3282    return true;
3283  if (Encoding == dwarf::DW_EH_PE_omit)
3284    return false;
3285
3286  if (!isValidEncoding(Encoding))
3287    return TokError("unsupported encoding.");
3288
3289  if (getLexer().isNot(AsmToken::Comma))
3290    return TokError("unexpected token in directive");
3291  Lex();
3292
3293  StringRef Name;
3294  if (parseIdentifier(Name))
3295    return TokError("expected identifier in directive");
3296
3297  MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3298
3299  if (IsPersonality)
3300    getStreamer().EmitCFIPersonality(Sym, Encoding);
3301  else
3302    getStreamer().EmitCFILsda(Sym, Encoding);
3303  return false;
3304}
3305
3306/// parseDirectiveCFIRememberState
3307/// ::= .cfi_remember_state
3308bool AsmParser::parseDirectiveCFIRememberState() {
3309  getStreamer().EmitCFIRememberState();
3310  return false;
3311}
3312
3313/// parseDirectiveCFIRestoreState
3314/// ::= .cfi_remember_state
3315bool AsmParser::parseDirectiveCFIRestoreState() {
3316  getStreamer().EmitCFIRestoreState();
3317  return false;
3318}
3319
3320/// parseDirectiveCFISameValue
3321/// ::= .cfi_same_value register
3322bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3323  int64_t Register = 0;
3324
3325  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3326    return true;
3327
3328  getStreamer().EmitCFISameValue(Register);
3329  return false;
3330}
3331
3332/// parseDirectiveCFIRestore
3333/// ::= .cfi_restore register
3334bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3335  int64_t Register = 0;
3336  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3337    return true;
3338
3339  getStreamer().EmitCFIRestore(Register);
3340  return false;
3341}
3342
3343/// parseDirectiveCFIEscape
3344/// ::= .cfi_escape expression[,...]
3345bool AsmParser::parseDirectiveCFIEscape() {
3346  std::string Values;
3347  int64_t CurrValue;
3348  if (parseAbsoluteExpression(CurrValue))
3349    return true;
3350
3351  Values.push_back((uint8_t)CurrValue);
3352
3353  while (getLexer().is(AsmToken::Comma)) {
3354    Lex();
3355
3356    if (parseAbsoluteExpression(CurrValue))
3357      return true;
3358
3359    Values.push_back((uint8_t)CurrValue);
3360  }
3361
3362  getStreamer().EmitCFIEscape(Values);
3363  return false;
3364}
3365
3366/// parseDirectiveCFISignalFrame
3367/// ::= .cfi_signal_frame
3368bool AsmParser::parseDirectiveCFISignalFrame() {
3369  if (getLexer().isNot(AsmToken::EndOfStatement))
3370    return Error(getLexer().getLoc(),
3371                 "unexpected token in '.cfi_signal_frame'");
3372
3373  getStreamer().EmitCFISignalFrame();
3374  return false;
3375}
3376
3377/// parseDirectiveCFIUndefined
3378/// ::= .cfi_undefined register
3379bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3380  int64_t Register = 0;
3381
3382  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3383    return true;
3384
3385  getStreamer().EmitCFIUndefined(Register);
3386  return false;
3387}
3388
3389/// parseDirectiveMacrosOnOff
3390/// ::= .macros_on
3391/// ::= .macros_off
3392bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3393  if (getLexer().isNot(AsmToken::EndOfStatement))
3394    return Error(getLexer().getLoc(),
3395                 "unexpected token in '" + Directive + "' directive");
3396
3397  setMacrosEnabled(Directive == ".macros_on");
3398  return false;
3399}
3400
3401/// parseDirectiveMacro
3402/// ::= .macro name[,] [parameters]
3403bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3404  StringRef Name;
3405  if (parseIdentifier(Name))
3406    return TokError("expected identifier in '.macro' directive");
3407
3408  if (getLexer().is(AsmToken::Comma))
3409    Lex();
3410
3411  MCAsmMacroParameters Parameters;
3412  while (getLexer().isNot(AsmToken::EndOfStatement)) {
3413
3414    if (!Parameters.empty() && Parameters.back().Vararg)
3415      return Error(Lexer.getLoc(),
3416                   "Vararg parameter '" + Parameters.back().Name +
3417                   "' should be last one in the list of parameters.");
3418
3419    MCAsmMacroParameter Parameter;
3420    if (parseIdentifier(Parameter.Name))
3421      return TokError("expected identifier in '.macro' directive");
3422
3423    if (Lexer.is(AsmToken::Colon)) {
3424      Lex();  // consume ':'
3425
3426      SMLoc QualLoc;
3427      StringRef Qualifier;
3428
3429      QualLoc = Lexer.getLoc();
3430      if (parseIdentifier(Qualifier))
3431        return Error(QualLoc, "missing parameter qualifier for "
3432                     "'" + Parameter.Name + "' in macro '" + Name + "'");
3433
3434      if (Qualifier == "req")
3435        Parameter.Required = true;
3436      else if (Qualifier == "vararg")
3437        Parameter.Vararg = true;
3438      else
3439        return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3440                     "for '" + Parameter.Name + "' in macro '" + Name + "'");
3441    }
3442
3443    if (getLexer().is(AsmToken::Equal)) {
3444      Lex();
3445
3446      SMLoc ParamLoc;
3447
3448      ParamLoc = Lexer.getLoc();
3449      if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3450        return true;
3451
3452      if (Parameter.Required)
3453        Warning(ParamLoc, "pointless default value for required parameter "
3454                "'" + Parameter.Name + "' in macro '" + Name + "'");
3455    }
3456
3457    Parameters.push_back(std::move(Parameter));
3458
3459    if (getLexer().is(AsmToken::Comma))
3460      Lex();
3461  }
3462
3463  // Eat the end of statement.
3464  Lex();
3465
3466  AsmToken EndToken, StartToken = getTok();
3467  unsigned MacroDepth = 0;
3468
3469  // Lex the macro definition.
3470  for (;;) {
3471    // Check whether we have reached the end of the file.
3472    if (getLexer().is(AsmToken::Eof))
3473      return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3474
3475    // Otherwise, check whether we have reach the .endmacro.
3476    if (getLexer().is(AsmToken::Identifier)) {
3477      if (getTok().getIdentifier() == ".endm" ||
3478          getTok().getIdentifier() == ".endmacro") {
3479        if (MacroDepth == 0) { // Outermost macro.
3480          EndToken = getTok();
3481          Lex();
3482          if (getLexer().isNot(AsmToken::EndOfStatement))
3483            return TokError("unexpected token in '" + EndToken.getIdentifier() +
3484                            "' directive");
3485          break;
3486        } else {
3487          // Otherwise we just found the end of an inner macro.
3488          --MacroDepth;
3489        }
3490      } else if (getTok().getIdentifier() == ".macro") {
3491        // We allow nested macros. Those aren't instantiated until the outermost
3492        // macro is expanded so just ignore them for now.
3493        ++MacroDepth;
3494      }
3495    }
3496
3497    // Otherwise, scan til the end of the statement.
3498    eatToEndOfStatement();
3499  }
3500
3501  if (lookupMacro(Name)) {
3502    return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3503  }
3504
3505  const char *BodyStart = StartToken.getLoc().getPointer();
3506  const char *BodyEnd = EndToken.getLoc().getPointer();
3507  StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3508  checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3509  defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
3510  return false;
3511}
3512
3513/// checkForBadMacro
3514///
3515/// With the support added for named parameters there may be code out there that
3516/// is transitioning from positional parameters.  In versions of gas that did
3517/// not support named parameters they would be ignored on the macro definition.
3518/// But to support both styles of parameters this is not possible so if a macro
3519/// definition has named parameters but does not use them and has what appears
3520/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3521/// warning that the positional parameter found in body which have no effect.
3522/// Hoping the developer will either remove the named parameters from the macro
3523/// definition so the positional parameters get used if that was what was
3524/// intended or change the macro to use the named parameters.  It is possible
3525/// this warning will trigger when the none of the named parameters are used
3526/// and the strings like $1 are infact to simply to be passed trough unchanged.
3527void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3528                                 StringRef Body,
3529                                 ArrayRef<MCAsmMacroParameter> Parameters) {
3530  // If this macro is not defined with named parameters the warning we are
3531  // checking for here doesn't apply.
3532  unsigned NParameters = Parameters.size();
3533  if (NParameters == 0)
3534    return;
3535
3536  bool NamedParametersFound = false;
3537  bool PositionalParametersFound = false;
3538
3539  // Look at the body of the macro for use of both the named parameters and what
3540  // are likely to be positional parameters.  This is what expandMacro() is
3541  // doing when it finds the parameters in the body.
3542  while (!Body.empty()) {
3543    // Scan for the next possible parameter.
3544    std::size_t End = Body.size(), Pos = 0;
3545    for (; Pos != End; ++Pos) {
3546      // Check for a substitution or escape.
3547      // This macro is defined with parameters, look for \foo, \bar, etc.
3548      if (Body[Pos] == '\\' && Pos + 1 != End)
3549        break;
3550
3551      // This macro should have parameters, but look for $0, $1, ..., $n too.
3552      if (Body[Pos] != '$' || Pos + 1 == End)
3553        continue;
3554      char Next = Body[Pos + 1];
3555      if (Next == '$' || Next == 'n' ||
3556          isdigit(static_cast<unsigned char>(Next)))
3557        break;
3558    }
3559
3560    // Check if we reached the end.
3561    if (Pos == End)
3562      break;
3563
3564    if (Body[Pos] == '$') {
3565      switch (Body[Pos + 1]) {
3566      // $$ => $
3567      case '$':
3568        break;
3569
3570      // $n => number of arguments
3571      case 'n':
3572        PositionalParametersFound = true;
3573        break;
3574
3575      // $[0-9] => argument
3576      default: {
3577        PositionalParametersFound = true;
3578        break;
3579      }
3580      }
3581      Pos += 2;
3582    } else {
3583      unsigned I = Pos + 1;
3584      while (isIdentifierChar(Body[I]) && I + 1 != End)
3585        ++I;
3586
3587      const char *Begin = Body.data() + Pos + 1;
3588      StringRef Argument(Begin, I - (Pos + 1));
3589      unsigned Index = 0;
3590      for (; Index < NParameters; ++Index)
3591        if (Parameters[Index].Name == Argument)
3592          break;
3593
3594      if (Index == NParameters) {
3595        if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3596          Pos += 3;
3597        else {
3598          Pos = I;
3599        }
3600      } else {
3601        NamedParametersFound = true;
3602        Pos += 1 + Argument.size();
3603      }
3604    }
3605    // Update the scan point.
3606    Body = Body.substr(Pos);
3607  }
3608
3609  if (!NamedParametersFound && PositionalParametersFound)
3610    Warning(DirectiveLoc, "macro defined with named parameters which are not "
3611                          "used in macro body, possible positional parameter "
3612                          "found in body which will have no effect");
3613}
3614
3615/// parseDirectiveExitMacro
3616/// ::= .exitm
3617bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3618  if (getLexer().isNot(AsmToken::EndOfStatement))
3619    return TokError("unexpected token in '" + Directive + "' directive");
3620
3621  if (!isInsideMacroInstantiation())
3622    return TokError("unexpected '" + Directive + "' in file, "
3623                                                 "no current macro definition");
3624
3625  // Exit all conditionals that are active in the current macro.
3626  while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3627    TheCondState = TheCondStack.back();
3628    TheCondStack.pop_back();
3629  }
3630
3631  handleMacroExit();
3632  return false;
3633}
3634
3635/// parseDirectiveEndMacro
3636/// ::= .endm
3637/// ::= .endmacro
3638bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3639  if (getLexer().isNot(AsmToken::EndOfStatement))
3640    return TokError("unexpected token in '" + Directive + "' directive");
3641
3642  // If we are inside a macro instantiation, terminate the current
3643  // instantiation.
3644  if (isInsideMacroInstantiation()) {
3645    handleMacroExit();
3646    return false;
3647  }
3648
3649  // Otherwise, this .endmacro is a stray entry in the file; well formed
3650  // .endmacro directives are handled during the macro definition parsing.
3651  return TokError("unexpected '" + Directive + "' in file, "
3652                                               "no current macro definition");
3653}
3654
3655/// parseDirectivePurgeMacro
3656/// ::= .purgem
3657bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3658  StringRef Name;
3659  if (parseIdentifier(Name))
3660    return TokError("expected identifier in '.purgem' directive");
3661
3662  if (getLexer().isNot(AsmToken::EndOfStatement))
3663    return TokError("unexpected token in '.purgem' directive");
3664
3665  if (!lookupMacro(Name))
3666    return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3667
3668  undefineMacro(Name);
3669  return false;
3670}
3671
3672/// parseDirectiveBundleAlignMode
3673/// ::= {.bundle_align_mode} expression
3674bool AsmParser::parseDirectiveBundleAlignMode() {
3675  checkForValidSection();
3676
3677  // Expect a single argument: an expression that evaluates to a constant
3678  // in the inclusive range 0-30.
3679  SMLoc ExprLoc = getLexer().getLoc();
3680  int64_t AlignSizePow2;
3681  if (parseAbsoluteExpression(AlignSizePow2))
3682    return true;
3683  else if (getLexer().isNot(AsmToken::EndOfStatement))
3684    return TokError("unexpected token after expression in"
3685                    " '.bundle_align_mode' directive");
3686  else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3687    return Error(ExprLoc,
3688                 "invalid bundle alignment size (expected between 0 and 30)");
3689
3690  Lex();
3691
3692  // Because of AlignSizePow2's verified range we can safely truncate it to
3693  // unsigned.
3694  getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3695  return false;
3696}
3697
3698/// parseDirectiveBundleLock
3699/// ::= {.bundle_lock} [align_to_end]
3700bool AsmParser::parseDirectiveBundleLock() {
3701  checkForValidSection();
3702  bool AlignToEnd = false;
3703
3704  if (getLexer().isNot(AsmToken::EndOfStatement)) {
3705    StringRef Option;
3706    SMLoc Loc = getTok().getLoc();
3707    const char *kInvalidOptionError =
3708        "invalid option for '.bundle_lock' directive";
3709
3710    if (parseIdentifier(Option))
3711      return Error(Loc, kInvalidOptionError);
3712
3713    if (Option != "align_to_end")
3714      return Error(Loc, kInvalidOptionError);
3715    else if (getLexer().isNot(AsmToken::EndOfStatement))
3716      return Error(Loc,
3717                   "unexpected token after '.bundle_lock' directive option");
3718    AlignToEnd = true;
3719  }
3720
3721  Lex();
3722
3723  getStreamer().EmitBundleLock(AlignToEnd);
3724  return false;
3725}
3726
3727/// parseDirectiveBundleLock
3728/// ::= {.bundle_lock}
3729bool AsmParser::parseDirectiveBundleUnlock() {
3730  checkForValidSection();
3731
3732  if (getLexer().isNot(AsmToken::EndOfStatement))
3733    return TokError("unexpected token in '.bundle_unlock' directive");
3734  Lex();
3735
3736  getStreamer().EmitBundleUnlock();
3737  return false;
3738}
3739
3740/// parseDirectiveSpace
3741/// ::= (.skip | .space) expression [ , expression ]
3742bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3743  checkForValidSection();
3744
3745  int64_t NumBytes;
3746  if (parseAbsoluteExpression(NumBytes))
3747    return true;
3748
3749  int64_t FillExpr = 0;
3750  if (getLexer().isNot(AsmToken::EndOfStatement)) {
3751    if (getLexer().isNot(AsmToken::Comma))
3752      return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3753    Lex();
3754
3755    if (parseAbsoluteExpression(FillExpr))
3756      return true;
3757
3758    if (getLexer().isNot(AsmToken::EndOfStatement))
3759      return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3760  }
3761
3762  Lex();
3763
3764  if (NumBytes <= 0)
3765    return TokError("invalid number of bytes in '" + Twine(IDVal) +
3766                    "' directive");
3767
3768  // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3769  getStreamer().EmitFill(NumBytes, FillExpr);
3770
3771  return false;
3772}
3773
3774/// parseDirectiveLEB128
3775/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
3776bool AsmParser::parseDirectiveLEB128(bool Signed) {
3777  checkForValidSection();
3778  const MCExpr *Value;
3779
3780  for (;;) {
3781    if (parseExpression(Value))
3782      return true;
3783
3784    if (Signed)
3785      getStreamer().EmitSLEB128Value(Value);
3786    else
3787      getStreamer().EmitULEB128Value(Value);
3788
3789    if (getLexer().is(AsmToken::EndOfStatement))
3790      break;
3791
3792    if (getLexer().isNot(AsmToken::Comma))
3793      return TokError("unexpected token in directive");
3794    Lex();
3795  }
3796
3797  return false;
3798}
3799
3800/// parseDirectiveSymbolAttribute
3801///  ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3802bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3803  if (getLexer().isNot(AsmToken::EndOfStatement)) {
3804    for (;;) {
3805      StringRef Name;
3806      SMLoc Loc = getTok().getLoc();
3807
3808      if (parseIdentifier(Name))
3809        return Error(Loc, "expected identifier in directive");
3810
3811      MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3812
3813      // Assembler local symbols don't make any sense here. Complain loudly.
3814      if (Sym->isTemporary())
3815        return Error(Loc, "non-local symbol required in directive");
3816
3817      if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3818        return Error(Loc, "unable to emit symbol attribute");
3819
3820      if (getLexer().is(AsmToken::EndOfStatement))
3821        break;
3822
3823      if (getLexer().isNot(AsmToken::Comma))
3824        return TokError("unexpected token in directive");
3825      Lex();
3826    }
3827  }
3828
3829  Lex();
3830  return false;
3831}
3832
3833/// parseDirectiveComm
3834///  ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3835bool AsmParser::parseDirectiveComm(bool IsLocal) {
3836  checkForValidSection();
3837
3838  SMLoc IDLoc = getLexer().getLoc();
3839  StringRef Name;
3840  if (parseIdentifier(Name))
3841    return TokError("expected identifier in directive");
3842
3843  // Handle the identifier as the key symbol.
3844  MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
3845
3846  if (getLexer().isNot(AsmToken::Comma))
3847    return TokError("unexpected token in directive");
3848  Lex();
3849
3850  int64_t Size;
3851  SMLoc SizeLoc = getLexer().getLoc();
3852  if (parseAbsoluteExpression(Size))
3853    return true;
3854
3855  int64_t Pow2Alignment = 0;
3856  SMLoc Pow2AlignmentLoc;
3857  if (getLexer().is(AsmToken::Comma)) {
3858    Lex();
3859    Pow2AlignmentLoc = getLexer().getLoc();
3860    if (parseAbsoluteExpression(Pow2Alignment))
3861      return true;
3862
3863    LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3864    if (IsLocal && LCOMM == LCOMM::NoAlignment)
3865      return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3866
3867    // If this target takes alignments in bytes (not log) validate and convert.
3868    if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3869        (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3870      if (!isPowerOf2_64(Pow2Alignment))
3871        return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3872      Pow2Alignment = Log2_64(Pow2Alignment);
3873    }
3874  }
3875
3876  if (getLexer().isNot(AsmToken::EndOfStatement))
3877    return TokError("unexpected token in '.comm' or '.lcomm' directive");
3878
3879  Lex();
3880
3881  // NOTE: a size of zero for a .comm should create a undefined symbol
3882  // but a size of .lcomm creates a bss symbol of size zero.
3883  if (Size < 0)
3884    return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3885                          "be less than zero");
3886
3887  // NOTE: The alignment in the directive is a power of 2 value, the assembler
3888  // may internally end up wanting an alignment in bytes.
3889  // FIXME: Diagnose overflow.
3890  if (Pow2Alignment < 0)
3891    return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3892                                   "alignment, can't be less than zero");
3893
3894  if (!Sym->isUndefined())
3895    return Error(IDLoc, "invalid symbol redefinition");
3896
3897  // Create the Symbol as a common or local common with Size and Pow2Alignment
3898  if (IsLocal) {
3899    getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3900    return false;
3901  }
3902
3903  getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3904  return false;
3905}
3906
3907/// parseDirectiveAbort
3908///  ::= .abort [... message ...]
3909bool AsmParser::parseDirectiveAbort() {
3910  // FIXME: Use loc from directive.
3911  SMLoc Loc = getLexer().getLoc();
3912
3913  StringRef Str = parseStringToEndOfStatement();
3914  if (getLexer().isNot(AsmToken::EndOfStatement))
3915    return TokError("unexpected token in '.abort' directive");
3916
3917  Lex();
3918
3919  if (Str.empty())
3920    Error(Loc, ".abort detected. Assembly stopping.");
3921  else
3922    Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3923  // FIXME: Actually abort assembly here.
3924
3925  return false;
3926}
3927
3928/// parseDirectiveInclude
3929///  ::= .include "filename"
3930bool AsmParser::parseDirectiveInclude() {
3931  if (getLexer().isNot(AsmToken::String))
3932    return TokError("expected string in '.include' directive");
3933
3934  // Allow the strings to have escaped octal character sequence.
3935  std::string Filename;
3936  if (parseEscapedString(Filename))
3937    return true;
3938  SMLoc IncludeLoc = getLexer().getLoc();
3939  Lex();
3940
3941  if (getLexer().isNot(AsmToken::EndOfStatement))
3942    return TokError("unexpected token in '.include' directive");
3943
3944  // Attempt to switch the lexer to the included file before consuming the end
3945  // of statement to avoid losing it when we switch.
3946  if (enterIncludeFile(Filename)) {
3947    Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3948    return true;
3949  }
3950
3951  return false;
3952}
3953
3954/// parseDirectiveIncbin
3955///  ::= .incbin "filename"
3956bool AsmParser::parseDirectiveIncbin() {
3957  if (getLexer().isNot(AsmToken::String))
3958    return TokError("expected string in '.incbin' directive");
3959
3960  // Allow the strings to have escaped octal character sequence.
3961  std::string Filename;
3962  if (parseEscapedString(Filename))
3963    return true;
3964  SMLoc IncbinLoc = getLexer().getLoc();
3965  Lex();
3966
3967  if (getLexer().isNot(AsmToken::EndOfStatement))
3968    return TokError("unexpected token in '.incbin' directive");
3969
3970  // Attempt to process the included file.
3971  if (processIncbinFile(Filename)) {
3972    Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3973    return true;
3974  }
3975
3976  return false;
3977}
3978
3979/// parseDirectiveIf
3980/// ::= .if{,eq,ge,gt,le,lt,ne} expression
3981bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
3982  TheCondStack.push_back(TheCondState);
3983  TheCondState.TheCond = AsmCond::IfCond;
3984  if (TheCondState.Ignore) {
3985    eatToEndOfStatement();
3986  } else {
3987    int64_t ExprValue;
3988    if (parseAbsoluteExpression(ExprValue))
3989      return true;
3990
3991    if (getLexer().isNot(AsmToken::EndOfStatement))
3992      return TokError("unexpected token in '.if' directive");
3993
3994    Lex();
3995
3996    switch (DirKind) {
3997    default:
3998      llvm_unreachable("unsupported directive");
3999    case DK_IF:
4000    case DK_IFNE:
4001      break;
4002    case DK_IFEQ:
4003      ExprValue = ExprValue == 0;
4004      break;
4005    case DK_IFGE:
4006      ExprValue = ExprValue >= 0;
4007      break;
4008    case DK_IFGT:
4009      ExprValue = ExprValue > 0;
4010      break;
4011    case DK_IFLE:
4012      ExprValue = ExprValue <= 0;
4013      break;
4014    case DK_IFLT:
4015      ExprValue = ExprValue < 0;
4016      break;
4017    }
4018
4019    TheCondState.CondMet = ExprValue;
4020    TheCondState.Ignore = !TheCondState.CondMet;
4021  }
4022
4023  return false;
4024}
4025
4026/// parseDirectiveIfb
4027/// ::= .ifb string
4028bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
4029  TheCondStack.push_back(TheCondState);
4030  TheCondState.TheCond = AsmCond::IfCond;
4031
4032  if (TheCondState.Ignore) {
4033    eatToEndOfStatement();
4034  } else {
4035    StringRef Str = parseStringToEndOfStatement();
4036
4037    if (getLexer().isNot(AsmToken::EndOfStatement))
4038      return TokError("unexpected token in '.ifb' directive");
4039
4040    Lex();
4041
4042    TheCondState.CondMet = ExpectBlank == Str.empty();
4043    TheCondState.Ignore = !TheCondState.CondMet;
4044  }
4045
4046  return false;
4047}
4048
4049/// parseDirectiveIfc
4050/// ::= .ifc string1, string2
4051/// ::= .ifnc string1, string2
4052bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
4053  TheCondStack.push_back(TheCondState);
4054  TheCondState.TheCond = AsmCond::IfCond;
4055
4056  if (TheCondState.Ignore) {
4057    eatToEndOfStatement();
4058  } else {
4059    StringRef Str1 = parseStringToComma();
4060
4061    if (getLexer().isNot(AsmToken::Comma))
4062      return TokError("unexpected token in '.ifc' directive");
4063
4064    Lex();
4065
4066    StringRef Str2 = parseStringToEndOfStatement();
4067
4068    if (getLexer().isNot(AsmToken::EndOfStatement))
4069      return TokError("unexpected token in '.ifc' directive");
4070
4071    Lex();
4072
4073    TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
4074    TheCondState.Ignore = !TheCondState.CondMet;
4075  }
4076
4077  return false;
4078}
4079
4080/// parseDirectiveIfeqs
4081///   ::= .ifeqs string1, string2
4082bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
4083  if (Lexer.isNot(AsmToken::String)) {
4084    if (ExpectEqual)
4085      TokError("expected string parameter for '.ifeqs' directive");
4086    else
4087      TokError("expected string parameter for '.ifnes' directive");
4088    eatToEndOfStatement();
4089    return true;
4090  }
4091
4092  StringRef String1 = getTok().getStringContents();
4093  Lex();
4094
4095  if (Lexer.isNot(AsmToken::Comma)) {
4096    if (ExpectEqual)
4097      TokError("expected comma after first string for '.ifeqs' directive");
4098    else
4099      TokError("expected comma after first string for '.ifnes' directive");
4100    eatToEndOfStatement();
4101    return true;
4102  }
4103
4104  Lex();
4105
4106  if (Lexer.isNot(AsmToken::String)) {
4107    if (ExpectEqual)
4108      TokError("expected string parameter for '.ifeqs' directive");
4109    else
4110      TokError("expected string parameter for '.ifnes' directive");
4111    eatToEndOfStatement();
4112    return true;
4113  }
4114
4115  StringRef String2 = getTok().getStringContents();
4116  Lex();
4117
4118  TheCondStack.push_back(TheCondState);
4119  TheCondState.TheCond = AsmCond::IfCond;
4120  TheCondState.CondMet = ExpectEqual == (String1 == String2);
4121  TheCondState.Ignore = !TheCondState.CondMet;
4122
4123  return false;
4124}
4125
4126/// parseDirectiveIfdef
4127/// ::= .ifdef symbol
4128bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
4129  StringRef Name;
4130  TheCondStack.push_back(TheCondState);
4131  TheCondState.TheCond = AsmCond::IfCond;
4132
4133  if (TheCondState.Ignore) {
4134    eatToEndOfStatement();
4135  } else {
4136    if (parseIdentifier(Name))
4137      return TokError("expected identifier after '.ifdef'");
4138
4139    Lex();
4140
4141    MCSymbol *Sym = getContext().lookupSymbol(Name);
4142
4143    if (expect_defined)
4144      TheCondState.CondMet = (Sym && !Sym->isUndefined());
4145    else
4146      TheCondState.CondMet = (!Sym || Sym->isUndefined());
4147    TheCondState.Ignore = !TheCondState.CondMet;
4148  }
4149
4150  return false;
4151}
4152
4153/// parseDirectiveElseIf
4154/// ::= .elseif expression
4155bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4156  if (TheCondState.TheCond != AsmCond::IfCond &&
4157      TheCondState.TheCond != AsmCond::ElseIfCond)
4158    Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4159                        " an .elseif");
4160  TheCondState.TheCond = AsmCond::ElseIfCond;
4161
4162  bool LastIgnoreState = false;
4163  if (!TheCondStack.empty())
4164    LastIgnoreState = TheCondStack.back().Ignore;
4165  if (LastIgnoreState || TheCondState.CondMet) {
4166    TheCondState.Ignore = true;
4167    eatToEndOfStatement();
4168  } else {
4169    int64_t ExprValue;
4170    if (parseAbsoluteExpression(ExprValue))
4171      return true;
4172
4173    if (getLexer().isNot(AsmToken::EndOfStatement))
4174      return TokError("unexpected token in '.elseif' directive");
4175
4176    Lex();
4177    TheCondState.CondMet = ExprValue;
4178    TheCondState.Ignore = !TheCondState.CondMet;
4179  }
4180
4181  return false;
4182}
4183
4184/// parseDirectiveElse
4185/// ::= .else
4186bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4187  if (getLexer().isNot(AsmToken::EndOfStatement))
4188    return TokError("unexpected token in '.else' directive");
4189
4190  Lex();
4191
4192  if (TheCondState.TheCond != AsmCond::IfCond &&
4193      TheCondState.TheCond != AsmCond::ElseIfCond)
4194    Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4195                        ".elseif");
4196  TheCondState.TheCond = AsmCond::ElseCond;
4197  bool LastIgnoreState = false;
4198  if (!TheCondStack.empty())
4199    LastIgnoreState = TheCondStack.back().Ignore;
4200  if (LastIgnoreState || TheCondState.CondMet)
4201    TheCondState.Ignore = true;
4202  else
4203    TheCondState.Ignore = false;
4204
4205  return false;
4206}
4207
4208/// parseDirectiveEnd
4209/// ::= .end
4210bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4211  if (getLexer().isNot(AsmToken::EndOfStatement))
4212    return TokError("unexpected token in '.end' directive");
4213
4214  Lex();
4215
4216  while (Lexer.isNot(AsmToken::Eof))
4217    Lex();
4218
4219  return false;
4220}
4221
4222/// parseDirectiveError
4223///   ::= .err
4224///   ::= .error [string]
4225bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4226  if (!TheCondStack.empty()) {
4227    if (TheCondStack.back().Ignore) {
4228      eatToEndOfStatement();
4229      return false;
4230    }
4231  }
4232
4233  if (!WithMessage)
4234    return Error(L, ".err encountered");
4235
4236  StringRef Message = ".error directive invoked in source file";
4237  if (Lexer.isNot(AsmToken::EndOfStatement)) {
4238    if (Lexer.isNot(AsmToken::String)) {
4239      TokError(".error argument must be a string");
4240      eatToEndOfStatement();
4241      return true;
4242    }
4243
4244    Message = getTok().getStringContents();
4245    Lex();
4246  }
4247
4248  Error(L, Message);
4249  return true;
4250}
4251
4252/// parseDirectiveWarning
4253///   ::= .warning [string]
4254bool AsmParser::parseDirectiveWarning(SMLoc L) {
4255  if (!TheCondStack.empty()) {
4256    if (TheCondStack.back().Ignore) {
4257      eatToEndOfStatement();
4258      return false;
4259    }
4260  }
4261
4262  StringRef Message = ".warning directive invoked in source file";
4263  if (Lexer.isNot(AsmToken::EndOfStatement)) {
4264    if (Lexer.isNot(AsmToken::String)) {
4265      TokError(".warning argument must be a string");
4266      eatToEndOfStatement();
4267      return true;
4268    }
4269
4270    Message = getTok().getStringContents();
4271    Lex();
4272  }
4273
4274  Warning(L, Message);
4275  return false;
4276}
4277
4278/// parseDirectiveEndIf
4279/// ::= .endif
4280bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4281  if (getLexer().isNot(AsmToken::EndOfStatement))
4282    return TokError("unexpected token in '.endif' directive");
4283
4284  Lex();
4285
4286  if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4287    Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4288                        ".else");
4289  if (!TheCondStack.empty()) {
4290    TheCondState = TheCondStack.back();
4291    TheCondStack.pop_back();
4292  }
4293
4294  return false;
4295}
4296
4297void AsmParser::initializeDirectiveKindMap() {
4298  DirectiveKindMap[".set"] = DK_SET;
4299  DirectiveKindMap[".equ"] = DK_EQU;
4300  DirectiveKindMap[".equiv"] = DK_EQUIV;
4301  DirectiveKindMap[".ascii"] = DK_ASCII;
4302  DirectiveKindMap[".asciz"] = DK_ASCIZ;
4303  DirectiveKindMap[".string"] = DK_STRING;
4304  DirectiveKindMap[".byte"] = DK_BYTE;
4305  DirectiveKindMap[".short"] = DK_SHORT;
4306  DirectiveKindMap[".value"] = DK_VALUE;
4307  DirectiveKindMap[".2byte"] = DK_2BYTE;
4308  DirectiveKindMap[".long"] = DK_LONG;
4309  DirectiveKindMap[".int"] = DK_INT;
4310  DirectiveKindMap[".4byte"] = DK_4BYTE;
4311  DirectiveKindMap[".quad"] = DK_QUAD;
4312  DirectiveKindMap[".8byte"] = DK_8BYTE;
4313  DirectiveKindMap[".octa"] = DK_OCTA;
4314  DirectiveKindMap[".single"] = DK_SINGLE;
4315  DirectiveKindMap[".float"] = DK_FLOAT;
4316  DirectiveKindMap[".double"] = DK_DOUBLE;
4317  DirectiveKindMap[".align"] = DK_ALIGN;
4318  DirectiveKindMap[".align32"] = DK_ALIGN32;
4319  DirectiveKindMap[".balign"] = DK_BALIGN;
4320  DirectiveKindMap[".balignw"] = DK_BALIGNW;
4321  DirectiveKindMap[".balignl"] = DK_BALIGNL;
4322  DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4323  DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4324  DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4325  DirectiveKindMap[".org"] = DK_ORG;
4326  DirectiveKindMap[".fill"] = DK_FILL;
4327  DirectiveKindMap[".zero"] = DK_ZERO;
4328  DirectiveKindMap[".extern"] = DK_EXTERN;
4329  DirectiveKindMap[".globl"] = DK_GLOBL;
4330  DirectiveKindMap[".global"] = DK_GLOBAL;
4331  DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4332  DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4333  DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4334  DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4335  DirectiveKindMap[".reference"] = DK_REFERENCE;
4336  DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4337  DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4338  DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4339  DirectiveKindMap[".comm"] = DK_COMM;
4340  DirectiveKindMap[".common"] = DK_COMMON;
4341  DirectiveKindMap[".lcomm"] = DK_LCOMM;
4342  DirectiveKindMap[".abort"] = DK_ABORT;
4343  DirectiveKindMap[".include"] = DK_INCLUDE;
4344  DirectiveKindMap[".incbin"] = DK_INCBIN;
4345  DirectiveKindMap[".code16"] = DK_CODE16;
4346  DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4347  DirectiveKindMap[".rept"] = DK_REPT;
4348  DirectiveKindMap[".rep"] = DK_REPT;
4349  DirectiveKindMap[".irp"] = DK_IRP;
4350  DirectiveKindMap[".irpc"] = DK_IRPC;
4351  DirectiveKindMap[".endr"] = DK_ENDR;
4352  DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4353  DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4354  DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4355  DirectiveKindMap[".if"] = DK_IF;
4356  DirectiveKindMap[".ifeq"] = DK_IFEQ;
4357  DirectiveKindMap[".ifge"] = DK_IFGE;
4358  DirectiveKindMap[".ifgt"] = DK_IFGT;
4359  DirectiveKindMap[".ifle"] = DK_IFLE;
4360  DirectiveKindMap[".iflt"] = DK_IFLT;
4361  DirectiveKindMap[".ifne"] = DK_IFNE;
4362  DirectiveKindMap[".ifb"] = DK_IFB;
4363  DirectiveKindMap[".ifnb"] = DK_IFNB;
4364  DirectiveKindMap[".ifc"] = DK_IFC;
4365  DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4366  DirectiveKindMap[".ifnc"] = DK_IFNC;
4367  DirectiveKindMap[".ifnes"] = DK_IFNES;
4368  DirectiveKindMap[".ifdef"] = DK_IFDEF;
4369  DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4370  DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4371  DirectiveKindMap[".elseif"] = DK_ELSEIF;
4372  DirectiveKindMap[".else"] = DK_ELSE;
4373  DirectiveKindMap[".end"] = DK_END;
4374  DirectiveKindMap[".endif"] = DK_ENDIF;
4375  DirectiveKindMap[".skip"] = DK_SKIP;
4376  DirectiveKindMap[".space"] = DK_SPACE;
4377  DirectiveKindMap[".file"] = DK_FILE;
4378  DirectiveKindMap[".line"] = DK_LINE;
4379  DirectiveKindMap[".loc"] = DK_LOC;
4380  DirectiveKindMap[".stabs"] = DK_STABS;
4381  DirectiveKindMap[".sleb128"] = DK_SLEB128;
4382  DirectiveKindMap[".uleb128"] = DK_ULEB128;
4383  DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4384  DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4385  DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4386  DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4387  DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4388  DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4389  DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4390  DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4391  DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4392  DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4393  DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4394  DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4395  DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4396  DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4397  DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4398  DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4399  DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4400  DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4401  DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4402  DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4403  DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4404  DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4405  DirectiveKindMap[".macro"] = DK_MACRO;
4406  DirectiveKindMap[".exitm"] = DK_EXITM;
4407  DirectiveKindMap[".endm"] = DK_ENDM;
4408  DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4409  DirectiveKindMap[".purgem"] = DK_PURGEM;
4410  DirectiveKindMap[".err"] = DK_ERR;
4411  DirectiveKindMap[".error"] = DK_ERROR;
4412  DirectiveKindMap[".warning"] = DK_WARNING;
4413  DirectiveKindMap[".reloc"] = DK_RELOC;
4414}
4415
4416MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4417  AsmToken EndToken, StartToken = getTok();
4418
4419  unsigned NestLevel = 0;
4420  for (;;) {
4421    // Check whether we have reached the end of the file.
4422    if (getLexer().is(AsmToken::Eof)) {
4423      Error(DirectiveLoc, "no matching '.endr' in definition");
4424      return nullptr;
4425    }
4426
4427    if (Lexer.is(AsmToken::Identifier) &&
4428        (getTok().getIdentifier() == ".rept")) {
4429      ++NestLevel;
4430    }
4431
4432    // Otherwise, check whether we have reached the .endr.
4433    if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4434      if (NestLevel == 0) {
4435        EndToken = getTok();
4436        Lex();
4437        if (Lexer.isNot(AsmToken::EndOfStatement)) {
4438          TokError("unexpected token in '.endr' directive");
4439          return nullptr;
4440        }
4441        break;
4442      }
4443      --NestLevel;
4444    }
4445
4446    // Otherwise, scan till the end of the statement.
4447    eatToEndOfStatement();
4448  }
4449
4450  const char *BodyStart = StartToken.getLoc().getPointer();
4451  const char *BodyEnd = EndToken.getLoc().getPointer();
4452  StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4453
4454  // We Are Anonymous.
4455  MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
4456  return &MacroLikeBodies.back();
4457}
4458
4459void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4460                                         raw_svector_ostream &OS) {
4461  OS << ".endr\n";
4462
4463  std::unique_ptr<MemoryBuffer> Instantiation =
4464      MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4465
4466  // Create the macro instantiation object and add to the current macro
4467  // instantiation stack.
4468  MacroInstantiation *MI = new MacroInstantiation(
4469      DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
4470  ActiveMacros.push_back(MI);
4471
4472  // Jump to the macro instantiation and prime the lexer.
4473  CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
4474  Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
4475  Lex();
4476}
4477
4478/// parseDirectiveRept
4479///   ::= .rep | .rept count
4480bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4481  const MCExpr *CountExpr;
4482  SMLoc CountLoc = getTok().getLoc();
4483  if (parseExpression(CountExpr))
4484    return true;
4485
4486  int64_t Count;
4487  if (!CountExpr->evaluateAsAbsolute(Count)) {
4488    eatToEndOfStatement();
4489    return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4490  }
4491
4492  if (Count < 0)
4493    return Error(CountLoc, "Count is negative");
4494
4495  if (Lexer.isNot(AsmToken::EndOfStatement))
4496    return TokError("unexpected token in '" + Dir + "' directive");
4497
4498  // Eat the end of statement.
4499  Lex();
4500
4501  // Lex the rept definition.
4502  MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4503  if (!M)
4504    return true;
4505
4506  // Macro instantiation is lexical, unfortunately. We construct a new buffer
4507  // to hold the macro body with substitutions.
4508  SmallString<256> Buf;
4509  raw_svector_ostream OS(Buf);
4510  while (Count--) {
4511    // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4512    if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
4513      return true;
4514  }
4515  instantiateMacroLikeBody(M, DirectiveLoc, OS);
4516
4517  return false;
4518}
4519
4520/// parseDirectiveIrp
4521/// ::= .irp symbol,values
4522bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4523  MCAsmMacroParameter Parameter;
4524
4525  if (parseIdentifier(Parameter.Name))
4526    return TokError("expected identifier in '.irp' directive");
4527
4528  if (Lexer.isNot(AsmToken::Comma))
4529    return TokError("expected comma in '.irp' directive");
4530
4531  Lex();
4532
4533  MCAsmMacroArguments A;
4534  if (parseMacroArguments(nullptr, A))
4535    return true;
4536
4537  // Eat the end of statement.
4538  Lex();
4539
4540  // Lex the irp definition.
4541  MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4542  if (!M)
4543    return true;
4544
4545  // Macro instantiation is lexical, unfortunately. We construct a new buffer
4546  // to hold the macro body with substitutions.
4547  SmallString<256> Buf;
4548  raw_svector_ostream OS(Buf);
4549
4550  for (const MCAsmMacroArgument &Arg : A) {
4551    // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4552    // This is undocumented, but GAS seems to support it.
4553    if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
4554      return true;
4555  }
4556
4557  instantiateMacroLikeBody(M, DirectiveLoc, OS);
4558
4559  return false;
4560}
4561
4562/// parseDirectiveIrpc
4563/// ::= .irpc symbol,values
4564bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4565  MCAsmMacroParameter Parameter;
4566
4567  if (parseIdentifier(Parameter.Name))
4568    return TokError("expected identifier in '.irpc' directive");
4569
4570  if (Lexer.isNot(AsmToken::Comma))
4571    return TokError("expected comma in '.irpc' directive");
4572
4573  Lex();
4574
4575  MCAsmMacroArguments A;
4576  if (parseMacroArguments(nullptr, A))
4577    return true;
4578
4579  if (A.size() != 1 || A.front().size() != 1)
4580    return TokError("unexpected token in '.irpc' directive");
4581
4582  // Eat the end of statement.
4583  Lex();
4584
4585  // Lex the irpc definition.
4586  MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4587  if (!M)
4588    return true;
4589
4590  // Macro instantiation is lexical, unfortunately. We construct a new buffer
4591  // to hold the macro body with substitutions.
4592  SmallString<256> Buf;
4593  raw_svector_ostream OS(Buf);
4594
4595  StringRef Values = A.front().front().getString();
4596  for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4597    MCAsmMacroArgument Arg;
4598    Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
4599
4600    // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4601    // This is undocumented, but GAS seems to support it.
4602    if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
4603      return true;
4604  }
4605
4606  instantiateMacroLikeBody(M, DirectiveLoc, OS);
4607
4608  return false;
4609}
4610
4611bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4612  if (ActiveMacros.empty())
4613    return TokError("unmatched '.endr' directive");
4614
4615  // The only .repl that should get here are the ones created by
4616  // instantiateMacroLikeBody.
4617  assert(getLexer().is(AsmToken::EndOfStatement));
4618
4619  handleMacroExit();
4620  return false;
4621}
4622
4623bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4624                                     size_t Len) {
4625  const MCExpr *Value;
4626  SMLoc ExprLoc = getLexer().getLoc();
4627  if (parseExpression(Value))
4628    return true;
4629  const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4630  if (!MCE)
4631    return Error(ExprLoc, "unexpected expression in _emit");
4632  uint64_t IntValue = MCE->getValue();
4633  if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
4634    return Error(ExprLoc, "literal value out of range for directive");
4635
4636  Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
4637  return false;
4638}
4639
4640bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4641  const MCExpr *Value;
4642  SMLoc ExprLoc = getLexer().getLoc();
4643  if (parseExpression(Value))
4644    return true;
4645  const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4646  if (!MCE)
4647    return Error(ExprLoc, "unexpected expression in align");
4648  uint64_t IntValue = MCE->getValue();
4649  if (!isPowerOf2_64(IntValue))
4650    return Error(ExprLoc, "literal value not a power of two greater then zero");
4651
4652  Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
4653  return false;
4654}
4655
4656// We are comparing pointers, but the pointers are relative to a single string.
4657// Thus, this should always be deterministic.
4658static int rewritesSort(const AsmRewrite *AsmRewriteA,
4659                        const AsmRewrite *AsmRewriteB) {
4660  if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4661    return -1;
4662  if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4663    return 1;
4664
4665  // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4666  // rewrite to the same location.  Make sure the SizeDirective rewrite is
4667  // performed first, then the Imm/ImmPrefix and finally the Input/Output.  This
4668  // ensures the sort algorithm is stable.
4669  if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4670      AsmRewritePrecedence[AsmRewriteB->Kind])
4671    return -1;
4672
4673  if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4674      AsmRewritePrecedence[AsmRewriteB->Kind])
4675    return 1;
4676  llvm_unreachable("Unstable rewrite sort.");
4677}
4678
4679bool AsmParser::parseMSInlineAsm(
4680    void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4681    unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4682    SmallVectorImpl<std::string> &Constraints,
4683    SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4684    const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4685  SmallVector<void *, 4> InputDecls;
4686  SmallVector<void *, 4> OutputDecls;
4687  SmallVector<bool, 4> InputDeclsAddressOf;
4688  SmallVector<bool, 4> OutputDeclsAddressOf;
4689  SmallVector<std::string, 4> InputConstraints;
4690  SmallVector<std::string, 4> OutputConstraints;
4691  SmallVector<unsigned, 4> ClobberRegs;
4692
4693  SmallVector<AsmRewrite, 4> AsmStrRewrites;
4694
4695  // Prime the lexer.
4696  Lex();
4697
4698  // While we have input, parse each statement.
4699  unsigned InputIdx = 0;
4700  unsigned OutputIdx = 0;
4701  while (getLexer().isNot(AsmToken::Eof)) {
4702    ParseStatementInfo Info(&AsmStrRewrites);
4703    if (parseStatement(Info, &SI))
4704      return true;
4705
4706    if (Info.ParseError)
4707      return true;
4708
4709    if (Info.Opcode == ~0U)
4710      continue;
4711
4712    const MCInstrDesc &Desc = MII->get(Info.Opcode);
4713
4714    // Build the list of clobbers, outputs and inputs.
4715    for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4716      MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4717
4718      // Immediate.
4719      if (Operand.isImm())
4720        continue;
4721
4722      // Register operand.
4723      if (Operand.isReg() && !Operand.needAddressOf() &&
4724          !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
4725        unsigned NumDefs = Desc.getNumDefs();
4726        // Clobber.
4727        if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4728          ClobberRegs.push_back(Operand.getReg());
4729        continue;
4730      }
4731
4732      // Expr/Input or Output.
4733      StringRef SymName = Operand.getSymName();
4734      if (SymName.empty())
4735        continue;
4736
4737      void *OpDecl = Operand.getOpDecl();
4738      if (!OpDecl)
4739        continue;
4740
4741      bool isOutput = (i == 1) && Desc.mayStore();
4742      SMLoc Start = SMLoc::getFromPointer(SymName.data());
4743      if (isOutput) {
4744        ++InputIdx;
4745        OutputDecls.push_back(OpDecl);
4746        OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4747        OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
4748        AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
4749      } else {
4750        InputDecls.push_back(OpDecl);
4751        InputDeclsAddressOf.push_back(Operand.needAddressOf());
4752        InputConstraints.push_back(Operand.getConstraint().str());
4753        AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
4754      }
4755    }
4756
4757    // Consider implicit defs to be clobbers.  Think of cpuid and push.
4758    ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
4759                                Desc.getNumImplicitDefs());
4760    ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
4761  }
4762
4763  // Set the number of Outputs and Inputs.
4764  NumOutputs = OutputDecls.size();
4765  NumInputs = InputDecls.size();
4766
4767  // Set the unique clobbers.
4768  array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4769  ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4770                    ClobberRegs.end());
4771  Clobbers.assign(ClobberRegs.size(), std::string());
4772  for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4773    raw_string_ostream OS(Clobbers[I]);
4774    IP->printRegName(OS, ClobberRegs[I]);
4775  }
4776
4777  // Merge the various outputs and inputs.  Output are expected first.
4778  if (NumOutputs || NumInputs) {
4779    unsigned NumExprs = NumOutputs + NumInputs;
4780    OpDecls.resize(NumExprs);
4781    Constraints.resize(NumExprs);
4782    for (unsigned i = 0; i < NumOutputs; ++i) {
4783      OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4784      Constraints[i] = OutputConstraints[i];
4785    }
4786    for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4787      OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4788      Constraints[j] = InputConstraints[i];
4789    }
4790  }
4791
4792  // Build the IR assembly string.
4793  std::string AsmStringIR;
4794  raw_string_ostream OS(AsmStringIR);
4795  StringRef ASMString =
4796      SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4797  const char *AsmStart = ASMString.begin();
4798  const char *AsmEnd = ASMString.end();
4799  array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4800  for (const AsmRewrite &AR : AsmStrRewrites) {
4801    AsmRewriteKind Kind = AR.Kind;
4802    if (Kind == AOK_Delete)
4803      continue;
4804
4805    const char *Loc = AR.Loc.getPointer();
4806    assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4807
4808    // Emit everything up to the immediate/expression.
4809    if (unsigned Len = Loc - AsmStart)
4810      OS << StringRef(AsmStart, Len);
4811
4812    // Skip the original expression.
4813    if (Kind == AOK_Skip) {
4814      AsmStart = Loc + AR.Len;
4815      continue;
4816    }
4817
4818    unsigned AdditionalSkip = 0;
4819    // Rewrite expressions in $N notation.
4820    switch (Kind) {
4821    default:
4822      break;
4823    case AOK_Imm:
4824      OS << "$$" << AR.Val;
4825      break;
4826    case AOK_ImmPrefix:
4827      OS << "$$";
4828      break;
4829    case AOK_Label:
4830      OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
4831      break;
4832    case AOK_Input:
4833      OS << '$' << InputIdx++;
4834      break;
4835    case AOK_Output:
4836      OS << '$' << OutputIdx++;
4837      break;
4838    case AOK_SizeDirective:
4839      switch (AR.Val) {
4840      default: break;
4841      case 8:  OS << "byte ptr "; break;
4842      case 16: OS << "word ptr "; break;
4843      case 32: OS << "dword ptr "; break;
4844      case 64: OS << "qword ptr "; break;
4845      case 80: OS << "xword ptr "; break;
4846      case 128: OS << "xmmword ptr "; break;
4847      case 256: OS << "ymmword ptr "; break;
4848      }
4849      break;
4850    case AOK_Emit:
4851      OS << ".byte";
4852      break;
4853    case AOK_Align: {
4854      // MS alignment directives are measured in bytes. If the native assembler
4855      // measures alignment in bytes, we can pass it straight through.
4856      OS << ".align";
4857      if (getContext().getAsmInfo()->getAlignmentIsInBytes())
4858        break;
4859
4860      // Alignment is in log2 form, so print that instead and skip the original
4861      // immediate.
4862      unsigned Val = AR.Val;
4863      OS << ' ' << Val;
4864      assert(Val < 10 && "Expected alignment less then 2^10.");
4865      AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4866      break;
4867    }
4868    case AOK_EVEN:
4869      OS << ".even";
4870      break;
4871    case AOK_DotOperator:
4872      // Insert the dot if the user omitted it.
4873      OS.flush();
4874      if (AsmStringIR.back() != '.')
4875        OS << '.';
4876      OS << AR.Val;
4877      break;
4878    }
4879
4880    // Skip the original expression.
4881    AsmStart = Loc + AR.Len + AdditionalSkip;
4882  }
4883
4884  // Emit the remainder of the asm string.
4885  if (AsmStart != AsmEnd)
4886    OS << StringRef(AsmStart, AsmEnd - AsmStart);
4887
4888  AsmString = OS.str();
4889  return false;
4890}
4891
4892namespace llvm {
4893namespace MCParserUtils {
4894
4895/// Returns whether the given symbol is used anywhere in the given expression,
4896/// or subexpressions.
4897static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
4898  switch (Value->getKind()) {
4899  case MCExpr::Binary: {
4900    const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
4901    return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
4902           isSymbolUsedInExpression(Sym, BE->getRHS());
4903  }
4904  case MCExpr::Target:
4905  case MCExpr::Constant:
4906    return false;
4907  case MCExpr::SymbolRef: {
4908    const MCSymbol &S =
4909        static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
4910    if (S.isVariable())
4911      return isSymbolUsedInExpression(Sym, S.getVariableValue());
4912    return &S == Sym;
4913  }
4914  case MCExpr::Unary:
4915    return isSymbolUsedInExpression(
4916        Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
4917  }
4918
4919  llvm_unreachable("Unknown expr kind!");
4920}
4921
4922bool parseAssignmentExpression(StringRef Name, bool allow_redef,
4923                               MCAsmParser &Parser, MCSymbol *&Sym,
4924                               const MCExpr *&Value) {
4925  MCAsmLexer &Lexer = Parser.getLexer();
4926
4927  // FIXME: Use better location, we should use proper tokens.
4928  SMLoc EqualLoc = Lexer.getLoc();
4929
4930  if (Parser.parseExpression(Value)) {
4931    Parser.TokError("missing expression");
4932    Parser.eatToEndOfStatement();
4933    return true;
4934  }
4935
4936  // Note: we don't count b as used in "a = b". This is to allow
4937  // a = b
4938  // b = c
4939
4940  if (Lexer.isNot(AsmToken::EndOfStatement))
4941    return Parser.TokError("unexpected token in assignment");
4942
4943  // Eat the end of statement marker.
4944  Parser.Lex();
4945
4946  // Validate that the LHS is allowed to be a variable (either it has not been
4947  // used as a symbol, or it is an absolute symbol).
4948  Sym = Parser.getContext().lookupSymbol(Name);
4949  if (Sym) {
4950    // Diagnose assignment to a label.
4951    //
4952    // FIXME: Diagnostics. Note the location of the definition as a label.
4953    // FIXME: Diagnose assignment to protected identifier (e.g., register name).
4954    if (isSymbolUsedInExpression(Sym, Value))
4955      return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
4956    else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
4957             !Sym->isVariable())
4958      ; // Allow redefinitions of undefined symbols only used in directives.
4959    else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
4960      ; // Allow redefinitions of variables that haven't yet been used.
4961    else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
4962      return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
4963    else if (!Sym->isVariable())
4964      return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
4965    else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
4966      return Parser.Error(EqualLoc,
4967                          "invalid reassignment of non-absolute variable '" +
4968                              Name + "'");
4969  } else if (Name == ".") {
4970    Parser.getStreamer().emitValueToOffset(Value, 0);
4971    return false;
4972  } else
4973    Sym = Parser.getContext().getOrCreateSymbol(Name);
4974
4975  Sym->setRedefinable(allow_redef);
4976
4977  return false;
4978}
4979
4980} // namespace MCParserUtils
4981} // namespace llvm
4982
4983/// \brief Create an MCAsmParser instance.
4984MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4985                                     MCStreamer &Out, const MCAsmInfo &MAI) {
4986  return new AsmParser(SM, C, Out, MAI);
4987}
4988