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