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