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