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