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