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