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