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   //
1501   // FIXME: gas seems to support '!' as an infix operator?
1502   case AsmToken::Pipe:
1503     Kind = MCBinaryExpr::Or;
1504     return 2;
1505   case AsmToken::Caret:
1506     Kind = MCBinaryExpr::Xor;
1507     return 2;
1508   case AsmToken::Amp:
1509     Kind = MCBinaryExpr::And;
1510     return 2;
1511 
1512   // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1513   case AsmToken::EqualEqual:
1514     Kind = MCBinaryExpr::EQ;
1515     return 3;
1516   case AsmToken::ExclaimEqual:
1517   case AsmToken::LessGreater:
1518     Kind = MCBinaryExpr::NE;
1519     return 3;
1520   case AsmToken::Less:
1521     Kind = MCBinaryExpr::LT;
1522     return 3;
1523   case AsmToken::LessEqual:
1524     Kind = MCBinaryExpr::LTE;
1525     return 3;
1526   case AsmToken::Greater:
1527     Kind = MCBinaryExpr::GT;
1528     return 3;
1529   case AsmToken::GreaterEqual:
1530     Kind = MCBinaryExpr::GTE;
1531     return 3;
1532 
1533   // Intermediate Precedence: <<, >>
1534   case AsmToken::LessLess:
1535     Kind = MCBinaryExpr::Shl;
1536     return 4;
1537   case AsmToken::GreaterGreater:
1538     Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1539     return 4;
1540 
1541   // High Intermediate Precedence: +, -
1542   case AsmToken::Plus:
1543     Kind = MCBinaryExpr::Add;
1544     return 5;
1545   case AsmToken::Minus:
1546     Kind = MCBinaryExpr::Sub;
1547     return 5;
1548 
1549   // Highest Precedence: *, /, %
1550   case AsmToken::Star:
1551     Kind = MCBinaryExpr::Mul;
1552     return 6;
1553   case AsmToken::Slash:
1554     Kind = MCBinaryExpr::Div;
1555     return 6;
1556   case AsmToken::Percent:
1557     Kind = MCBinaryExpr::Mod;
1558     return 6;
1559   }
1560 }
1561 
1562 static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1563                                       MCBinaryExpr::Opcode &Kind,
1564                                       bool ShouldUseLogicalShr) {
1565   switch (K) {
1566   default:
1567     return 0; // not a binop.
1568 
1569   // Lowest Precedence: &&, ||
1570   case AsmToken::AmpAmp:
1571     Kind = MCBinaryExpr::LAnd;
1572     return 2;
1573   case AsmToken::PipePipe:
1574     Kind = MCBinaryExpr::LOr;
1575     return 1;
1576 
1577   // Low Precedence: ==, !=, <>, <, <=, >, >=
1578   case AsmToken::EqualEqual:
1579     Kind = MCBinaryExpr::EQ;
1580     return 3;
1581   case AsmToken::ExclaimEqual:
1582   case AsmToken::LessGreater:
1583     Kind = MCBinaryExpr::NE;
1584     return 3;
1585   case AsmToken::Less:
1586     Kind = MCBinaryExpr::LT;
1587     return 3;
1588   case AsmToken::LessEqual:
1589     Kind = MCBinaryExpr::LTE;
1590     return 3;
1591   case AsmToken::Greater:
1592     Kind = MCBinaryExpr::GT;
1593     return 3;
1594   case AsmToken::GreaterEqual:
1595     Kind = MCBinaryExpr::GTE;
1596     return 3;
1597 
1598   // Low Intermediate Precedence: +, -
1599   case AsmToken::Plus:
1600     Kind = MCBinaryExpr::Add;
1601     return 4;
1602   case AsmToken::Minus:
1603     Kind = MCBinaryExpr::Sub;
1604     return 4;
1605 
1606   // High Intermediate Precedence: |, &, ^
1607   //
1608   // FIXME: gas seems to support '!' as an infix operator?
1609   case AsmToken::Pipe:
1610     Kind = MCBinaryExpr::Or;
1611     return 5;
1612   case AsmToken::Caret:
1613     Kind = MCBinaryExpr::Xor;
1614     return 5;
1615   case AsmToken::Amp:
1616     Kind = MCBinaryExpr::And;
1617     return 5;
1618 
1619   // Highest Precedence: *, /, %, <<, >>
1620   case AsmToken::Star:
1621     Kind = MCBinaryExpr::Mul;
1622     return 6;
1623   case AsmToken::Slash:
1624     Kind = MCBinaryExpr::Div;
1625     return 6;
1626   case AsmToken::Percent:
1627     Kind = MCBinaryExpr::Mod;
1628     return 6;
1629   case AsmToken::LessLess:
1630     Kind = MCBinaryExpr::Shl;
1631     return 6;
1632   case AsmToken::GreaterGreater:
1633     Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1634     return 6;
1635   }
1636 }
1637 
1638 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1639                                        MCBinaryExpr::Opcode &Kind) {
1640   bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1641   return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1642                   : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1643 }
1644 
1645 /// Parse all binary operators with precedence >= 'Precedence'.
1646 /// Res contains the LHS of the expression on input.
1647 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1648                               SMLoc &EndLoc) {
1649   SMLoc StartLoc = Lexer.getLoc();
1650   while (true) {
1651     MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1652     unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1653 
1654     // If the next token is lower precedence than we are allowed to eat, return
1655     // successfully with what we ate already.
1656     if (TokPrec < Precedence)
1657       return false;
1658 
1659     Lex();
1660 
1661     // Eat the next primary expression.
1662     const MCExpr *RHS;
1663     if (getTargetParser().parsePrimaryExpr(RHS, EndLoc))
1664       return true;
1665 
1666     // If BinOp binds less tightly with RHS than the operator after RHS, let
1667     // the pending operator take RHS as its LHS.
1668     MCBinaryExpr::Opcode Dummy;
1669     unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1670     if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1671       return true;
1672 
1673     // Merge LHS and RHS according to operator.
1674     Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
1675   }
1676 }
1677 
1678 /// ParseStatement:
1679 ///   ::= EndOfStatement
1680 ///   ::= Label* Directive ...Operands... EndOfStatement
1681 ///   ::= Label* Identifier OperandList* EndOfStatement
1682 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1683                                MCAsmParserSemaCallback *SI) {
1684   assert(!hasPendingError() && "parseStatement started with pending error");
1685   // Eat initial spaces and comments
1686   while (Lexer.is(AsmToken::Space))
1687     Lex();
1688   if (Lexer.is(AsmToken::EndOfStatement)) {
1689     // if this is a line comment we can drop it safely
1690     if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
1691         getTok().getString().front() == '\n')
1692       Out.AddBlankLine();
1693     Lex();
1694     return false;
1695   }
1696   // Statements always start with an identifier.
1697   AsmToken ID = getTok();
1698   SMLoc IDLoc = ID.getLoc();
1699   StringRef IDVal;
1700   int64_t LocalLabelVal = -1;
1701   if (Lexer.is(AsmToken::HashDirective))
1702     return parseCppHashLineFilenameComment(IDLoc,
1703                                            !isInsideMacroInstantiation());
1704 
1705   // Allow an integer followed by a ':' as a directional local label.
1706   if (Lexer.is(AsmToken::Integer)) {
1707     LocalLabelVal = getTok().getIntVal();
1708     if (LocalLabelVal < 0) {
1709       if (!TheCondState.Ignore) {
1710         Lex(); // always eat a token
1711         return Error(IDLoc, "unexpected token at start of statement");
1712       }
1713       IDVal = "";
1714     } else {
1715       IDVal = getTok().getString();
1716       Lex(); // Consume the integer token to be used as an identifier token.
1717       if (Lexer.getKind() != AsmToken::Colon) {
1718         if (!TheCondState.Ignore) {
1719           Lex(); // always eat a token
1720           return Error(IDLoc, "unexpected token at start of statement");
1721         }
1722       }
1723     }
1724   } else if (Lexer.is(AsmToken::Dot)) {
1725     // Treat '.' as a valid identifier in this context.
1726     Lex();
1727     IDVal = ".";
1728   } else if (Lexer.is(AsmToken::LCurly)) {
1729     // Treat '{' as a valid identifier in this context.
1730     Lex();
1731     IDVal = "{";
1732 
1733   } else if (Lexer.is(AsmToken::RCurly)) {
1734     // Treat '}' as a valid identifier in this context.
1735     Lex();
1736     IDVal = "}";
1737   } else if (Lexer.is(AsmToken::Star) &&
1738              getTargetParser().starIsStartOfStatement()) {
1739     // Accept '*' as a valid start of statement.
1740     Lex();
1741     IDVal = "*";
1742   } else if (parseIdentifier(IDVal)) {
1743     if (!TheCondState.Ignore) {
1744       Lex(); // always eat a token
1745       return Error(IDLoc, "unexpected token at start of statement");
1746     }
1747     IDVal = "";
1748   }
1749 
1750   // Handle conditional assembly here before checking for skipping.  We
1751   // have to do this so that .endif isn't skipped in a ".if 0" block for
1752   // example.
1753   StringMap<DirectiveKind>::const_iterator DirKindIt =
1754       DirectiveKindMap.find(IDVal.lower());
1755   DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1756 
1757                               ? DK_NO_DIRECTIVE
1758                               : DirKindIt->getValue();
1759   switch (DirKind) {
1760   default:
1761     break;
1762   case DK_IF:
1763   case DK_IFEQ:
1764   case DK_IFGE:
1765   case DK_IFGT:
1766   case DK_IFLE:
1767   case DK_IFLT:
1768   case DK_IFNE:
1769     return parseDirectiveIf(IDLoc, DirKind);
1770   case DK_IFB:
1771     return parseDirectiveIfb(IDLoc, true);
1772   case DK_IFNB:
1773     return parseDirectiveIfb(IDLoc, false);
1774   case DK_IFC:
1775     return parseDirectiveIfc(IDLoc, true);
1776   case DK_IFEQS:
1777     return parseDirectiveIfeqs(IDLoc, true);
1778   case DK_IFNC:
1779     return parseDirectiveIfc(IDLoc, false);
1780   case DK_IFNES:
1781     return parseDirectiveIfeqs(IDLoc, false);
1782   case DK_IFDEF:
1783     return parseDirectiveIfdef(IDLoc, true);
1784   case DK_IFNDEF:
1785   case DK_IFNOTDEF:
1786     return parseDirectiveIfdef(IDLoc, false);
1787   case DK_ELSEIF:
1788     return parseDirectiveElseIf(IDLoc);
1789   case DK_ELSE:
1790     return parseDirectiveElse(IDLoc);
1791   case DK_ENDIF:
1792     return parseDirectiveEndIf(IDLoc);
1793   }
1794 
1795   // Ignore the statement if in the middle of inactive conditional
1796   // (e.g. ".if 0").
1797   if (TheCondState.Ignore) {
1798     eatToEndOfStatement();
1799     return false;
1800   }
1801 
1802   // FIXME: Recurse on local labels?
1803 
1804   // See what kind of statement we have.
1805   switch (Lexer.getKind()) {
1806   case AsmToken::Colon: {
1807     if (!getTargetParser().isLabel(ID))
1808       break;
1809     if (checkForValidSection())
1810       return true;
1811 
1812     // identifier ':'   -> Label.
1813     Lex();
1814 
1815     // Diagnose attempt to use '.' as a label.
1816     if (IDVal == ".")
1817       return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1818 
1819     // Diagnose attempt to use a variable as a label.
1820     //
1821     // FIXME: Diagnostics. Note the location of the definition as a label.
1822     // FIXME: This doesn't diagnose assignment to a symbol which has been
1823     // implicitly marked as external.
1824     MCSymbol *Sym;
1825     if (LocalLabelVal == -1) {
1826       if (ParsingMSInlineAsm && SI) {
1827         StringRef RewrittenLabel =
1828             SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1829         assert(!RewrittenLabel.empty() &&
1830                "We should have an internal name here.");
1831         Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1832                                        RewrittenLabel);
1833         IDVal = RewrittenLabel;
1834       }
1835       Sym = getContext().getOrCreateSymbol(IDVal);
1836     } else
1837       Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1838     // End of Labels should be treated as end of line for lexing
1839     // purposes but that information is not available to the Lexer who
1840     // does not understand Labels. This may cause us to see a Hash
1841     // here instead of a preprocessor line comment.
1842     if (getTok().is(AsmToken::Hash)) {
1843       StringRef CommentStr = parseStringToEndOfStatement();
1844       Lexer.Lex();
1845       Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1846     }
1847 
1848     // Consume any end of statement token, if present, to avoid spurious
1849     // AddBlankLine calls().
1850     if (getTok().is(AsmToken::EndOfStatement)) {
1851       Lex();
1852     }
1853 
1854     getTargetParser().doBeforeLabelEmit(Sym);
1855 
1856     // Emit the label.
1857     if (!getTargetParser().isParsingMSInlineAsm())
1858       Out.emitLabel(Sym, IDLoc);
1859 
1860     // If we are generating dwarf for assembly source files then gather the
1861     // info to make a dwarf label entry for this label if needed.
1862     if (enabledGenDwarfForAssembly())
1863       MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1864                                  IDLoc);
1865 
1866     getTargetParser().onLabelParsed(Sym);
1867 
1868     return false;
1869   }
1870 
1871   case AsmToken::Equal:
1872     if (!getTargetParser().equalIsAsmAssignment())
1873       break;
1874     // identifier '=' ... -> assignment statement
1875     Lex();
1876 
1877     return parseAssignment(IDVal, true);
1878 
1879   default: // Normal instruction or directive.
1880     break;
1881   }
1882 
1883   // If macros are enabled, check to see if this is a macro instantiation.
1884   if (areMacrosEnabled())
1885     if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) {
1886       return handleMacroEntry(M, IDLoc);
1887     }
1888 
1889   // Otherwise, we have a normal instruction or directive.
1890 
1891   // Directives start with "."
1892   if (IDVal.startswith(".") && IDVal != ".") {
1893     // There are several entities interested in parsing directives:
1894     //
1895     // 1. The target-specific assembly parser. Some directives are target
1896     //    specific or may potentially behave differently on certain targets.
1897     // 2. Asm parser extensions. For example, platform-specific parsers
1898     //    (like the ELF parser) register themselves as extensions.
1899     // 3. The generic directive parser implemented by this class. These are
1900     //    all the directives that behave in a target and platform independent
1901     //    manner, or at least have a default behavior that's shared between
1902     //    all targets and platforms.
1903 
1904     getTargetParser().flushPendingInstructions(getStreamer());
1905 
1906     SMLoc StartTokLoc = getTok().getLoc();
1907     bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1908 
1909     if (hasPendingError())
1910       return true;
1911     // Currently the return value should be true if we are
1912     // uninterested but as this is at odds with the standard parsing
1913     // convention (return true = error) we have instances of a parsed
1914     // directive that fails returning true as an error. Catch these
1915     // cases as best as possible errors here.
1916     if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1917       return true;
1918     // Return if we did some parsing or believe we succeeded.
1919     if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
1920       return false;
1921 
1922     // Next, check the extension directive map to see if any extension has
1923     // registered itself to parse this directive.
1924     std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1925         ExtensionDirectiveMap.lookup(IDVal);
1926     if (Handler.first)
1927       return (*Handler.second)(Handler.first, IDVal, IDLoc);
1928 
1929     // Finally, if no one else is interested in this directive, it must be
1930     // generic and familiar to this class.
1931     switch (DirKind) {
1932     default:
1933       break;
1934     case DK_SET:
1935     case DK_EQU:
1936       return parseDirectiveSet(IDVal, true);
1937     case DK_EQUIV:
1938       return parseDirectiveSet(IDVal, false);
1939     case DK_ASCII:
1940       return parseDirectiveAscii(IDVal, false);
1941     case DK_ASCIZ:
1942     case DK_STRING:
1943       return parseDirectiveAscii(IDVal, true);
1944     case DK_BYTE:
1945     case DK_DC_B:
1946       return parseDirectiveValue(IDVal, 1);
1947     case DK_DC:
1948     case DK_DC_W:
1949     case DK_SHORT:
1950     case DK_VALUE:
1951     case DK_2BYTE:
1952       return parseDirectiveValue(IDVal, 2);
1953     case DK_LONG:
1954     case DK_INT:
1955     case DK_4BYTE:
1956     case DK_DC_L:
1957       return parseDirectiveValue(IDVal, 4);
1958     case DK_QUAD:
1959     case DK_8BYTE:
1960       return parseDirectiveValue(IDVal, 8);
1961     case DK_DC_A:
1962       return parseDirectiveValue(
1963           IDVal, getContext().getAsmInfo()->getCodePointerSize());
1964     case DK_OCTA:
1965       return parseDirectiveOctaValue(IDVal);
1966     case DK_SINGLE:
1967     case DK_FLOAT:
1968     case DK_DC_S:
1969       return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
1970     case DK_DOUBLE:
1971     case DK_DC_D:
1972       return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
1973     case DK_ALIGN: {
1974       bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1975       return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1976     }
1977     case DK_ALIGN32: {
1978       bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1979       return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1980     }
1981     case DK_BALIGN:
1982       return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1983     case DK_BALIGNW:
1984       return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1985     case DK_BALIGNL:
1986       return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1987     case DK_P2ALIGN:
1988       return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1989     case DK_P2ALIGNW:
1990       return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1991     case DK_P2ALIGNL:
1992       return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1993     case DK_ORG:
1994       return parseDirectiveOrg();
1995     case DK_FILL:
1996       return parseDirectiveFill();
1997     case DK_ZERO:
1998       return parseDirectiveZero();
1999     case DK_EXTERN:
2000       eatToEndOfStatement(); // .extern is the default, ignore it.
2001       return false;
2002     case DK_GLOBL:
2003     case DK_GLOBAL:
2004       return parseDirectiveSymbolAttribute(MCSA_Global);
2005     case DK_LAZY_REFERENCE:
2006       return parseDirectiveSymbolAttribute(MCSA_LazyReference);
2007     case DK_NO_DEAD_STRIP:
2008       return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
2009     case DK_SYMBOL_RESOLVER:
2010       return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
2011     case DK_PRIVATE_EXTERN:
2012       return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
2013     case DK_REFERENCE:
2014       return parseDirectiveSymbolAttribute(MCSA_Reference);
2015     case DK_WEAK_DEFINITION:
2016       return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
2017     case DK_WEAK_REFERENCE:
2018       return parseDirectiveSymbolAttribute(MCSA_WeakReference);
2019     case DK_WEAK_DEF_CAN_BE_HIDDEN:
2020       return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
2021     case DK_COLD:
2022       return parseDirectiveSymbolAttribute(MCSA_Cold);
2023     case DK_COMM:
2024     case DK_COMMON:
2025       return parseDirectiveComm(/*IsLocal=*/false);
2026     case DK_LCOMM:
2027       return parseDirectiveComm(/*IsLocal=*/true);
2028     case DK_ABORT:
2029       return parseDirectiveAbort();
2030     case DK_INCLUDE:
2031       return parseDirectiveInclude();
2032     case DK_INCBIN:
2033       return parseDirectiveIncbin();
2034     case DK_CODE16:
2035     case DK_CODE16GCC:
2036       return TokError(Twine(IDVal) +
2037                       " not currently supported for this target");
2038     case DK_REPT:
2039       return parseDirectiveRept(IDLoc, IDVal);
2040     case DK_IRP:
2041       return parseDirectiveIrp(IDLoc);
2042     case DK_IRPC:
2043       return parseDirectiveIrpc(IDLoc);
2044     case DK_ENDR:
2045       return parseDirectiveEndr(IDLoc);
2046     case DK_BUNDLE_ALIGN_MODE:
2047       return parseDirectiveBundleAlignMode();
2048     case DK_BUNDLE_LOCK:
2049       return parseDirectiveBundleLock();
2050     case DK_BUNDLE_UNLOCK:
2051       return parseDirectiveBundleUnlock();
2052     case DK_SLEB128:
2053       return parseDirectiveLEB128(true);
2054     case DK_ULEB128:
2055       return parseDirectiveLEB128(false);
2056     case DK_SPACE:
2057     case DK_SKIP:
2058       return parseDirectiveSpace(IDVal);
2059     case DK_FILE:
2060       return parseDirectiveFile(IDLoc);
2061     case DK_LINE:
2062       return parseDirectiveLine();
2063     case DK_LOC:
2064       return parseDirectiveLoc();
2065     case DK_STABS:
2066       return parseDirectiveStabs();
2067     case DK_CV_FILE:
2068       return parseDirectiveCVFile();
2069     case DK_CV_FUNC_ID:
2070       return parseDirectiveCVFuncId();
2071     case DK_CV_INLINE_SITE_ID:
2072       return parseDirectiveCVInlineSiteId();
2073     case DK_CV_LOC:
2074       return parseDirectiveCVLoc();
2075     case DK_CV_LINETABLE:
2076       return parseDirectiveCVLinetable();
2077     case DK_CV_INLINE_LINETABLE:
2078       return parseDirectiveCVInlineLinetable();
2079     case DK_CV_DEF_RANGE:
2080       return parseDirectiveCVDefRange();
2081     case DK_CV_STRING:
2082       return parseDirectiveCVString();
2083     case DK_CV_STRINGTABLE:
2084       return parseDirectiveCVStringTable();
2085     case DK_CV_FILECHECKSUMS:
2086       return parseDirectiveCVFileChecksums();
2087     case DK_CV_FILECHECKSUM_OFFSET:
2088       return parseDirectiveCVFileChecksumOffset();
2089     case DK_CV_FPO_DATA:
2090       return parseDirectiveCVFPOData();
2091     case DK_CFI_SECTIONS:
2092       return parseDirectiveCFISections();
2093     case DK_CFI_STARTPROC:
2094       return parseDirectiveCFIStartProc();
2095     case DK_CFI_ENDPROC:
2096       return parseDirectiveCFIEndProc();
2097     case DK_CFI_DEF_CFA:
2098       return parseDirectiveCFIDefCfa(IDLoc);
2099     case DK_CFI_DEF_CFA_OFFSET:
2100       return parseDirectiveCFIDefCfaOffset();
2101     case DK_CFI_ADJUST_CFA_OFFSET:
2102       return parseDirectiveCFIAdjustCfaOffset();
2103     case DK_CFI_DEF_CFA_REGISTER:
2104       return parseDirectiveCFIDefCfaRegister(IDLoc);
2105     case DK_CFI_OFFSET:
2106       return parseDirectiveCFIOffset(IDLoc);
2107     case DK_CFI_REL_OFFSET:
2108       return parseDirectiveCFIRelOffset(IDLoc);
2109     case DK_CFI_PERSONALITY:
2110       return parseDirectiveCFIPersonalityOrLsda(true);
2111     case DK_CFI_LSDA:
2112       return parseDirectiveCFIPersonalityOrLsda(false);
2113     case DK_CFI_REMEMBER_STATE:
2114       return parseDirectiveCFIRememberState();
2115     case DK_CFI_RESTORE_STATE:
2116       return parseDirectiveCFIRestoreState();
2117     case DK_CFI_SAME_VALUE:
2118       return parseDirectiveCFISameValue(IDLoc);
2119     case DK_CFI_RESTORE:
2120       return parseDirectiveCFIRestore(IDLoc);
2121     case DK_CFI_ESCAPE:
2122       return parseDirectiveCFIEscape();
2123     case DK_CFI_RETURN_COLUMN:
2124       return parseDirectiveCFIReturnColumn(IDLoc);
2125     case DK_CFI_SIGNAL_FRAME:
2126       return parseDirectiveCFISignalFrame();
2127     case DK_CFI_UNDEFINED:
2128       return parseDirectiveCFIUndefined(IDLoc);
2129     case DK_CFI_REGISTER:
2130       return parseDirectiveCFIRegister(IDLoc);
2131     case DK_CFI_WINDOW_SAVE:
2132       return parseDirectiveCFIWindowSave();
2133     case DK_MACROS_ON:
2134     case DK_MACROS_OFF:
2135       return parseDirectiveMacrosOnOff(IDVal);
2136     case DK_MACRO:
2137       return parseDirectiveMacro(IDLoc);
2138     case DK_ALTMACRO:
2139     case DK_NOALTMACRO:
2140       return parseDirectiveAltmacro(IDVal);
2141     case DK_EXITM:
2142       return parseDirectiveExitMacro(IDVal);
2143     case DK_ENDM:
2144     case DK_ENDMACRO:
2145       return parseDirectiveEndMacro(IDVal);
2146     case DK_PURGEM:
2147       return parseDirectivePurgeMacro(IDLoc);
2148     case DK_END:
2149       return parseDirectiveEnd(IDLoc);
2150     case DK_ERR:
2151       return parseDirectiveError(IDLoc, false);
2152     case DK_ERROR:
2153       return parseDirectiveError(IDLoc, true);
2154     case DK_WARNING:
2155       return parseDirectiveWarning(IDLoc);
2156     case DK_RELOC:
2157       return parseDirectiveReloc(IDLoc);
2158     case DK_DCB:
2159     case DK_DCB_W:
2160       return parseDirectiveDCB(IDVal, 2);
2161     case DK_DCB_B:
2162       return parseDirectiveDCB(IDVal, 1);
2163     case DK_DCB_D:
2164       return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
2165     case DK_DCB_L:
2166       return parseDirectiveDCB(IDVal, 4);
2167     case DK_DCB_S:
2168       return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
2169     case DK_DC_X:
2170     case DK_DCB_X:
2171       return TokError(Twine(IDVal) +
2172                       " not currently supported for this target");
2173     case DK_DS:
2174     case DK_DS_W:
2175       return parseDirectiveDS(IDVal, 2);
2176     case DK_DS_B:
2177       return parseDirectiveDS(IDVal, 1);
2178     case DK_DS_D:
2179       return parseDirectiveDS(IDVal, 8);
2180     case DK_DS_L:
2181     case DK_DS_S:
2182       return parseDirectiveDS(IDVal, 4);
2183     case DK_DS_P:
2184     case DK_DS_X:
2185       return parseDirectiveDS(IDVal, 12);
2186     case DK_PRINT:
2187       return parseDirectivePrint(IDLoc);
2188     case DK_ADDRSIG:
2189       return parseDirectiveAddrsig();
2190     case DK_ADDRSIG_SYM:
2191       return parseDirectiveAddrsigSym();
2192     }
2193 
2194     return Error(IDLoc, "unknown directive");
2195   }
2196 
2197   // __asm _emit or __asm __emit
2198   if (ParsingMSInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2199                              IDVal == "_EMIT" || IDVal == "__EMIT"))
2200     return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
2201 
2202   // __asm align
2203   if (ParsingMSInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
2204     return parseDirectiveMSAlign(IDLoc, Info);
2205 
2206   if (ParsingMSInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
2207     Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
2208   if (checkForValidSection())
2209     return true;
2210 
2211   // Canonicalize the opcode to lower case.
2212   std::string OpcodeStr = IDVal.lower();
2213   ParseInstructionInfo IInfo(Info.AsmRewrites);
2214   bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2215                                                           Info.ParsedOperands);
2216   Info.ParseError = ParseHadError;
2217 
2218   // Dump the parsed representation, if requested.
2219   if (getShowParsedOperands()) {
2220     SmallString<256> Str;
2221     raw_svector_ostream OS(Str);
2222     OS << "parsed instruction: [";
2223     for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
2224       if (i != 0)
2225         OS << ", ";
2226       Info.ParsedOperands[i]->print(OS);
2227     }
2228     OS << "]";
2229 
2230     printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
2231   }
2232 
2233   // Fail even if ParseInstruction erroneously returns false.
2234   if (hasPendingError() || ParseHadError)
2235     return true;
2236 
2237   // If we are generating dwarf for the current section then generate a .loc
2238   // directive for the instruction.
2239   if (!ParseHadError && enabledGenDwarfForAssembly() &&
2240       getContext().getGenDwarfSectionSyms().count(
2241           getStreamer().getCurrentSectionOnly())) {
2242     unsigned Line;
2243     if (ActiveMacros.empty())
2244       Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2245     else
2246       Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2247                                    ActiveMacros.front()->ExitBuffer);
2248 
2249     // If we previously parsed a cpp hash file line comment then make sure the
2250     // current Dwarf File is for the CppHashFilename if not then emit the
2251     // Dwarf File table for it and adjust the line number for the .loc.
2252     if (!CppHashInfo.Filename.empty()) {
2253       unsigned FileNumber = getStreamer().emitDwarfFileDirective(
2254           0, StringRef(), CppHashInfo.Filename);
2255       getContext().setGenDwarfFileNumber(FileNumber);
2256 
2257       unsigned CppHashLocLineNo =
2258         SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
2259       Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
2260     }
2261 
2262     getStreamer().emitDwarfLocDirective(
2263         getContext().getGenDwarfFileNumber(), Line, 0,
2264         DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2265         StringRef());
2266   }
2267 
2268   // If parsing succeeded, match the instruction.
2269   if (!ParseHadError) {
2270     uint64_t ErrorInfo;
2271     if (getTargetParser().MatchAndEmitInstruction(
2272             IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2273             getTargetParser().isParsingMSInlineAsm()))
2274       return true;
2275   }
2276   return false;
2277 }
2278 
2279 // Parse and erase curly braces marking block start/end
2280 bool
2281 AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2282   // Identify curly brace marking block start/end
2283   if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2284     return false;
2285 
2286   SMLoc StartLoc = Lexer.getLoc();
2287   Lex(); // Eat the brace
2288   if (Lexer.is(AsmToken::EndOfStatement))
2289     Lex(); // Eat EndOfStatement following the brace
2290 
2291   // Erase the block start/end brace from the output asm string
2292   AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2293                                                   StartLoc.getPointer());
2294   return true;
2295 }
2296 
2297 /// parseCppHashLineFilenameComment as this:
2298 ///   ::= # number "filename"
2299 bool AsmParser::parseCppHashLineFilenameComment(SMLoc L, bool SaveLocInfo) {
2300   Lex(); // Eat the hash token.
2301   // Lexer only ever emits HashDirective if it fully formed if it's
2302   // done the checking already so this is an internal error.
2303   assert(getTok().is(AsmToken::Integer) &&
2304          "Lexing Cpp line comment: Expected Integer");
2305   int64_t LineNumber = getTok().getIntVal();
2306   Lex();
2307   assert(getTok().is(AsmToken::String) &&
2308          "Lexing Cpp line comment: Expected String");
2309   StringRef Filename = getTok().getString();
2310   Lex();
2311 
2312   if (!SaveLocInfo)
2313     return false;
2314 
2315   // Get rid of the enclosing quotes.
2316   Filename = Filename.substr(1, Filename.size() - 2);
2317 
2318   // Save the SMLoc, Filename and LineNumber for later use by diagnostics
2319   // and possibly DWARF file info.
2320   CppHashInfo.Loc = L;
2321   CppHashInfo.Filename = Filename;
2322   CppHashInfo.LineNumber = LineNumber;
2323   CppHashInfo.Buf = CurBuffer;
2324   if (FirstCppHashFilename.empty())
2325     FirstCppHashFilename = Filename;
2326   return false;
2327 }
2328 
2329 /// will use the last parsed cpp hash line filename comment
2330 /// for the Filename and LineNo if any in the diagnostic.
2331 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
2332   const AsmParser *Parser = static_cast<const AsmParser *>(Context);
2333   raw_ostream &OS = errs();
2334 
2335   const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
2336   SMLoc DiagLoc = Diag.getLoc();
2337   unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2338   unsigned CppHashBuf =
2339       Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
2340 
2341   // Like SourceMgr::printMessage() we need to print the include stack if any
2342   // before printing the message.
2343   unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2344   if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2345       DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
2346     SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2347     DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
2348   }
2349 
2350   // If we have not parsed a cpp hash line filename comment or the source
2351   // manager changed or buffer changed (like in a nested include) then just
2352   // print the normal diagnostic using its Filename and LineNo.
2353   if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
2354       DiagBuf != CppHashBuf) {
2355     if (Parser->SavedDiagHandler)
2356       Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2357     else
2358       Diag.print(nullptr, OS);
2359     return;
2360   }
2361 
2362   // Use the CppHashFilename and calculate a line number based on the
2363   // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2364   // for the diagnostic.
2365   const std::string &Filename = std::string(Parser->CppHashInfo.Filename);
2366 
2367   int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2368   int CppHashLocLineNo =
2369       Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
2370   int LineNo =
2371       Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
2372 
2373   SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2374                        Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
2375                        Diag.getLineContents(), Diag.getRanges());
2376 
2377   if (Parser->SavedDiagHandler)
2378     Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2379   else
2380     NewDiag.print(nullptr, OS);
2381 }
2382 
2383 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2384 // difference being that that function accepts '@' as part of identifiers and
2385 // we can't do that. AsmLexer.cpp should probably be changed to handle
2386 // '@' as a special case when needed.
2387 static bool isIdentifierChar(char c) {
2388   return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2389          c == '.';
2390 }
2391 
2392 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
2393                             ArrayRef<MCAsmMacroParameter> Parameters,
2394                             ArrayRef<MCAsmMacroArgument> A,
2395                             bool EnableAtPseudoVariable, SMLoc L) {
2396   unsigned NParameters = Parameters.size();
2397   bool HasVararg = NParameters ? Parameters.back().Vararg : false;
2398   if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
2399     return Error(L, "Wrong number of arguments");
2400 
2401   // A macro without parameters is handled differently on Darwin:
2402   // gas accepts no arguments and does no substitutions
2403   while (!Body.empty()) {
2404     // Scan for the next substitution.
2405     std::size_t End = Body.size(), Pos = 0;
2406     for (; Pos != End; ++Pos) {
2407       // Check for a substitution or escape.
2408       if (IsDarwin && !NParameters) {
2409         // This macro has no parameters, look for $0, $1, etc.
2410         if (Body[Pos] != '$' || Pos + 1 == End)
2411           continue;
2412 
2413         char Next = Body[Pos + 1];
2414         if (Next == '$' || Next == 'n' ||
2415             isdigit(static_cast<unsigned char>(Next)))
2416           break;
2417       } else {
2418         // This macro has parameters, look for \foo, \bar, etc.
2419         if (Body[Pos] == '\\' && Pos + 1 != End)
2420           break;
2421       }
2422     }
2423 
2424     // Add the prefix.
2425     OS << Body.slice(0, Pos);
2426 
2427     // Check if we reached the end.
2428     if (Pos == End)
2429       break;
2430 
2431     if (IsDarwin && !NParameters) {
2432       switch (Body[Pos + 1]) {
2433       // $$ => $
2434       case '$':
2435         OS << '$';
2436         break;
2437 
2438       // $n => number of arguments
2439       case 'n':
2440         OS << A.size();
2441         break;
2442 
2443       // $[0-9] => argument
2444       default: {
2445         // Missing arguments are ignored.
2446         unsigned Index = Body[Pos + 1] - '0';
2447         if (Index >= A.size())
2448           break;
2449 
2450         // Otherwise substitute with the token values, with spaces eliminated.
2451         for (const AsmToken &Token : A[Index])
2452           OS << Token.getString();
2453         break;
2454       }
2455       }
2456       Pos += 2;
2457     } else {
2458       unsigned I = Pos + 1;
2459 
2460       // Check for the \@ pseudo-variable.
2461       if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
2462         ++I;
2463       else
2464         while (isIdentifierChar(Body[I]) && I + 1 != End)
2465           ++I;
2466 
2467       const char *Begin = Body.data() + Pos + 1;
2468       StringRef Argument(Begin, I - (Pos + 1));
2469       unsigned Index = 0;
2470 
2471       if (Argument == "@") {
2472         OS << NumOfMacroInstantiations;
2473         Pos += 2;
2474       } else {
2475         for (; Index < NParameters; ++Index)
2476           if (Parameters[Index].Name == Argument)
2477             break;
2478 
2479         if (Index == NParameters) {
2480           if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2481             Pos += 3;
2482           else {
2483             OS << '\\' << Argument;
2484             Pos = I;
2485           }
2486         } else {
2487           bool VarargParameter = HasVararg && Index == (NParameters - 1);
2488           for (const AsmToken &Token : A[Index])
2489             // For altmacro mode, you can write '%expr'.
2490             // The prefix '%' evaluates the expression 'expr'
2491             // and uses the result as a string (e.g. replace %(1+2) with the
2492             // string "3").
2493             // Here, we identify the integer token which is the result of the
2494             // absolute expression evaluation and replace it with its string
2495             // representation.
2496             if (AltMacroMode && Token.getString().front() == '%' &&
2497                 Token.is(AsmToken::Integer))
2498               // Emit an integer value to the buffer.
2499               OS << Token.getIntVal();
2500             // Only Token that was validated as a string and begins with '<'
2501             // is considered altMacroString!!!
2502             else if (AltMacroMode && Token.getString().front() == '<' &&
2503                      Token.is(AsmToken::String)) {
2504               OS << angleBracketString(Token.getStringContents());
2505             }
2506             // We expect no quotes around the string's contents when
2507             // parsing for varargs.
2508             else if (Token.isNot(AsmToken::String) || VarargParameter)
2509               OS << Token.getString();
2510             else
2511               OS << Token.getStringContents();
2512 
2513           Pos += 1 + Argument.size();
2514         }
2515       }
2516     }
2517     // Update the scan point.
2518     Body = Body.substr(Pos);
2519   }
2520 
2521   return false;
2522 }
2523 
2524 static bool isOperator(AsmToken::TokenKind kind) {
2525   switch (kind) {
2526   default:
2527     return false;
2528   case AsmToken::Plus:
2529   case AsmToken::Minus:
2530   case AsmToken::Tilde:
2531   case AsmToken::Slash:
2532   case AsmToken::Star:
2533   case AsmToken::Dot:
2534   case AsmToken::Equal:
2535   case AsmToken::EqualEqual:
2536   case AsmToken::Pipe:
2537   case AsmToken::PipePipe:
2538   case AsmToken::Caret:
2539   case AsmToken::Amp:
2540   case AsmToken::AmpAmp:
2541   case AsmToken::Exclaim:
2542   case AsmToken::ExclaimEqual:
2543   case AsmToken::Less:
2544   case AsmToken::LessEqual:
2545   case AsmToken::LessLess:
2546   case AsmToken::LessGreater:
2547   case AsmToken::Greater:
2548   case AsmToken::GreaterEqual:
2549   case AsmToken::GreaterGreater:
2550     return true;
2551   }
2552 }
2553 
2554 namespace {
2555 
2556 class AsmLexerSkipSpaceRAII {
2557 public:
2558   AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2559     Lexer.setSkipSpace(SkipSpace);
2560   }
2561 
2562   ~AsmLexerSkipSpaceRAII() {
2563     Lexer.setSkipSpace(true);
2564   }
2565 
2566 private:
2567   AsmLexer &Lexer;
2568 };
2569 
2570 } // end anonymous namespace
2571 
2572 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2573 
2574   if (Vararg) {
2575     if (Lexer.isNot(AsmToken::EndOfStatement)) {
2576       StringRef Str = parseStringToEndOfStatement();
2577       MA.emplace_back(AsmToken::String, Str);
2578     }
2579     return false;
2580   }
2581 
2582   unsigned ParenLevel = 0;
2583 
2584   // Darwin doesn't use spaces to delmit arguments.
2585   AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
2586 
2587   bool SpaceEaten;
2588 
2589   while (true) {
2590     SpaceEaten = false;
2591     if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
2592       return TokError("unexpected token in macro instantiation");
2593 
2594     if (ParenLevel == 0) {
2595 
2596       if (Lexer.is(AsmToken::Comma))
2597         break;
2598 
2599       if (Lexer.is(AsmToken::Space)) {
2600         SpaceEaten = true;
2601         Lexer.Lex(); // Eat spaces
2602       }
2603 
2604       // Spaces can delimit parameters, but could also be part an expression.
2605       // If the token after a space is an operator, add the token and the next
2606       // one into this argument
2607       if (!IsDarwin) {
2608         if (isOperator(Lexer.getKind())) {
2609           MA.push_back(getTok());
2610           Lexer.Lex();
2611 
2612           // Whitespace after an operator can be ignored.
2613           if (Lexer.is(AsmToken::Space))
2614             Lexer.Lex();
2615 
2616           continue;
2617         }
2618       }
2619       if (SpaceEaten)
2620         break;
2621     }
2622 
2623     // handleMacroEntry relies on not advancing the lexer here
2624     // to be able to fill in the remaining default parameter values
2625     if (Lexer.is(AsmToken::EndOfStatement))
2626       break;
2627 
2628     // Adjust the current parentheses level.
2629     if (Lexer.is(AsmToken::LParen))
2630       ++ParenLevel;
2631     else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2632       --ParenLevel;
2633 
2634     // Append the token to the current argument list.
2635     MA.push_back(getTok());
2636     Lexer.Lex();
2637   }
2638 
2639   if (ParenLevel != 0)
2640     return TokError("unbalanced parentheses in macro argument");
2641   return false;
2642 }
2643 
2644 // Parse the macro instantiation arguments.
2645 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2646                                     MCAsmMacroArguments &A) {
2647   const unsigned NParameters = M ? M->Parameters.size() : 0;
2648   bool NamedParametersFound = false;
2649   SmallVector<SMLoc, 4> FALocs;
2650 
2651   A.resize(NParameters);
2652   FALocs.resize(NParameters);
2653 
2654   // Parse two kinds of macro invocations:
2655   // - macros defined without any parameters accept an arbitrary number of them
2656   // - macros defined with parameters accept at most that many of them
2657   bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2658   for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2659        ++Parameter) {
2660     SMLoc IDLoc = Lexer.getLoc();
2661     MCAsmMacroParameter FA;
2662 
2663     if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2664       if (parseIdentifier(FA.Name))
2665         return Error(IDLoc, "invalid argument identifier for formal argument");
2666 
2667       if (Lexer.isNot(AsmToken::Equal))
2668         return TokError("expected '=' after formal parameter identifier");
2669 
2670       Lex();
2671 
2672       NamedParametersFound = true;
2673     }
2674     bool Vararg = HasVararg && Parameter == (NParameters - 1);
2675 
2676     if (NamedParametersFound && FA.Name.empty())
2677       return Error(IDLoc, "cannot mix positional and keyword arguments");
2678 
2679     SMLoc StrLoc = Lexer.getLoc();
2680     SMLoc EndLoc;
2681     if (AltMacroMode && Lexer.is(AsmToken::Percent)) {
2682       const MCExpr *AbsoluteExp;
2683       int64_t Value;
2684       /// Eat '%'
2685       Lex();
2686       if (parseExpression(AbsoluteExp, EndLoc))
2687         return false;
2688       if (!AbsoluteExp->evaluateAsAbsolute(Value,
2689                                            getStreamer().getAssemblerPtr()))
2690         return Error(StrLoc, "expected absolute expression");
2691       const char *StrChar = StrLoc.getPointer();
2692       const char *EndChar = EndLoc.getPointer();
2693       AsmToken newToken(AsmToken::Integer,
2694                         StringRef(StrChar, EndChar - StrChar), Value);
2695       FA.Value.push_back(newToken);
2696     } else if (AltMacroMode && Lexer.is(AsmToken::Less) &&
2697                isAngleBracketString(StrLoc, EndLoc)) {
2698       const char *StrChar = StrLoc.getPointer();
2699       const char *EndChar = EndLoc.getPointer();
2700       jumpToLoc(EndLoc, CurBuffer);
2701       /// Eat from '<' to '>'
2702       Lex();
2703       AsmToken newToken(AsmToken::String,
2704                         StringRef(StrChar, EndChar - StrChar));
2705       FA.Value.push_back(newToken);
2706     } else if(parseMacroArgument(FA.Value, Vararg))
2707       return true;
2708 
2709     unsigned PI = Parameter;
2710     if (!FA.Name.empty()) {
2711       unsigned FAI = 0;
2712       for (FAI = 0; FAI < NParameters; ++FAI)
2713         if (M->Parameters[FAI].Name == FA.Name)
2714           break;
2715 
2716       if (FAI >= NParameters) {
2717         assert(M && "expected macro to be defined");
2718         return Error(IDLoc, "parameter named '" + FA.Name +
2719                                 "' does not exist for macro '" + M->Name + "'");
2720       }
2721       PI = FAI;
2722     }
2723 
2724     if (!FA.Value.empty()) {
2725       if (A.size() <= PI)
2726         A.resize(PI + 1);
2727       A[PI] = FA.Value;
2728 
2729       if (FALocs.size() <= PI)
2730         FALocs.resize(PI + 1);
2731 
2732       FALocs[PI] = Lexer.getLoc();
2733     }
2734 
2735     // At the end of the statement, fill in remaining arguments that have
2736     // default values. If there aren't any, then the next argument is
2737     // required but missing
2738     if (Lexer.is(AsmToken::EndOfStatement)) {
2739       bool Failure = false;
2740       for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2741         if (A[FAI].empty()) {
2742           if (M->Parameters[FAI].Required) {
2743             Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2744                   "missing value for required parameter "
2745                   "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2746             Failure = true;
2747           }
2748 
2749           if (!M->Parameters[FAI].Value.empty())
2750             A[FAI] = M->Parameters[FAI].Value;
2751         }
2752       }
2753       return Failure;
2754     }
2755 
2756     if (Lexer.is(AsmToken::Comma))
2757       Lex();
2758   }
2759 
2760   return TokError("too many positional arguments");
2761 }
2762 
2763 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2764   // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2765   // eliminate this, although we should protect against infinite loops.
2766   unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2767   if (ActiveMacros.size() == MaxNestingDepth) {
2768     std::ostringstream MaxNestingDepthError;
2769     MaxNestingDepthError << "macros cannot be nested more than "
2770                          << MaxNestingDepth << " levels deep."
2771                          << " Use -asm-macro-max-nesting-depth to increase "
2772                             "this limit.";
2773     return TokError(MaxNestingDepthError.str());
2774   }
2775 
2776   MCAsmMacroArguments A;
2777   if (parseMacroArguments(M, A))
2778     return true;
2779 
2780   // Macro instantiation is lexical, unfortunately. We construct a new buffer
2781   // to hold the macro body with substitutions.
2782   SmallString<256> Buf;
2783   StringRef Body = M->Body;
2784   raw_svector_ostream OS(Buf);
2785 
2786   if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2787     return true;
2788 
2789   // We include the .endmacro in the buffer as our cue to exit the macro
2790   // instantiation.
2791   OS << ".endmacro\n";
2792 
2793   std::unique_ptr<MemoryBuffer> Instantiation =
2794       MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2795 
2796   // Create the macro instantiation object and add to the current macro
2797   // instantiation stack.
2798   MacroInstantiation *MI = new MacroInstantiation{
2799       NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size()};
2800   ActiveMacros.push_back(MI);
2801 
2802   ++NumOfMacroInstantiations;
2803 
2804   // Jump to the macro instantiation and prime the lexer.
2805   CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2806   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2807   Lex();
2808 
2809   return false;
2810 }
2811 
2812 void AsmParser::handleMacroExit() {
2813   // Jump to the EndOfStatement we should return to, and consume it.
2814   jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2815   Lex();
2816 
2817   // Pop the instantiation entry.
2818   delete ActiveMacros.back();
2819   ActiveMacros.pop_back();
2820 }
2821 
2822 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2823                                 bool NoDeadStrip) {
2824   MCSymbol *Sym;
2825   const MCExpr *Value;
2826   if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2827                                                Value))
2828     return true;
2829 
2830   if (!Sym) {
2831     // In the case where we parse an expression starting with a '.', we will
2832     // not generate an error, nor will we create a symbol.  In this case we
2833     // should just return out.
2834     return false;
2835   }
2836 
2837   // Do the assignment.
2838   Out.emitAssignment(Sym, Value);
2839   if (NoDeadStrip)
2840     Out.emitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2841 
2842   return false;
2843 }
2844 
2845 /// parseIdentifier:
2846 ///   ::= identifier
2847 ///   ::= string
2848 bool AsmParser::parseIdentifier(StringRef &Res) {
2849   // The assembler has relaxed rules for accepting identifiers, in particular we
2850   // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2851   // separate tokens. At this level, we have already lexed so we cannot (currently)
2852   // handle this as a context dependent token, instead we detect adjacent tokens
2853   // and return the combined identifier.
2854   if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2855     SMLoc PrefixLoc = getLexer().getLoc();
2856 
2857     // Consume the prefix character, and check for a following identifier.
2858 
2859     AsmToken Buf[1];
2860     Lexer.peekTokens(Buf, false);
2861 
2862     if (Buf[0].isNot(AsmToken::Identifier) && Buf[0].isNot(AsmToken::Integer))
2863       return true;
2864 
2865     // We have a '$' or '@' followed by an identifier or integer token, make
2866     // sure they are adjacent.
2867     if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
2868       return true;
2869 
2870     // eat $ or @
2871     Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
2872     // Construct the joined identifier and consume the token.
2873     Res = StringRef(PrefixLoc.getPointer(), getTok().getString().size() + 1);
2874     Lex(); // Parser Lex to maintain invariants.
2875     return false;
2876   }
2877 
2878   if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2879     return true;
2880 
2881   Res = getTok().getIdentifier();
2882 
2883   Lex(); // Consume the identifier token.
2884 
2885   return false;
2886 }
2887 
2888 /// parseDirectiveSet:
2889 ///   ::= .equ identifier ',' expression
2890 ///   ::= .equiv identifier ',' expression
2891 ///   ::= .set identifier ',' expression
2892 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2893   StringRef Name;
2894   if (check(parseIdentifier(Name), "expected identifier") ||
2895       parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2896     return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2897   return false;
2898 }
2899 
2900 bool AsmParser::parseEscapedString(std::string &Data) {
2901   if (check(getTok().isNot(AsmToken::String), "expected string"))
2902     return true;
2903 
2904   Data = "";
2905   StringRef Str = getTok().getStringContents();
2906   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2907     if (Str[i] != '\\') {
2908       Data += Str[i];
2909       continue;
2910     }
2911 
2912     // Recognize escaped characters. Note that this escape semantics currently
2913     // loosely follows Darwin 'as'.
2914     ++i;
2915     if (i == e)
2916       return TokError("unexpected backslash at end of string");
2917 
2918     // Recognize hex sequences similarly to GNU 'as'.
2919     if (Str[i] == 'x' || Str[i] == 'X') {
2920       size_t length = Str.size();
2921       if (i + 1 >= length || !isHexDigit(Str[i + 1]))
2922         return TokError("invalid hexadecimal escape sequence");
2923 
2924       // Consume hex characters. GNU 'as' reads all hexadecimal characters and
2925       // then truncates to the lower 16 bits. Seems reasonable.
2926       unsigned Value = 0;
2927       while (i + 1 < length && isHexDigit(Str[i + 1]))
2928         Value = Value * 16 + hexDigitValue(Str[++i]);
2929 
2930       Data += (unsigned char)(Value & 0xFF);
2931       continue;
2932     }
2933 
2934     // Recognize octal sequences.
2935     if ((unsigned)(Str[i] - '0') <= 7) {
2936       // Consume up to three octal characters.
2937       unsigned Value = Str[i] - '0';
2938 
2939       if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2940         ++i;
2941         Value = Value * 8 + (Str[i] - '0');
2942 
2943         if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2944           ++i;
2945           Value = Value * 8 + (Str[i] - '0');
2946         }
2947       }
2948 
2949       if (Value > 255)
2950         return TokError("invalid octal escape sequence (out of range)");
2951 
2952       Data += (unsigned char)Value;
2953       continue;
2954     }
2955 
2956     // Otherwise recognize individual escapes.
2957     switch (Str[i]) {
2958     default:
2959       // Just reject invalid escape sequences for now.
2960       return TokError("invalid escape sequence (unrecognized character)");
2961 
2962     case 'b': Data += '\b'; break;
2963     case 'f': Data += '\f'; break;
2964     case 'n': Data += '\n'; break;
2965     case 'r': Data += '\r'; break;
2966     case 't': Data += '\t'; break;
2967     case '"': Data += '"'; break;
2968     case '\\': Data += '\\'; break;
2969     }
2970   }
2971 
2972   Lex();
2973   return false;
2974 }
2975 
2976 bool AsmParser::parseAngleBracketString(std::string &Data) {
2977   SMLoc EndLoc, StartLoc = getTok().getLoc();
2978   if (isAngleBracketString(StartLoc, EndLoc)) {
2979     const char *StartChar = StartLoc.getPointer() + 1;
2980     const char *EndChar = EndLoc.getPointer() - 1;
2981     jumpToLoc(EndLoc, CurBuffer);
2982     /// Eat from '<' to '>'
2983     Lex();
2984 
2985     Data = angleBracketString(StringRef(StartChar, EndChar - StartChar));
2986     return false;
2987   }
2988   return true;
2989 }
2990 
2991 /// parseDirectiveAscii:
2992 ///   ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2993 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2994   auto parseOp = [&]() -> bool {
2995     std::string Data;
2996     if (checkForValidSection() || parseEscapedString(Data))
2997       return true;
2998     getStreamer().emitBytes(Data);
2999     if (ZeroTerminated)
3000       getStreamer().emitBytes(StringRef("\0", 1));
3001     return false;
3002   };
3003 
3004   if (parseMany(parseOp))
3005     return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
3006   return false;
3007 }
3008 
3009 /// parseDirectiveReloc
3010 ///  ::= .reloc expression , identifier [ , expression ]
3011 bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
3012   const MCExpr *Offset;
3013   const MCExpr *Expr = nullptr;
3014   int64_t OffsetValue;
3015   SMLoc OffsetLoc = Lexer.getTok().getLoc();
3016 
3017   if (parseExpression(Offset))
3018     return true;
3019 
3020   if ((Offset->evaluateAsAbsolute(OffsetValue,
3021                                   getStreamer().getAssemblerPtr()) &&
3022        check(OffsetValue < 0, OffsetLoc, "expression is negative")) ||
3023       (check(Offset->getKind() != llvm::MCExpr::Constant &&
3024              Offset->getKind() != llvm::MCExpr::SymbolRef,
3025              OffsetLoc, "expected non-negative number or a label")) ||
3026       (parseToken(AsmToken::Comma, "expected comma") ||
3027        check(getTok().isNot(AsmToken::Identifier), "expected relocation name")))
3028     return true;
3029 
3030   SMLoc NameLoc = Lexer.getTok().getLoc();
3031   StringRef Name = Lexer.getTok().getIdentifier();
3032   Lex();
3033 
3034   if (Lexer.is(AsmToken::Comma)) {
3035     Lex();
3036     SMLoc ExprLoc = Lexer.getLoc();
3037     if (parseExpression(Expr))
3038       return true;
3039 
3040     MCValue Value;
3041     if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
3042       return Error(ExprLoc, "expression must be relocatable");
3043   }
3044 
3045   if (parseToken(AsmToken::EndOfStatement,
3046                  "unexpected token in .reloc directive"))
3047       return true;
3048 
3049   const MCTargetAsmParser &MCT = getTargetParser();
3050   const MCSubtargetInfo &STI = MCT.getSTI();
3051   if (getStreamer().emitRelocDirective(*Offset, Name, Expr, DirectiveLoc, STI))
3052     return Error(NameLoc, "unknown relocation name");
3053 
3054   return false;
3055 }
3056 
3057 /// parseDirectiveValue
3058 ///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
3059 bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
3060   auto parseOp = [&]() -> bool {
3061     const MCExpr *Value;
3062     SMLoc ExprLoc = getLexer().getLoc();
3063     if (checkForValidSection() || parseExpression(Value))
3064       return true;
3065     // Special case constant expressions to match code generator.
3066     if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3067       assert(Size <= 8 && "Invalid size");
3068       uint64_t IntValue = MCE->getValue();
3069       if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
3070         return Error(ExprLoc, "out of range literal value");
3071       getStreamer().emitIntValue(IntValue, Size);
3072     } else
3073       getStreamer().emitValue(Value, Size, ExprLoc);
3074     return false;
3075   };
3076 
3077   if (parseMany(parseOp))
3078     return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
3079   return false;
3080 }
3081 
3082 static bool parseHexOcta(AsmParser &Asm, uint64_t &hi, uint64_t &lo) {
3083   if (Asm.getTok().isNot(AsmToken::Integer) &&
3084       Asm.getTok().isNot(AsmToken::BigNum))
3085     return Asm.TokError("unknown token in expression");
3086   SMLoc ExprLoc = Asm.getTok().getLoc();
3087   APInt IntValue = Asm.getTok().getAPIntVal();
3088   Asm.Lex();
3089   if (!IntValue.isIntN(128))
3090     return Asm.Error(ExprLoc, "out of range literal value");
3091   if (!IntValue.isIntN(64)) {
3092     hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
3093     lo = IntValue.getLoBits(64).getZExtValue();
3094   } else {
3095     hi = 0;
3096     lo = IntValue.getZExtValue();
3097   }
3098   return false;
3099 }
3100 
3101 /// ParseDirectiveOctaValue
3102 ///  ::= .octa [ hexconstant (, hexconstant)* ]
3103 
3104 bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
3105   auto parseOp = [&]() -> bool {
3106     if (checkForValidSection())
3107       return true;
3108     uint64_t hi, lo;
3109     if (parseHexOcta(*this, hi, lo))
3110       return true;
3111     if (MAI.isLittleEndian()) {
3112       getStreamer().emitInt64(lo);
3113       getStreamer().emitInt64(hi);
3114     } else {
3115       getStreamer().emitInt64(hi);
3116       getStreamer().emitInt64(lo);
3117     }
3118     return false;
3119   };
3120 
3121   if (parseMany(parseOp))
3122     return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
3123   return false;
3124 }
3125 
3126 bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3127   // We don't truly support arithmetic on floating point expressions, so we
3128   // have to manually parse unary prefixes.
3129   bool IsNeg = false;
3130   if (getLexer().is(AsmToken::Minus)) {
3131     Lexer.Lex();
3132     IsNeg = true;
3133   } else if (getLexer().is(AsmToken::Plus))
3134     Lexer.Lex();
3135 
3136   if (Lexer.is(AsmToken::Error))
3137     return TokError(Lexer.getErr());
3138   if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3139       Lexer.isNot(AsmToken::Identifier))
3140     return TokError("unexpected token in directive");
3141 
3142   // Convert to an APFloat.
3143   APFloat Value(Semantics);
3144   StringRef IDVal = getTok().getString();
3145   if (getLexer().is(AsmToken::Identifier)) {
3146     if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
3147       Value = APFloat::getInf(Semantics);
3148     else if (!IDVal.compare_lower("nan"))
3149       Value = APFloat::getNaN(Semantics, false, ~0);
3150     else
3151       return TokError("invalid floating point literal");
3152   } else if (errorToBool(
3153                  Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven)
3154                      .takeError()))
3155     return TokError("invalid floating point literal");
3156   if (IsNeg)
3157     Value.changeSign();
3158 
3159   // Consume the numeric token.
3160   Lex();
3161 
3162   Res = Value.bitcastToAPInt();
3163 
3164   return false;
3165 }
3166 
3167 /// parseDirectiveRealValue
3168 ///  ::= (.single | .double) [ expression (, expression)* ]
3169 bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3170                                         const fltSemantics &Semantics) {
3171   auto parseOp = [&]() -> bool {
3172     APInt AsInt;
3173     if (checkForValidSection() || parseRealValue(Semantics, AsInt))
3174       return true;
3175     getStreamer().emitIntValue(AsInt.getLimitedValue(),
3176                                AsInt.getBitWidth() / 8);
3177     return false;
3178   };
3179 
3180   if (parseMany(parseOp))
3181     return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
3182   return false;
3183 }
3184 
3185 /// parseDirectiveZero
3186 ///  ::= .zero expression
3187 bool AsmParser::parseDirectiveZero() {
3188   SMLoc NumBytesLoc = Lexer.getLoc();
3189   const MCExpr *NumBytes;
3190   if (checkForValidSection() || parseExpression(NumBytes))
3191     return true;
3192 
3193   int64_t Val = 0;
3194   if (getLexer().is(AsmToken::Comma)) {
3195     Lex();
3196     if (parseAbsoluteExpression(Val))
3197       return true;
3198   }
3199 
3200   if (parseToken(AsmToken::EndOfStatement,
3201                  "unexpected token in '.zero' directive"))
3202     return true;
3203   getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
3204 
3205   return false;
3206 }
3207 
3208 /// parseDirectiveFill
3209 ///  ::= .fill expression [ , expression [ , expression ] ]
3210 bool AsmParser::parseDirectiveFill() {
3211   SMLoc NumValuesLoc = Lexer.getLoc();
3212   const MCExpr *NumValues;
3213   if (checkForValidSection() || parseExpression(NumValues))
3214     return true;
3215 
3216   int64_t FillSize = 1;
3217   int64_t FillExpr = 0;
3218 
3219   SMLoc SizeLoc, ExprLoc;
3220 
3221   if (parseOptionalToken(AsmToken::Comma)) {
3222     SizeLoc = getTok().getLoc();
3223     if (parseAbsoluteExpression(FillSize))
3224       return true;
3225     if (parseOptionalToken(AsmToken::Comma)) {
3226       ExprLoc = getTok().getLoc();
3227       if (parseAbsoluteExpression(FillExpr))
3228         return true;
3229     }
3230   }
3231   if (parseToken(AsmToken::EndOfStatement,
3232                  "unexpected token in '.fill' directive"))
3233     return true;
3234 
3235   if (FillSize < 0) {
3236     Warning(SizeLoc, "'.fill' directive with negative size has no effect");
3237     return false;
3238   }
3239   if (FillSize > 8) {
3240     Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3241     FillSize = 8;
3242   }
3243 
3244   if (!isUInt<32>(FillExpr) && FillSize > 4)
3245     Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3246 
3247   getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
3248 
3249   return false;
3250 }
3251 
3252 /// parseDirectiveOrg
3253 ///  ::= .org expression [ , expression ]
3254 bool AsmParser::parseDirectiveOrg() {
3255   const MCExpr *Offset;
3256   SMLoc OffsetLoc = Lexer.getLoc();
3257   if (checkForValidSection() || parseExpression(Offset))
3258     return true;
3259 
3260   // Parse optional fill expression.
3261   int64_t FillExpr = 0;
3262   if (parseOptionalToken(AsmToken::Comma))
3263     if (parseAbsoluteExpression(FillExpr))
3264       return addErrorSuffix(" in '.org' directive");
3265   if (parseToken(AsmToken::EndOfStatement))
3266     return addErrorSuffix(" in '.org' directive");
3267 
3268   getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
3269   return false;
3270 }
3271 
3272 /// parseDirectiveAlign
3273 ///  ::= {.align, ...} expression [ , expression [ , expression ]]
3274 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
3275   SMLoc AlignmentLoc = getLexer().getLoc();
3276   int64_t Alignment;
3277   SMLoc MaxBytesLoc;
3278   bool HasFillExpr = false;
3279   int64_t FillExpr = 0;
3280   int64_t MaxBytesToFill = 0;
3281 
3282   auto parseAlign = [&]() -> bool {
3283     if (parseAbsoluteExpression(Alignment))
3284       return true;
3285     if (parseOptionalToken(AsmToken::Comma)) {
3286       // The fill expression can be omitted while specifying a maximum number of
3287       // alignment bytes, e.g:
3288       //  .align 3,,4
3289       if (getTok().isNot(AsmToken::Comma)) {
3290         HasFillExpr = true;
3291         if (parseAbsoluteExpression(FillExpr))
3292           return true;
3293       }
3294       if (parseOptionalToken(AsmToken::Comma))
3295         if (parseTokenLoc(MaxBytesLoc) ||
3296             parseAbsoluteExpression(MaxBytesToFill))
3297           return true;
3298     }
3299     return parseToken(AsmToken::EndOfStatement);
3300   };
3301 
3302   if (checkForValidSection())
3303     return addErrorSuffix(" in directive");
3304   // Ignore empty '.p2align' directives for GNU-as compatibility
3305   if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
3306     Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
3307     return parseToken(AsmToken::EndOfStatement);
3308   }
3309   if (parseAlign())
3310     return addErrorSuffix(" in directive");
3311 
3312   // Always emit an alignment here even if we thrown an error.
3313   bool ReturnVal = false;
3314 
3315   // Compute alignment in bytes.
3316   if (IsPow2) {
3317     // FIXME: Diagnose overflow.
3318     if (Alignment >= 32) {
3319       ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
3320       Alignment = 31;
3321     }
3322 
3323     Alignment = 1ULL << Alignment;
3324   } else {
3325     // Reject alignments that aren't either a power of two or zero,
3326     // for gas compatibility. Alignment of zero is silently rounded
3327     // up to one.
3328     if (Alignment == 0)
3329       Alignment = 1;
3330     if (!isPowerOf2_64(Alignment))
3331       ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
3332   }
3333 
3334   // Diagnose non-sensical max bytes to align.
3335   if (MaxBytesLoc.isValid()) {
3336     if (MaxBytesToFill < 1) {
3337       ReturnVal |= Error(MaxBytesLoc,
3338                          "alignment directive can never be satisfied in this "
3339                          "many bytes, ignoring maximum bytes expression");
3340       MaxBytesToFill = 0;
3341     }
3342 
3343     if (MaxBytesToFill >= Alignment) {
3344       Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
3345                            "has no effect");
3346       MaxBytesToFill = 0;
3347     }
3348   }
3349 
3350   // Check whether we should use optimal code alignment for this .align
3351   // directive.
3352   const MCSection *Section = getStreamer().getCurrentSectionOnly();
3353   assert(Section && "must have section to emit alignment");
3354   bool UseCodeAlign = Section->UseCodeAlign();
3355   if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3356       ValueSize == 1 && UseCodeAlign) {
3357     getStreamer().emitCodeAlignment(Alignment, MaxBytesToFill);
3358   } else {
3359     // FIXME: Target specific behavior about how the "extra" bytes are filled.
3360     getStreamer().emitValueToAlignment(Alignment, FillExpr, ValueSize,
3361                                        MaxBytesToFill);
3362   }
3363 
3364   return ReturnVal;
3365 }
3366 
3367 /// parseDirectiveFile
3368 /// ::= .file filename
3369 /// ::= .file number [directory] filename [md5 checksum] [source source-text]
3370 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
3371   // FIXME: I'm not sure what this is.
3372   int64_t FileNumber = -1;
3373   if (getLexer().is(AsmToken::Integer)) {
3374     FileNumber = getTok().getIntVal();
3375     Lex();
3376 
3377     if (FileNumber < 0)
3378       return TokError("negative file number");
3379   }
3380 
3381   std::string Path;
3382 
3383   // Usually the directory and filename together, otherwise just the directory.
3384   // Allow the strings to have escaped octal character sequence.
3385   if (check(getTok().isNot(AsmToken::String),
3386             "unexpected token in '.file' directive") ||
3387       parseEscapedString(Path))
3388     return true;
3389 
3390   StringRef Directory;
3391   StringRef Filename;
3392   std::string FilenameData;
3393   if (getLexer().is(AsmToken::String)) {
3394     if (check(FileNumber == -1,
3395               "explicit path specified, but no file number") ||
3396         parseEscapedString(FilenameData))
3397       return true;
3398     Filename = FilenameData;
3399     Directory = Path;
3400   } else {
3401     Filename = Path;
3402   }
3403 
3404   uint64_t MD5Hi, MD5Lo;
3405   bool HasMD5 = false;
3406 
3407   Optional<StringRef> Source;
3408   bool HasSource = false;
3409   std::string SourceString;
3410 
3411   while (!parseOptionalToken(AsmToken::EndOfStatement)) {
3412     StringRef Keyword;
3413     if (check(getTok().isNot(AsmToken::Identifier),
3414               "unexpected token in '.file' directive") ||
3415         parseIdentifier(Keyword))
3416       return true;
3417     if (Keyword == "md5") {
3418       HasMD5 = true;
3419       if (check(FileNumber == -1,
3420                 "MD5 checksum specified, but no file number") ||
3421           parseHexOcta(*this, MD5Hi, MD5Lo))
3422         return true;
3423     } else if (Keyword == "source") {
3424       HasSource = true;
3425       if (check(FileNumber == -1,
3426                 "source specified, but no file number") ||
3427           check(getTok().isNot(AsmToken::String),
3428                 "unexpected token in '.file' directive") ||
3429           parseEscapedString(SourceString))
3430         return true;
3431     } else {
3432       return TokError("unexpected token in '.file' directive");
3433     }
3434   }
3435 
3436   if (FileNumber == -1) {
3437     // Ignore the directive if there is no number and the target doesn't support
3438     // numberless .file directives. This allows some portability of assembler
3439     // between different object file formats.
3440     if (getContext().getAsmInfo()->hasSingleParameterDotFile())
3441       getStreamer().emitFileDirective(Filename);
3442   } else {
3443     // In case there is a -g option as well as debug info from directive .file,
3444     // we turn off the -g option, directly use the existing debug info instead.
3445     // Throw away any implicit file table for the assembler source.
3446     if (Ctx.getGenDwarfForAssembly()) {
3447       Ctx.getMCDwarfLineTable(0).resetFileTable();
3448       Ctx.setGenDwarfForAssembly(false);
3449     }
3450 
3451     Optional<MD5::MD5Result> CKMem;
3452     if (HasMD5) {
3453       MD5::MD5Result Sum;
3454       for (unsigned i = 0; i != 8; ++i) {
3455         Sum.Bytes[i] = uint8_t(MD5Hi >> ((7 - i) * 8));
3456         Sum.Bytes[i + 8] = uint8_t(MD5Lo >> ((7 - i) * 8));
3457       }
3458       CKMem = Sum;
3459     }
3460     if (HasSource) {
3461       char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size()));
3462       memcpy(SourceBuf, SourceString.data(), SourceString.size());
3463       Source = StringRef(SourceBuf, SourceString.size());
3464     }
3465     if (FileNumber == 0) {
3466       if (Ctx.getDwarfVersion() < 5)
3467         return Warning(DirectiveLoc, "file 0 not supported prior to DWARF-5");
3468       getStreamer().emitDwarfFile0Directive(Directory, Filename, CKMem, Source);
3469     } else {
3470       Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective(
3471           FileNumber, Directory, Filename, CKMem, Source);
3472       if (!FileNumOrErr)
3473         return Error(DirectiveLoc, toString(FileNumOrErr.takeError()));
3474     }
3475     // Alert the user if there are some .file directives with MD5 and some not.
3476     // But only do that once.
3477     if (!ReportedInconsistentMD5 && !Ctx.isDwarfMD5UsageConsistent(0)) {
3478       ReportedInconsistentMD5 = true;
3479       return Warning(DirectiveLoc, "inconsistent use of MD5 checksums");
3480     }
3481   }
3482 
3483   return false;
3484 }
3485 
3486 /// parseDirectiveLine
3487 /// ::= .line [number]
3488 bool AsmParser::parseDirectiveLine() {
3489   int64_t LineNumber;
3490   if (getLexer().is(AsmToken::Integer)) {
3491     if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3492       return true;
3493     (void)LineNumber;
3494     // FIXME: Do something with the .line.
3495   }
3496   if (parseToken(AsmToken::EndOfStatement,
3497                  "unexpected token in '.line' directive"))
3498     return true;
3499 
3500   return false;
3501 }
3502 
3503 /// parseDirectiveLoc
3504 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3505 ///                                [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3506 /// The first number is a file number, must have been previously assigned with
3507 /// a .file directive, the second number is the line number and optionally the
3508 /// third number is a column position (zero if not specified).  The remaining
3509 /// optional items are .loc sub-directives.
3510 bool AsmParser::parseDirectiveLoc() {
3511   int64_t FileNumber = 0, LineNumber = 0;
3512   SMLoc Loc = getTok().getLoc();
3513   if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3514       check(FileNumber < 1 && Ctx.getDwarfVersion() < 5, Loc,
3515             "file number less than one in '.loc' directive") ||
3516       check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3517             "unassigned file number in '.loc' directive"))
3518     return true;
3519 
3520   // optional
3521   if (getLexer().is(AsmToken::Integer)) {
3522     LineNumber = getTok().getIntVal();
3523     if (LineNumber < 0)
3524       return TokError("line number less than zero in '.loc' directive");
3525     Lex();
3526   }
3527 
3528   int64_t ColumnPos = 0;
3529   if (getLexer().is(AsmToken::Integer)) {
3530     ColumnPos = getTok().getIntVal();
3531     if (ColumnPos < 0)
3532       return TokError("column position less than zero in '.loc' directive");
3533     Lex();
3534   }
3535 
3536   auto PrevFlags = getContext().getCurrentDwarfLoc().getFlags();
3537   unsigned Flags = PrevFlags & DWARF2_FLAG_IS_STMT;
3538   unsigned Isa = 0;
3539   int64_t Discriminator = 0;
3540 
3541   auto parseLocOp = [&]() -> bool {
3542     StringRef Name;
3543     SMLoc Loc = getTok().getLoc();
3544     if (parseIdentifier(Name))
3545       return TokError("unexpected token in '.loc' directive");
3546 
3547     if (Name == "basic_block")
3548       Flags |= DWARF2_FLAG_BASIC_BLOCK;
3549     else if (Name == "prologue_end")
3550       Flags |= DWARF2_FLAG_PROLOGUE_END;
3551     else if (Name == "epilogue_begin")
3552       Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3553     else if (Name == "is_stmt") {
3554       Loc = getTok().getLoc();
3555       const MCExpr *Value;
3556       if (parseExpression(Value))
3557         return true;
3558       // The expression must be the constant 0 or 1.
3559       if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3560         int Value = MCE->getValue();
3561         if (Value == 0)
3562           Flags &= ~DWARF2_FLAG_IS_STMT;
3563         else if (Value == 1)
3564           Flags |= DWARF2_FLAG_IS_STMT;
3565         else
3566           return Error(Loc, "is_stmt value not 0 or 1");
3567       } else {
3568         return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3569       }
3570     } else if (Name == "isa") {
3571       Loc = getTok().getLoc();
3572       const MCExpr *Value;
3573       if (parseExpression(Value))
3574         return true;
3575       // The expression must be a constant greater or equal to 0.
3576       if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3577         int Value = MCE->getValue();
3578         if (Value < 0)
3579           return Error(Loc, "isa number less than zero");
3580         Isa = Value;
3581       } else {
3582         return Error(Loc, "isa number not a constant value");
3583       }
3584     } else if (Name == "discriminator") {
3585       if (parseAbsoluteExpression(Discriminator))
3586         return true;
3587     } else {
3588       return Error(Loc, "unknown sub-directive in '.loc' directive");
3589     }
3590     return false;
3591   };
3592 
3593   if (parseMany(parseLocOp, false /*hasComma*/))
3594     return true;
3595 
3596   getStreamer().emitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3597                                       Isa, Discriminator, StringRef());
3598 
3599   return false;
3600 }
3601 
3602 /// parseDirectiveStabs
3603 /// ::= .stabs string, number, number, number
3604 bool AsmParser::parseDirectiveStabs() {
3605   return TokError("unsupported directive '.stabs'");
3606 }
3607 
3608 /// parseDirectiveCVFile
3609 /// ::= .cv_file number filename [checksum] [checksumkind]
3610 bool AsmParser::parseDirectiveCVFile() {
3611   SMLoc FileNumberLoc = getTok().getLoc();
3612   int64_t FileNumber;
3613   std::string Filename;
3614   std::string Checksum;
3615   int64_t ChecksumKind = 0;
3616 
3617   if (parseIntToken(FileNumber,
3618                     "expected file number in '.cv_file' directive") ||
3619       check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3620       check(getTok().isNot(AsmToken::String),
3621             "unexpected token in '.cv_file' directive") ||
3622       parseEscapedString(Filename))
3623     return true;
3624   if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3625     if (check(getTok().isNot(AsmToken::String),
3626               "unexpected token in '.cv_file' directive") ||
3627         parseEscapedString(Checksum) ||
3628         parseIntToken(ChecksumKind,
3629                       "expected checksum kind in '.cv_file' directive") ||
3630         parseToken(AsmToken::EndOfStatement,
3631                    "unexpected token in '.cv_file' directive"))
3632       return true;
3633   }
3634 
3635   Checksum = fromHex(Checksum);
3636   void *CKMem = Ctx.allocate(Checksum.size(), 1);
3637   memcpy(CKMem, Checksum.data(), Checksum.size());
3638   ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
3639                                     Checksum.size());
3640 
3641   if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
3642                                          static_cast<uint8_t>(ChecksumKind)))
3643     return Error(FileNumberLoc, "file number already allocated");
3644 
3645   return false;
3646 }
3647 
3648 bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3649                                   StringRef DirectiveName) {
3650   SMLoc Loc;
3651   return parseTokenLoc(Loc) ||
3652          parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3653                                        "' directive") ||
3654          check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3655                "expected function id within range [0, UINT_MAX)");
3656 }
3657 
3658 bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3659   SMLoc Loc;
3660   return parseTokenLoc(Loc) ||
3661          parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3662                                        "' directive") ||
3663          check(FileNumber < 1, Loc, "file number less than one in '" +
3664                                         DirectiveName + "' directive") ||
3665          check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3666                "unassigned file number in '" + DirectiveName + "' directive");
3667 }
3668 
3669 /// parseDirectiveCVFuncId
3670 /// ::= .cv_func_id FunctionId
3671 ///
3672 /// Introduces a function ID that can be used with .cv_loc.
3673 bool AsmParser::parseDirectiveCVFuncId() {
3674   SMLoc FunctionIdLoc = getTok().getLoc();
3675   int64_t FunctionId;
3676 
3677   if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3678       parseToken(AsmToken::EndOfStatement,
3679                  "unexpected token in '.cv_func_id' directive"))
3680     return true;
3681 
3682   if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
3683     return Error(FunctionIdLoc, "function id already allocated");
3684 
3685   return false;
3686 }
3687 
3688 /// parseDirectiveCVInlineSiteId
3689 /// ::= .cv_inline_site_id FunctionId
3690 ///         "within" IAFunc
3691 ///         "inlined_at" IAFile IALine [IACol]
3692 ///
3693 /// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3694 /// at" source location information for use in the line table of the caller,
3695 /// whether the caller is a real function or another inlined call site.
3696 bool AsmParser::parseDirectiveCVInlineSiteId() {
3697   SMLoc FunctionIdLoc = getTok().getLoc();
3698   int64_t FunctionId;
3699   int64_t IAFunc;
3700   int64_t IAFile;
3701   int64_t IALine;
3702   int64_t IACol = 0;
3703 
3704   // FunctionId
3705   if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3706     return true;
3707 
3708   // "within"
3709   if (check((getLexer().isNot(AsmToken::Identifier) ||
3710              getTok().getIdentifier() != "within"),
3711             "expected 'within' identifier in '.cv_inline_site_id' directive"))
3712     return true;
3713   Lex();
3714 
3715   // IAFunc
3716   if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3717     return true;
3718 
3719   // "inlined_at"
3720   if (check((getLexer().isNot(AsmToken::Identifier) ||
3721              getTok().getIdentifier() != "inlined_at"),
3722             "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3723             "directive") )
3724     return true;
3725   Lex();
3726 
3727   // IAFile IALine
3728   if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3729       parseIntToken(IALine, "expected line number after 'inlined_at'"))
3730     return true;
3731 
3732   // [IACol]
3733   if (getLexer().is(AsmToken::Integer)) {
3734     IACol = getTok().getIntVal();
3735     Lex();
3736   }
3737 
3738   if (parseToken(AsmToken::EndOfStatement,
3739                  "unexpected token in '.cv_inline_site_id' directive"))
3740     return true;
3741 
3742   if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3743                                                  IALine, IACol, FunctionIdLoc))
3744     return Error(FunctionIdLoc, "function id already allocated");
3745 
3746   return false;
3747 }
3748 
3749 /// parseDirectiveCVLoc
3750 /// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3751 ///                                [is_stmt VALUE]
3752 /// The first number is a file number, must have been previously assigned with
3753 /// a .file directive, the second number is the line number and optionally the
3754 /// third number is a column position (zero if not specified).  The remaining
3755 /// optional items are .loc sub-directives.
3756 bool AsmParser::parseDirectiveCVLoc() {
3757   SMLoc DirectiveLoc = getTok().getLoc();
3758   int64_t FunctionId, FileNumber;
3759   if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3760       parseCVFileId(FileNumber, ".cv_loc"))
3761     return true;
3762 
3763   int64_t LineNumber = 0;
3764   if (getLexer().is(AsmToken::Integer)) {
3765     LineNumber = getTok().getIntVal();
3766     if (LineNumber < 0)
3767       return TokError("line number less than zero in '.cv_loc' directive");
3768     Lex();
3769   }
3770 
3771   int64_t ColumnPos = 0;
3772   if (getLexer().is(AsmToken::Integer)) {
3773     ColumnPos = getTok().getIntVal();
3774     if (ColumnPos < 0)
3775       return TokError("column position less than zero in '.cv_loc' directive");
3776     Lex();
3777   }
3778 
3779   bool PrologueEnd = false;
3780   uint64_t IsStmt = 0;
3781 
3782   auto parseOp = [&]() -> bool {
3783     StringRef Name;
3784     SMLoc Loc = getTok().getLoc();
3785     if (parseIdentifier(Name))
3786       return TokError("unexpected token in '.cv_loc' directive");
3787     if (Name == "prologue_end")
3788       PrologueEnd = true;
3789     else if (Name == "is_stmt") {
3790       Loc = getTok().getLoc();
3791       const MCExpr *Value;
3792       if (parseExpression(Value))
3793         return true;
3794       // The expression must be the constant 0 or 1.
3795       IsStmt = ~0ULL;
3796       if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3797         IsStmt = MCE->getValue();
3798 
3799       if (IsStmt > 1)
3800         return Error(Loc, "is_stmt value not 0 or 1");
3801     } else {
3802       return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3803     }
3804     return false;
3805   };
3806 
3807   if (parseMany(parseOp, false /*hasComma*/))
3808     return true;
3809 
3810   getStreamer().emitCVLocDirective(FunctionId, FileNumber, LineNumber,
3811                                    ColumnPos, PrologueEnd, IsStmt, StringRef(),
3812                                    DirectiveLoc);
3813   return false;
3814 }
3815 
3816 /// parseDirectiveCVLinetable
3817 /// ::= .cv_linetable FunctionId, FnStart, FnEnd
3818 bool AsmParser::parseDirectiveCVLinetable() {
3819   int64_t FunctionId;
3820   StringRef FnStartName, FnEndName;
3821   SMLoc Loc = getTok().getLoc();
3822   if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
3823       parseToken(AsmToken::Comma,
3824                  "unexpected token in '.cv_linetable' directive") ||
3825       parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3826                                   "expected identifier in directive") ||
3827       parseToken(AsmToken::Comma,
3828                  "unexpected token in '.cv_linetable' directive") ||
3829       parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3830                                   "expected identifier in directive"))
3831     return true;
3832 
3833   MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3834   MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3835 
3836   getStreamer().emitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3837   return false;
3838 }
3839 
3840 /// parseDirectiveCVInlineLinetable
3841 /// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
3842 bool AsmParser::parseDirectiveCVInlineLinetable() {
3843   int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3844   StringRef FnStartName, FnEndName;
3845   SMLoc Loc = getTok().getLoc();
3846   if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
3847       parseTokenLoc(Loc) ||
3848       parseIntToken(
3849           SourceFileId,
3850           "expected SourceField in '.cv_inline_linetable' directive") ||
3851       check(SourceFileId <= 0, Loc,
3852             "File id less than zero in '.cv_inline_linetable' directive") ||
3853       parseTokenLoc(Loc) ||
3854       parseIntToken(
3855           SourceLineNum,
3856           "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3857       check(SourceLineNum < 0, Loc,
3858             "Line number less than zero in '.cv_inline_linetable' directive") ||
3859       parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3860                                   "expected identifier in directive") ||
3861       parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3862                                   "expected identifier in directive"))
3863     return true;
3864 
3865   if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3866     return true;
3867 
3868   MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3869   MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3870   getStreamer().emitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3871                                                SourceLineNum, FnStartSym,
3872                                                FnEndSym);
3873   return false;
3874 }
3875 
3876 void AsmParser::initializeCVDefRangeTypeMap() {
3877   CVDefRangeTypeMap["reg"] = CVDR_DEFRANGE_REGISTER;
3878   CVDefRangeTypeMap["frame_ptr_rel"] = CVDR_DEFRANGE_FRAMEPOINTER_REL;
3879   CVDefRangeTypeMap["subfield_reg"] = CVDR_DEFRANGE_SUBFIELD_REGISTER;
3880   CVDefRangeTypeMap["reg_rel"] = CVDR_DEFRANGE_REGISTER_REL;
3881 }
3882 
3883 /// parseDirectiveCVDefRange
3884 /// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3885 bool AsmParser::parseDirectiveCVDefRange() {
3886   SMLoc Loc;
3887   std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3888   while (getLexer().is(AsmToken::Identifier)) {
3889     Loc = getLexer().getLoc();
3890     StringRef GapStartName;
3891     if (parseIdentifier(GapStartName))
3892       return Error(Loc, "expected identifier in directive");
3893     MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3894 
3895     Loc = getLexer().getLoc();
3896     StringRef GapEndName;
3897     if (parseIdentifier(GapEndName))
3898       return Error(Loc, "expected identifier in directive");
3899     MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3900 
3901     Ranges.push_back({GapStartSym, GapEndSym});
3902   }
3903 
3904   StringRef CVDefRangeTypeStr;
3905   if (parseToken(
3906           AsmToken::Comma,
3907           "expected comma before def_range type in .cv_def_range directive") ||
3908       parseIdentifier(CVDefRangeTypeStr))
3909     return Error(Loc, "expected def_range type in directive");
3910 
3911   StringMap<CVDefRangeType>::const_iterator CVTypeIt =
3912       CVDefRangeTypeMap.find(CVDefRangeTypeStr);
3913   CVDefRangeType CVDRType = (CVTypeIt == CVDefRangeTypeMap.end())
3914                                 ? CVDR_DEFRANGE
3915                                 : CVTypeIt->getValue();
3916   switch (CVDRType) {
3917   case CVDR_DEFRANGE_REGISTER: {
3918     int64_t DRRegister;
3919     if (parseToken(AsmToken::Comma, "expected comma before register number in "
3920                                     ".cv_def_range directive") ||
3921         parseAbsoluteExpression(DRRegister))
3922       return Error(Loc, "expected register number");
3923 
3924     codeview::DefRangeRegisterHeader DRHdr;
3925     DRHdr.Register = DRRegister;
3926     DRHdr.MayHaveNoName = 0;
3927     getStreamer().emitCVDefRangeDirective(Ranges, DRHdr);
3928     break;
3929   }
3930   case CVDR_DEFRANGE_FRAMEPOINTER_REL: {
3931     int64_t DROffset;
3932     if (parseToken(AsmToken::Comma,
3933                    "expected comma before offset in .cv_def_range directive") ||
3934         parseAbsoluteExpression(DROffset))
3935       return Error(Loc, "expected offset value");
3936 
3937     codeview::DefRangeFramePointerRelHeader DRHdr;
3938     DRHdr.Offset = DROffset;
3939     getStreamer().emitCVDefRangeDirective(Ranges, DRHdr);
3940     break;
3941   }
3942   case CVDR_DEFRANGE_SUBFIELD_REGISTER: {
3943     int64_t DRRegister;
3944     int64_t DROffsetInParent;
3945     if (parseToken(AsmToken::Comma, "expected comma before register number in "
3946                                     ".cv_def_range directive") ||
3947         parseAbsoluteExpression(DRRegister))
3948       return Error(Loc, "expected register number");
3949     if (parseToken(AsmToken::Comma,
3950                    "expected comma before offset in .cv_def_range directive") ||
3951         parseAbsoluteExpression(DROffsetInParent))
3952       return Error(Loc, "expected offset value");
3953 
3954     codeview::DefRangeSubfieldRegisterHeader DRHdr;
3955     DRHdr.Register = DRRegister;
3956     DRHdr.MayHaveNoName = 0;
3957     DRHdr.OffsetInParent = DROffsetInParent;
3958     getStreamer().emitCVDefRangeDirective(Ranges, DRHdr);
3959     break;
3960   }
3961   case CVDR_DEFRANGE_REGISTER_REL: {
3962     int64_t DRRegister;
3963     int64_t DRFlags;
3964     int64_t DRBasePointerOffset;
3965     if (parseToken(AsmToken::Comma, "expected comma before register number in "
3966                                     ".cv_def_range directive") ||
3967         parseAbsoluteExpression(DRRegister))
3968       return Error(Loc, "expected register value");
3969     if (parseToken(
3970             AsmToken::Comma,
3971             "expected comma before flag value in .cv_def_range directive") ||
3972         parseAbsoluteExpression(DRFlags))
3973       return Error(Loc, "expected flag value");
3974     if (parseToken(AsmToken::Comma, "expected comma before base pointer offset "
3975                                     "in .cv_def_range directive") ||
3976         parseAbsoluteExpression(DRBasePointerOffset))
3977       return Error(Loc, "expected base pointer offset value");
3978 
3979     codeview::DefRangeRegisterRelHeader DRHdr;
3980     DRHdr.Register = DRRegister;
3981     DRHdr.Flags = DRFlags;
3982     DRHdr.BasePointerOffset = DRBasePointerOffset;
3983     getStreamer().emitCVDefRangeDirective(Ranges, DRHdr);
3984     break;
3985   }
3986   default:
3987     return Error(Loc, "unexpected def_range type in .cv_def_range directive");
3988   }
3989   return true;
3990 }
3991 
3992 /// parseDirectiveCVString
3993 /// ::= .cv_stringtable "string"
3994 bool AsmParser::parseDirectiveCVString() {
3995   std::string Data;
3996   if (checkForValidSection() || parseEscapedString(Data))
3997     return addErrorSuffix(" in '.cv_string' directive");
3998 
3999   // Put the string in the table and emit the offset.
4000   std::pair<StringRef, unsigned> Insertion =
4001       getCVContext().addToStringTable(Data);
4002   getStreamer().emitInt32(Insertion.second);
4003   return false;
4004 }
4005 
4006 /// parseDirectiveCVStringTable
4007 /// ::= .cv_stringtable
4008 bool AsmParser::parseDirectiveCVStringTable() {
4009   getStreamer().emitCVStringTableDirective();
4010   return false;
4011 }
4012 
4013 /// parseDirectiveCVFileChecksums
4014 /// ::= .cv_filechecksums
4015 bool AsmParser::parseDirectiveCVFileChecksums() {
4016   getStreamer().emitCVFileChecksumsDirective();
4017   return false;
4018 }
4019 
4020 /// parseDirectiveCVFileChecksumOffset
4021 /// ::= .cv_filechecksumoffset fileno
4022 bool AsmParser::parseDirectiveCVFileChecksumOffset() {
4023   int64_t FileNo;
4024   if (parseIntToken(FileNo, "expected identifier in directive"))
4025     return true;
4026   if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
4027     return true;
4028   getStreamer().emitCVFileChecksumOffsetDirective(FileNo);
4029   return false;
4030 }
4031 
4032 /// parseDirectiveCVFPOData
4033 /// ::= .cv_fpo_data procsym
4034 bool AsmParser::parseDirectiveCVFPOData() {
4035   SMLoc DirLoc = getLexer().getLoc();
4036   StringRef ProcName;
4037   if (parseIdentifier(ProcName))
4038     return TokError("expected symbol name");
4039   if (parseEOL("unexpected tokens"))
4040     return addErrorSuffix(" in '.cv_fpo_data' directive");
4041   MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
4042   getStreamer().EmitCVFPOData(ProcSym, DirLoc);
4043   return false;
4044 }
4045 
4046 /// parseDirectiveCFISections
4047 /// ::= .cfi_sections section [, section]
4048 bool AsmParser::parseDirectiveCFISections() {
4049   StringRef Name;
4050   bool EH = false;
4051   bool Debug = false;
4052 
4053   if (parseIdentifier(Name))
4054     return TokError("Expected an identifier");
4055 
4056   if (Name == ".eh_frame")
4057     EH = true;
4058   else if (Name == ".debug_frame")
4059     Debug = true;
4060 
4061   if (getLexer().is(AsmToken::Comma)) {
4062     Lex();
4063 
4064     if (parseIdentifier(Name))
4065       return TokError("Expected an identifier");
4066 
4067     if (Name == ".eh_frame")
4068       EH = true;
4069     else if (Name == ".debug_frame")
4070       Debug = true;
4071   }
4072 
4073   getStreamer().emitCFISections(EH, Debug);
4074   return false;
4075 }
4076 
4077 /// parseDirectiveCFIStartProc
4078 /// ::= .cfi_startproc [simple]
4079 bool AsmParser::parseDirectiveCFIStartProc() {
4080   StringRef Simple;
4081   if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4082     if (check(parseIdentifier(Simple) || Simple != "simple",
4083               "unexpected token") ||
4084         parseToken(AsmToken::EndOfStatement))
4085       return addErrorSuffix(" in '.cfi_startproc' directive");
4086   }
4087 
4088   // TODO(kristina): Deal with a corner case of incorrect diagnostic context
4089   // being produced if this directive is emitted as part of preprocessor macro
4090   // expansion which can *ONLY* happen if Clang's cc1as is the API consumer.
4091   // Tools like llvm-mc on the other hand are not affected by it, and report
4092   // correct context information.
4093   getStreamer().emitCFIStartProc(!Simple.empty(), Lexer.getLoc());
4094   return false;
4095 }
4096 
4097 /// parseDirectiveCFIEndProc
4098 /// ::= .cfi_endproc
4099 bool AsmParser::parseDirectiveCFIEndProc() {
4100   getStreamer().emitCFIEndProc();
4101   return false;
4102 }
4103 
4104 /// parse register name or number.
4105 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
4106                                               SMLoc DirectiveLoc) {
4107   unsigned RegNo;
4108 
4109   if (getLexer().isNot(AsmToken::Integer)) {
4110     if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
4111       return true;
4112     Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
4113   } else
4114     return parseAbsoluteExpression(Register);
4115 
4116   return false;
4117 }
4118 
4119 /// parseDirectiveCFIDefCfa
4120 /// ::= .cfi_def_cfa register,  offset
4121 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
4122   int64_t Register = 0, Offset = 0;
4123   if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4124       parseToken(AsmToken::Comma, "unexpected token in directive") ||
4125       parseAbsoluteExpression(Offset))
4126     return true;
4127 
4128   getStreamer().emitCFIDefCfa(Register, Offset);
4129   return false;
4130 }
4131 
4132 /// parseDirectiveCFIDefCfaOffset
4133 /// ::= .cfi_def_cfa_offset offset
4134 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
4135   int64_t Offset = 0;
4136   if (parseAbsoluteExpression(Offset))
4137     return true;
4138 
4139   getStreamer().emitCFIDefCfaOffset(Offset);
4140   return false;
4141 }
4142 
4143 /// parseDirectiveCFIRegister
4144 /// ::= .cfi_register register, register
4145 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
4146   int64_t Register1 = 0, Register2 = 0;
4147   if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
4148       parseToken(AsmToken::Comma, "unexpected token in directive") ||
4149       parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
4150     return true;
4151 
4152   getStreamer().emitCFIRegister(Register1, Register2);
4153   return false;
4154 }
4155 
4156 /// parseDirectiveCFIWindowSave
4157 /// ::= .cfi_window_save
4158 bool AsmParser::parseDirectiveCFIWindowSave() {
4159   getStreamer().emitCFIWindowSave();
4160   return false;
4161 }
4162 
4163 /// parseDirectiveCFIAdjustCfaOffset
4164 /// ::= .cfi_adjust_cfa_offset adjustment
4165 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
4166   int64_t Adjustment = 0;
4167   if (parseAbsoluteExpression(Adjustment))
4168     return true;
4169 
4170   getStreamer().emitCFIAdjustCfaOffset(Adjustment);
4171   return false;
4172 }
4173 
4174 /// parseDirectiveCFIDefCfaRegister
4175 /// ::= .cfi_def_cfa_register register
4176 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
4177   int64_t Register = 0;
4178   if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4179     return true;
4180 
4181   getStreamer().emitCFIDefCfaRegister(Register);
4182   return false;
4183 }
4184 
4185 /// parseDirectiveCFIOffset
4186 /// ::= .cfi_offset register, offset
4187 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
4188   int64_t Register = 0;
4189   int64_t Offset = 0;
4190 
4191   if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4192       parseToken(AsmToken::Comma, "unexpected token in directive") ||
4193       parseAbsoluteExpression(Offset))
4194     return true;
4195 
4196   getStreamer().emitCFIOffset(Register, Offset);
4197   return false;
4198 }
4199 
4200 /// parseDirectiveCFIRelOffset
4201 /// ::= .cfi_rel_offset register, offset
4202 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
4203   int64_t Register = 0, Offset = 0;
4204 
4205   if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4206       parseToken(AsmToken::Comma, "unexpected token in directive") ||
4207       parseAbsoluteExpression(Offset))
4208     return true;
4209 
4210   getStreamer().emitCFIRelOffset(Register, Offset);
4211   return false;
4212 }
4213 
4214 static bool isValidEncoding(int64_t Encoding) {
4215   if (Encoding & ~0xff)
4216     return false;
4217 
4218   if (Encoding == dwarf::DW_EH_PE_omit)
4219     return true;
4220 
4221   const unsigned Format = Encoding & 0xf;
4222   if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
4223       Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
4224       Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
4225       Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
4226     return false;
4227 
4228   const unsigned Application = Encoding & 0x70;
4229   if (Application != dwarf::DW_EH_PE_absptr &&
4230       Application != dwarf::DW_EH_PE_pcrel)
4231     return false;
4232 
4233   return true;
4234 }
4235 
4236 /// parseDirectiveCFIPersonalityOrLsda
4237 /// IsPersonality true for cfi_personality, false for cfi_lsda
4238 /// ::= .cfi_personality encoding, [symbol_name]
4239 /// ::= .cfi_lsda encoding, [symbol_name]
4240 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
4241   int64_t Encoding = 0;
4242   if (parseAbsoluteExpression(Encoding))
4243     return true;
4244   if (Encoding == dwarf::DW_EH_PE_omit)
4245     return false;
4246 
4247   StringRef Name;
4248   if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
4249       parseToken(AsmToken::Comma, "unexpected token in directive") ||
4250       check(parseIdentifier(Name), "expected identifier in directive"))
4251     return true;
4252 
4253   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4254 
4255   if (IsPersonality)
4256     getStreamer().emitCFIPersonality(Sym, Encoding);
4257   else
4258     getStreamer().emitCFILsda(Sym, Encoding);
4259   return false;
4260 }
4261 
4262 /// parseDirectiveCFIRememberState
4263 /// ::= .cfi_remember_state
4264 bool AsmParser::parseDirectiveCFIRememberState() {
4265   getStreamer().emitCFIRememberState();
4266   return false;
4267 }
4268 
4269 /// parseDirectiveCFIRestoreState
4270 /// ::= .cfi_remember_state
4271 bool AsmParser::parseDirectiveCFIRestoreState() {
4272   getStreamer().emitCFIRestoreState();
4273   return false;
4274 }
4275 
4276 /// parseDirectiveCFISameValue
4277 /// ::= .cfi_same_value register
4278 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
4279   int64_t Register = 0;
4280 
4281   if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4282     return true;
4283 
4284   getStreamer().emitCFISameValue(Register);
4285   return false;
4286 }
4287 
4288 /// parseDirectiveCFIRestore
4289 /// ::= .cfi_restore register
4290 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
4291   int64_t Register = 0;
4292   if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4293     return true;
4294 
4295   getStreamer().emitCFIRestore(Register);
4296   return false;
4297 }
4298 
4299 /// parseDirectiveCFIEscape
4300 /// ::= .cfi_escape expression[,...]
4301 bool AsmParser::parseDirectiveCFIEscape() {
4302   std::string Values;
4303   int64_t CurrValue;
4304   if (parseAbsoluteExpression(CurrValue))
4305     return true;
4306 
4307   Values.push_back((uint8_t)CurrValue);
4308 
4309   while (getLexer().is(AsmToken::Comma)) {
4310     Lex();
4311 
4312     if (parseAbsoluteExpression(CurrValue))
4313       return true;
4314 
4315     Values.push_back((uint8_t)CurrValue);
4316   }
4317 
4318   getStreamer().emitCFIEscape(Values);
4319   return false;
4320 }
4321 
4322 /// parseDirectiveCFIReturnColumn
4323 /// ::= .cfi_return_column register
4324 bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4325   int64_t Register = 0;
4326   if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4327     return true;
4328   getStreamer().emitCFIReturnColumn(Register);
4329   return false;
4330 }
4331 
4332 /// parseDirectiveCFISignalFrame
4333 /// ::= .cfi_signal_frame
4334 bool AsmParser::parseDirectiveCFISignalFrame() {
4335   if (parseToken(AsmToken::EndOfStatement,
4336                  "unexpected token in '.cfi_signal_frame'"))
4337     return true;
4338 
4339   getStreamer().emitCFISignalFrame();
4340   return false;
4341 }
4342 
4343 /// parseDirectiveCFIUndefined
4344 /// ::= .cfi_undefined register
4345 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
4346   int64_t Register = 0;
4347 
4348   if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4349     return true;
4350 
4351   getStreamer().emitCFIUndefined(Register);
4352   return false;
4353 }
4354 
4355 /// parseDirectiveAltmacro
4356 /// ::= .altmacro
4357 /// ::= .noaltmacro
4358 bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4359   if (getLexer().isNot(AsmToken::EndOfStatement))
4360     return TokError("unexpected token in '" + Directive + "' directive");
4361   AltMacroMode = (Directive == ".altmacro");
4362   return false;
4363 }
4364 
4365 /// parseDirectiveMacrosOnOff
4366 /// ::= .macros_on
4367 /// ::= .macros_off
4368 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
4369   if (parseToken(AsmToken::EndOfStatement,
4370                  "unexpected token in '" + Directive + "' directive"))
4371     return true;
4372 
4373   setMacrosEnabled(Directive == ".macros_on");
4374   return false;
4375 }
4376 
4377 /// parseDirectiveMacro
4378 /// ::= .macro name[,] [parameters]
4379 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
4380   StringRef Name;
4381   if (parseIdentifier(Name))
4382     return TokError("expected identifier in '.macro' directive");
4383 
4384   if (getLexer().is(AsmToken::Comma))
4385     Lex();
4386 
4387   MCAsmMacroParameters Parameters;
4388   while (getLexer().isNot(AsmToken::EndOfStatement)) {
4389 
4390     if (!Parameters.empty() && Parameters.back().Vararg)
4391       return Error(Lexer.getLoc(), "vararg parameter '" +
4392                                        Parameters.back().Name +
4393                                        "' should be the last parameter");
4394 
4395     MCAsmMacroParameter Parameter;
4396     if (parseIdentifier(Parameter.Name))
4397       return TokError("expected identifier in '.macro' directive");
4398 
4399     // Emit an error if two (or more) named parameters share the same name
4400     for (const MCAsmMacroParameter& CurrParam : Parameters)
4401       if (CurrParam.Name.equals(Parameter.Name))
4402         return TokError("macro '" + Name + "' has multiple parameters"
4403                         " named '" + Parameter.Name + "'");
4404 
4405     if (Lexer.is(AsmToken::Colon)) {
4406       Lex();  // consume ':'
4407 
4408       SMLoc QualLoc;
4409       StringRef Qualifier;
4410 
4411       QualLoc = Lexer.getLoc();
4412       if (parseIdentifier(Qualifier))
4413         return Error(QualLoc, "missing parameter qualifier for "
4414                      "'" + Parameter.Name + "' in macro '" + Name + "'");
4415 
4416       if (Qualifier == "req")
4417         Parameter.Required = true;
4418       else if (Qualifier == "vararg")
4419         Parameter.Vararg = true;
4420       else
4421         return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4422                      "for '" + Parameter.Name + "' in macro '" + Name + "'");
4423     }
4424 
4425     if (getLexer().is(AsmToken::Equal)) {
4426       Lex();
4427 
4428       SMLoc ParamLoc;
4429 
4430       ParamLoc = Lexer.getLoc();
4431       if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
4432         return true;
4433 
4434       if (Parameter.Required)
4435         Warning(ParamLoc, "pointless default value for required parameter "
4436                 "'" + Parameter.Name + "' in macro '" + Name + "'");
4437     }
4438 
4439     Parameters.push_back(std::move(Parameter));
4440 
4441     if (getLexer().is(AsmToken::Comma))
4442       Lex();
4443   }
4444 
4445   // Eat just the end of statement.
4446   Lexer.Lex();
4447 
4448   // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
4449   AsmToken EndToken, StartToken = getTok();
4450   unsigned MacroDepth = 0;
4451   // Lex the macro definition.
4452   while (true) {
4453     // Ignore Lexing errors in macros.
4454     while (Lexer.is(AsmToken::Error)) {
4455       Lexer.Lex();
4456     }
4457 
4458     // Check whether we have reached the end of the file.
4459     if (getLexer().is(AsmToken::Eof))
4460       return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4461 
4462     // Otherwise, check whether we have reach the .endmacro or the start of a
4463     // preprocessor line marker.
4464     if (getLexer().is(AsmToken::Identifier)) {
4465       if (getTok().getIdentifier() == ".endm" ||
4466           getTok().getIdentifier() == ".endmacro") {
4467         if (MacroDepth == 0) { // Outermost macro.
4468           EndToken = getTok();
4469           Lexer.Lex();
4470           if (getLexer().isNot(AsmToken::EndOfStatement))
4471             return TokError("unexpected token in '" + EndToken.getIdentifier() +
4472                             "' directive");
4473           break;
4474         } else {
4475           // Otherwise we just found the end of an inner macro.
4476           --MacroDepth;
4477         }
4478       } else if (getTok().getIdentifier() == ".macro") {
4479         // We allow nested macros. Those aren't instantiated until the outermost
4480         // macro is expanded so just ignore them for now.
4481         ++MacroDepth;
4482       }
4483     } else if (Lexer.is(AsmToken::HashDirective)) {
4484       (void)parseCppHashLineFilenameComment(getLexer().getLoc());
4485     }
4486 
4487     // Otherwise, scan til the end of the statement.
4488     eatToEndOfStatement();
4489   }
4490 
4491   if (getContext().lookupMacro(Name)) {
4492     return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4493   }
4494 
4495   const char *BodyStart = StartToken.getLoc().getPointer();
4496   const char *BodyEnd = EndToken.getLoc().getPointer();
4497   StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4498   checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
4499   MCAsmMacro Macro(Name, Body, std::move(Parameters));
4500   DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n";
4501                   Macro.dump());
4502   getContext().defineMacro(Name, std::move(Macro));
4503   return false;
4504 }
4505 
4506 /// checkForBadMacro
4507 ///
4508 /// With the support added for named parameters there may be code out there that
4509 /// is transitioning from positional parameters.  In versions of gas that did
4510 /// not support named parameters they would be ignored on the macro definition.
4511 /// But to support both styles of parameters this is not possible so if a macro
4512 /// definition has named parameters but does not use them and has what appears
4513 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4514 /// warning that the positional parameter found in body which have no effect.
4515 /// Hoping the developer will either remove the named parameters from the macro
4516 /// definition so the positional parameters get used if that was what was
4517 /// intended or change the macro to use the named parameters.  It is possible
4518 /// this warning will trigger when the none of the named parameters are used
4519 /// and the strings like $1 are infact to simply to be passed trough unchanged.
4520 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
4521                                  StringRef Body,
4522                                  ArrayRef<MCAsmMacroParameter> Parameters) {
4523   // If this macro is not defined with named parameters the warning we are
4524   // checking for here doesn't apply.
4525   unsigned NParameters = Parameters.size();
4526   if (NParameters == 0)
4527     return;
4528 
4529   bool NamedParametersFound = false;
4530   bool PositionalParametersFound = false;
4531 
4532   // Look at the body of the macro for use of both the named parameters and what
4533   // are likely to be positional parameters.  This is what expandMacro() is
4534   // doing when it finds the parameters in the body.
4535   while (!Body.empty()) {
4536     // Scan for the next possible parameter.
4537     std::size_t End = Body.size(), Pos = 0;
4538     for (; Pos != End; ++Pos) {
4539       // Check for a substitution or escape.
4540       // This macro is defined with parameters, look for \foo, \bar, etc.
4541       if (Body[Pos] == '\\' && Pos + 1 != End)
4542         break;
4543 
4544       // This macro should have parameters, but look for $0, $1, ..., $n too.
4545       if (Body[Pos] != '$' || Pos + 1 == End)
4546         continue;
4547       char Next = Body[Pos + 1];
4548       if (Next == '$' || Next == 'n' ||
4549           isdigit(static_cast<unsigned char>(Next)))
4550         break;
4551     }
4552 
4553     // Check if we reached the end.
4554     if (Pos == End)
4555       break;
4556 
4557     if (Body[Pos] == '$') {
4558       switch (Body[Pos + 1]) {
4559       // $$ => $
4560       case '$':
4561         break;
4562 
4563       // $n => number of arguments
4564       case 'n':
4565         PositionalParametersFound = true;
4566         break;
4567 
4568       // $[0-9] => argument
4569       default: {
4570         PositionalParametersFound = true;
4571         break;
4572       }
4573       }
4574       Pos += 2;
4575     } else {
4576       unsigned I = Pos + 1;
4577       while (isIdentifierChar(Body[I]) && I + 1 != End)
4578         ++I;
4579 
4580       const char *Begin = Body.data() + Pos + 1;
4581       StringRef Argument(Begin, I - (Pos + 1));
4582       unsigned Index = 0;
4583       for (; Index < NParameters; ++Index)
4584         if (Parameters[Index].Name == Argument)
4585           break;
4586 
4587       if (Index == NParameters) {
4588         if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4589           Pos += 3;
4590         else {
4591           Pos = I;
4592         }
4593       } else {
4594         NamedParametersFound = true;
4595         Pos += 1 + Argument.size();
4596       }
4597     }
4598     // Update the scan point.
4599     Body = Body.substr(Pos);
4600   }
4601 
4602   if (!NamedParametersFound && PositionalParametersFound)
4603     Warning(DirectiveLoc, "macro defined with named parameters which are not "
4604                           "used in macro body, possible positional parameter "
4605                           "found in body which will have no effect");
4606 }
4607 
4608 /// parseDirectiveExitMacro
4609 /// ::= .exitm
4610 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
4611   if (parseToken(AsmToken::EndOfStatement,
4612                  "unexpected token in '" + Directive + "' directive"))
4613     return true;
4614 
4615   if (!isInsideMacroInstantiation())
4616     return TokError("unexpected '" + Directive + "' in file, "
4617                                                  "no current macro definition");
4618 
4619   // Exit all conditionals that are active in the current macro.
4620   while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4621     TheCondState = TheCondStack.back();
4622     TheCondStack.pop_back();
4623   }
4624 
4625   handleMacroExit();
4626   return false;
4627 }
4628 
4629 /// parseDirectiveEndMacro
4630 /// ::= .endm
4631 /// ::= .endmacro
4632 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
4633   if (getLexer().isNot(AsmToken::EndOfStatement))
4634     return TokError("unexpected token in '" + Directive + "' directive");
4635 
4636   // If we are inside a macro instantiation, terminate the current
4637   // instantiation.
4638   if (isInsideMacroInstantiation()) {
4639     handleMacroExit();
4640     return false;
4641   }
4642 
4643   // Otherwise, this .endmacro is a stray entry in the file; well formed
4644   // .endmacro directives are handled during the macro definition parsing.
4645   return TokError("unexpected '" + Directive + "' in file, "
4646                                                "no current macro definition");
4647 }
4648 
4649 /// parseDirectivePurgeMacro
4650 /// ::= .purgem
4651 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
4652   StringRef Name;
4653   SMLoc Loc;
4654   if (parseTokenLoc(Loc) ||
4655       check(parseIdentifier(Name), Loc,
4656             "expected identifier in '.purgem' directive") ||
4657       parseToken(AsmToken::EndOfStatement,
4658                  "unexpected token in '.purgem' directive"))
4659     return true;
4660 
4661   if (!getContext().lookupMacro(Name))
4662     return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4663 
4664   getContext().undefineMacro(Name);
4665   DEBUG_WITH_TYPE("asm-macros", dbgs()
4666                                     << "Un-defining macro: " << Name << "\n");
4667   return false;
4668 }
4669 
4670 /// parseDirectiveBundleAlignMode
4671 /// ::= {.bundle_align_mode} expression
4672 bool AsmParser::parseDirectiveBundleAlignMode() {
4673   // Expect a single argument: an expression that evaluates to a constant
4674   // in the inclusive range 0-30.
4675   SMLoc ExprLoc = getLexer().getLoc();
4676   int64_t AlignSizePow2;
4677   if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
4678       parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4679                                            "in '.bundle_align_mode' "
4680                                            "directive") ||
4681       check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4682             "invalid bundle alignment size (expected between 0 and 30)"))
4683     return true;
4684 
4685   // Because of AlignSizePow2's verified range we can safely truncate it to
4686   // unsigned.
4687   getStreamer().emitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4688   return false;
4689 }
4690 
4691 /// parseDirectiveBundleLock
4692 /// ::= {.bundle_lock} [align_to_end]
4693 bool AsmParser::parseDirectiveBundleLock() {
4694   if (checkForValidSection())
4695     return true;
4696   bool AlignToEnd = false;
4697 
4698   StringRef Option;
4699   SMLoc Loc = getTok().getLoc();
4700   const char *kInvalidOptionError =
4701       "invalid option for '.bundle_lock' directive";
4702 
4703   if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4704     if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4705         check(Option != "align_to_end", Loc, kInvalidOptionError) ||
4706         parseToken(AsmToken::EndOfStatement,
4707                    "unexpected token after '.bundle_lock' directive option"))
4708       return true;
4709     AlignToEnd = true;
4710   }
4711 
4712   getStreamer().emitBundleLock(AlignToEnd);
4713   return false;
4714 }
4715 
4716 /// parseDirectiveBundleLock
4717 /// ::= {.bundle_lock}
4718 bool AsmParser::parseDirectiveBundleUnlock() {
4719   if (checkForValidSection() ||
4720       parseToken(AsmToken::EndOfStatement,
4721                  "unexpected token in '.bundle_unlock' directive"))
4722     return true;
4723 
4724   getStreamer().emitBundleUnlock();
4725   return false;
4726 }
4727 
4728 /// parseDirectiveSpace
4729 /// ::= (.skip | .space) expression [ , expression ]
4730 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
4731   SMLoc NumBytesLoc = Lexer.getLoc();
4732   const MCExpr *NumBytes;
4733   if (checkForValidSection() || parseExpression(NumBytes))
4734     return true;
4735 
4736   int64_t FillExpr = 0;
4737   if (parseOptionalToken(AsmToken::Comma))
4738     if (parseAbsoluteExpression(FillExpr))
4739       return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4740   if (parseToken(AsmToken::EndOfStatement))
4741     return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4742 
4743   // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
4744   getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
4745 
4746   return false;
4747 }
4748 
4749 /// parseDirectiveDCB
4750 /// ::= .dcb.{b, l, w} expression, expression
4751 bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
4752   SMLoc NumValuesLoc = Lexer.getLoc();
4753   int64_t NumValues;
4754   if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4755     return true;
4756 
4757   if (NumValues < 0) {
4758     Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4759     return false;
4760   }
4761 
4762   if (parseToken(AsmToken::Comma,
4763                  "unexpected token in '" + Twine(IDVal) + "' directive"))
4764     return true;
4765 
4766   const MCExpr *Value;
4767   SMLoc ExprLoc = getLexer().getLoc();
4768   if (parseExpression(Value))
4769     return true;
4770 
4771   // Special case constant expressions to match code generator.
4772   if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4773     assert(Size <= 8 && "Invalid size");
4774     uint64_t IntValue = MCE->getValue();
4775     if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4776       return Error(ExprLoc, "literal value out of range for directive");
4777     for (uint64_t i = 0, e = NumValues; i != e; ++i)
4778       getStreamer().emitIntValue(IntValue, Size);
4779   } else {
4780     for (uint64_t i = 0, e = NumValues; i != e; ++i)
4781       getStreamer().emitValue(Value, Size, ExprLoc);
4782   }
4783 
4784   if (parseToken(AsmToken::EndOfStatement,
4785                  "unexpected token in '" + Twine(IDVal) + "' directive"))
4786     return true;
4787 
4788   return false;
4789 }
4790 
4791 /// parseDirectiveRealDCB
4792 /// ::= .dcb.{d, s} expression, expression
4793 bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
4794   SMLoc NumValuesLoc = Lexer.getLoc();
4795   int64_t NumValues;
4796   if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4797     return true;
4798 
4799   if (NumValues < 0) {
4800     Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4801     return false;
4802   }
4803 
4804   if (parseToken(AsmToken::Comma,
4805                  "unexpected token in '" + Twine(IDVal) + "' directive"))
4806     return true;
4807 
4808   APInt AsInt;
4809   if (parseRealValue(Semantics, AsInt))
4810     return true;
4811 
4812   if (parseToken(AsmToken::EndOfStatement,
4813                  "unexpected token in '" + Twine(IDVal) + "' directive"))
4814     return true;
4815 
4816   for (uint64_t i = 0, e = NumValues; i != e; ++i)
4817     getStreamer().emitIntValue(AsInt.getLimitedValue(),
4818                                AsInt.getBitWidth() / 8);
4819 
4820   return false;
4821 }
4822 
4823 /// parseDirectiveDS
4824 /// ::= .ds.{b, d, l, p, s, w, x} expression
4825 bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
4826   SMLoc NumValuesLoc = Lexer.getLoc();
4827   int64_t NumValues;
4828   if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4829     return true;
4830 
4831   if (NumValues < 0) {
4832     Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4833     return false;
4834   }
4835 
4836   if (parseToken(AsmToken::EndOfStatement,
4837                  "unexpected token in '" + Twine(IDVal) + "' directive"))
4838     return true;
4839 
4840   for (uint64_t i = 0, e = NumValues; i != e; ++i)
4841     getStreamer().emitFill(Size, 0);
4842 
4843   return false;
4844 }
4845 
4846 /// parseDirectiveLEB128
4847 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
4848 bool AsmParser::parseDirectiveLEB128(bool Signed) {
4849   if (checkForValidSection())
4850     return true;
4851 
4852   auto parseOp = [&]() -> bool {
4853     const MCExpr *Value;
4854     if (parseExpression(Value))
4855       return true;
4856     if (Signed)
4857       getStreamer().emitSLEB128Value(Value);
4858     else
4859       getStreamer().emitULEB128Value(Value);
4860     return false;
4861   };
4862 
4863   if (parseMany(parseOp))
4864     return addErrorSuffix(" in directive");
4865 
4866   return false;
4867 }
4868 
4869 /// parseDirectiveSymbolAttribute
4870 ///  ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
4871 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
4872   auto parseOp = [&]() -> bool {
4873     StringRef Name;
4874     SMLoc Loc = getTok().getLoc();
4875     if (parseIdentifier(Name))
4876       return Error(Loc, "expected identifier");
4877     MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4878 
4879     // Assembler local symbols don't make any sense here. Complain loudly.
4880     if (Sym->isTemporary())
4881       return Error(Loc, "non-local symbol required");
4882 
4883     if (!getStreamer().emitSymbolAttribute(Sym, Attr))
4884       return Error(Loc, "unable to emit symbol attribute");
4885     return false;
4886   };
4887 
4888   if (parseMany(parseOp))
4889     return addErrorSuffix(" in directive");
4890   return false;
4891 }
4892 
4893 /// parseDirectiveComm
4894 ///  ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
4895 bool AsmParser::parseDirectiveComm(bool IsLocal) {
4896   if (checkForValidSection())
4897     return true;
4898 
4899   SMLoc IDLoc = getLexer().getLoc();
4900   StringRef Name;
4901   if (parseIdentifier(Name))
4902     return TokError("expected identifier in directive");
4903 
4904   // Handle the identifier as the key symbol.
4905   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4906 
4907   if (getLexer().isNot(AsmToken::Comma))
4908     return TokError("unexpected token in directive");
4909   Lex();
4910 
4911   int64_t Size;
4912   SMLoc SizeLoc = getLexer().getLoc();
4913   if (parseAbsoluteExpression(Size))
4914     return true;
4915 
4916   int64_t Pow2Alignment = 0;
4917   SMLoc Pow2AlignmentLoc;
4918   if (getLexer().is(AsmToken::Comma)) {
4919     Lex();
4920     Pow2AlignmentLoc = getLexer().getLoc();
4921     if (parseAbsoluteExpression(Pow2Alignment))
4922       return true;
4923 
4924     LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4925     if (IsLocal && LCOMM == LCOMM::NoAlignment)
4926       return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4927 
4928     // If this target takes alignments in bytes (not log) validate and convert.
4929     if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4930         (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
4931       if (!isPowerOf2_64(Pow2Alignment))
4932         return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4933       Pow2Alignment = Log2_64(Pow2Alignment);
4934     }
4935   }
4936 
4937   if (parseToken(AsmToken::EndOfStatement,
4938                  "unexpected token in '.comm' or '.lcomm' directive"))
4939     return true;
4940 
4941   // NOTE: a size of zero for a .comm should create a undefined symbol
4942   // but a size of .lcomm creates a bss symbol of size zero.
4943   if (Size < 0)
4944     return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
4945                           "be less than zero");
4946 
4947   // NOTE: The alignment in the directive is a power of 2 value, the assembler
4948   // may internally end up wanting an alignment in bytes.
4949   // FIXME: Diagnose overflow.
4950   if (Pow2Alignment < 0)
4951     return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
4952                                    "alignment, can't be less than zero");
4953 
4954   Sym->redefineIfPossible();
4955   if (!Sym->isUndefined())
4956     return Error(IDLoc, "invalid symbol redefinition");
4957 
4958   // Create the Symbol as a common or local common with Size and Pow2Alignment
4959   if (IsLocal) {
4960     getStreamer().emitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4961     return false;
4962   }
4963 
4964   getStreamer().emitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4965   return false;
4966 }
4967 
4968 /// parseDirectiveAbort
4969 ///  ::= .abort [... message ...]
4970 bool AsmParser::parseDirectiveAbort() {
4971   // FIXME: Use loc from directive.
4972   SMLoc Loc = getLexer().getLoc();
4973 
4974   StringRef Str = parseStringToEndOfStatement();
4975   if (parseToken(AsmToken::EndOfStatement,
4976                  "unexpected token in '.abort' directive"))
4977     return true;
4978 
4979   if (Str.empty())
4980     return Error(Loc, ".abort detected. Assembly stopping.");
4981   else
4982     return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
4983   // FIXME: Actually abort assembly here.
4984 
4985   return false;
4986 }
4987 
4988 /// parseDirectiveInclude
4989 ///  ::= .include "filename"
4990 bool AsmParser::parseDirectiveInclude() {
4991   // Allow the strings to have escaped octal character sequence.
4992   std::string Filename;
4993   SMLoc IncludeLoc = getTok().getLoc();
4994 
4995   if (check(getTok().isNot(AsmToken::String),
4996             "expected string in '.include' directive") ||
4997       parseEscapedString(Filename) ||
4998       check(getTok().isNot(AsmToken::EndOfStatement),
4999             "unexpected token in '.include' directive") ||
5000       // Attempt to switch the lexer to the included file before consuming the
5001       // end of statement to avoid losing it when we switch.
5002       check(enterIncludeFile(Filename), IncludeLoc,
5003             "Could not find include file '" + Filename + "'"))
5004     return true;
5005 
5006   return false;
5007 }
5008 
5009 /// parseDirectiveIncbin
5010 ///  ::= .incbin "filename" [ , skip [ , count ] ]
5011 bool AsmParser::parseDirectiveIncbin() {
5012   // Allow the strings to have escaped octal character sequence.
5013   std::string Filename;
5014   SMLoc IncbinLoc = getTok().getLoc();
5015   if (check(getTok().isNot(AsmToken::String),
5016             "expected string in '.incbin' directive") ||
5017       parseEscapedString(Filename))
5018     return true;
5019 
5020   int64_t Skip = 0;
5021   const MCExpr *Count = nullptr;
5022   SMLoc SkipLoc, CountLoc;
5023   if (parseOptionalToken(AsmToken::Comma)) {
5024     // The skip expression can be omitted while specifying the count, e.g:
5025     //  .incbin "filename",,4
5026     if (getTok().isNot(AsmToken::Comma)) {
5027       if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
5028         return true;
5029     }
5030     if (parseOptionalToken(AsmToken::Comma)) {
5031       CountLoc = getTok().getLoc();
5032       if (parseExpression(Count))
5033         return true;
5034     }
5035   }
5036 
5037   if (parseToken(AsmToken::EndOfStatement,
5038                  "unexpected token in '.incbin' directive"))
5039     return true;
5040 
5041   if (check(Skip < 0, SkipLoc, "skip is negative"))
5042     return true;
5043 
5044   // Attempt to process the included file.
5045   if (processIncbinFile(Filename, Skip, Count, CountLoc))
5046     return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
5047   return false;
5048 }
5049 
5050 /// parseDirectiveIf
5051 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
5052 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
5053   TheCondStack.push_back(TheCondState);
5054   TheCondState.TheCond = AsmCond::IfCond;
5055   if (TheCondState.Ignore) {
5056     eatToEndOfStatement();
5057   } else {
5058     int64_t ExprValue;
5059     if (parseAbsoluteExpression(ExprValue) ||
5060         parseToken(AsmToken::EndOfStatement,
5061                    "unexpected token in '.if' directive"))
5062       return true;
5063 
5064     switch (DirKind) {
5065     default:
5066       llvm_unreachable("unsupported directive");
5067     case DK_IF:
5068     case DK_IFNE:
5069       break;
5070     case DK_IFEQ:
5071       ExprValue = ExprValue == 0;
5072       break;
5073     case DK_IFGE:
5074       ExprValue = ExprValue >= 0;
5075       break;
5076     case DK_IFGT:
5077       ExprValue = ExprValue > 0;
5078       break;
5079     case DK_IFLE:
5080       ExprValue = ExprValue <= 0;
5081       break;
5082     case DK_IFLT:
5083       ExprValue = ExprValue < 0;
5084       break;
5085     }
5086 
5087     TheCondState.CondMet = ExprValue;
5088     TheCondState.Ignore = !TheCondState.CondMet;
5089   }
5090 
5091   return false;
5092 }
5093 
5094 /// parseDirectiveIfb
5095 /// ::= .ifb string
5096 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
5097   TheCondStack.push_back(TheCondState);
5098   TheCondState.TheCond = AsmCond::IfCond;
5099 
5100   if (TheCondState.Ignore) {
5101     eatToEndOfStatement();
5102   } else {
5103     StringRef Str = parseStringToEndOfStatement();
5104 
5105     if (parseToken(AsmToken::EndOfStatement,
5106                    "unexpected token in '.ifb' directive"))
5107       return true;
5108 
5109     TheCondState.CondMet = ExpectBlank == Str.empty();
5110     TheCondState.Ignore = !TheCondState.CondMet;
5111   }
5112 
5113   return false;
5114 }
5115 
5116 /// parseDirectiveIfc
5117 /// ::= .ifc string1, string2
5118 /// ::= .ifnc string1, string2
5119 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
5120   TheCondStack.push_back(TheCondState);
5121   TheCondState.TheCond = AsmCond::IfCond;
5122 
5123   if (TheCondState.Ignore) {
5124     eatToEndOfStatement();
5125   } else {
5126     StringRef Str1 = parseStringToComma();
5127 
5128     if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
5129       return true;
5130 
5131     StringRef Str2 = parseStringToEndOfStatement();
5132 
5133     if (parseToken(AsmToken::EndOfStatement,
5134                    "unexpected token in '.ifc' directive"))
5135       return true;
5136 
5137     TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
5138     TheCondState.Ignore = !TheCondState.CondMet;
5139   }
5140 
5141   return false;
5142 }
5143 
5144 /// parseDirectiveIfeqs
5145 ///   ::= .ifeqs string1, string2
5146 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
5147   if (Lexer.isNot(AsmToken::String)) {
5148     if (ExpectEqual)
5149       return TokError("expected string parameter for '.ifeqs' directive");
5150     return TokError("expected string parameter for '.ifnes' directive");
5151   }
5152 
5153   StringRef String1 = getTok().getStringContents();
5154   Lex();
5155 
5156   if (Lexer.isNot(AsmToken::Comma)) {
5157     if (ExpectEqual)
5158       return TokError(
5159           "expected comma after first string for '.ifeqs' directive");
5160     return TokError("expected comma after first string for '.ifnes' directive");
5161   }
5162 
5163   Lex();
5164 
5165   if (Lexer.isNot(AsmToken::String)) {
5166     if (ExpectEqual)
5167       return TokError("expected string parameter for '.ifeqs' directive");
5168     return TokError("expected string parameter for '.ifnes' directive");
5169   }
5170 
5171   StringRef String2 = getTok().getStringContents();
5172   Lex();
5173 
5174   TheCondStack.push_back(TheCondState);
5175   TheCondState.TheCond = AsmCond::IfCond;
5176   TheCondState.CondMet = ExpectEqual == (String1 == String2);
5177   TheCondState.Ignore = !TheCondState.CondMet;
5178 
5179   return false;
5180 }
5181 
5182 /// parseDirectiveIfdef
5183 /// ::= .ifdef symbol
5184 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
5185   StringRef Name;
5186   TheCondStack.push_back(TheCondState);
5187   TheCondState.TheCond = AsmCond::IfCond;
5188 
5189   if (TheCondState.Ignore) {
5190     eatToEndOfStatement();
5191   } else {
5192     if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
5193         parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
5194       return true;
5195 
5196     MCSymbol *Sym = getContext().lookupSymbol(Name);
5197 
5198     if (expect_defined)
5199       TheCondState.CondMet = (Sym && !Sym->isUndefined(false));
5200     else
5201       TheCondState.CondMet = (!Sym || Sym->isUndefined(false));
5202     TheCondState.Ignore = !TheCondState.CondMet;
5203   }
5204 
5205   return false;
5206 }
5207 
5208 /// parseDirectiveElseIf
5209 /// ::= .elseif expression
5210 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
5211   if (TheCondState.TheCond != AsmCond::IfCond &&
5212       TheCondState.TheCond != AsmCond::ElseIfCond)
5213     return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
5214                                " .if or  an .elseif");
5215   TheCondState.TheCond = AsmCond::ElseIfCond;
5216 
5217   bool LastIgnoreState = false;
5218   if (!TheCondStack.empty())
5219     LastIgnoreState = TheCondStack.back().Ignore;
5220   if (LastIgnoreState || TheCondState.CondMet) {
5221     TheCondState.Ignore = true;
5222     eatToEndOfStatement();
5223   } else {
5224     int64_t ExprValue;
5225     if (parseAbsoluteExpression(ExprValue))
5226       return true;
5227 
5228     if (parseToken(AsmToken::EndOfStatement,
5229                    "unexpected token in '.elseif' directive"))
5230       return true;
5231 
5232     TheCondState.CondMet = ExprValue;
5233     TheCondState.Ignore = !TheCondState.CondMet;
5234   }
5235 
5236   return false;
5237 }
5238 
5239 /// parseDirectiveElse
5240 /// ::= .else
5241 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
5242   if (parseToken(AsmToken::EndOfStatement,
5243                  "unexpected token in '.else' directive"))
5244     return true;
5245 
5246   if (TheCondState.TheCond != AsmCond::IfCond &&
5247       TheCondState.TheCond != AsmCond::ElseIfCond)
5248     return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
5249                                " an .if or an .elseif");
5250   TheCondState.TheCond = AsmCond::ElseCond;
5251   bool LastIgnoreState = false;
5252   if (!TheCondStack.empty())
5253     LastIgnoreState = TheCondStack.back().Ignore;
5254   if (LastIgnoreState || TheCondState.CondMet)
5255     TheCondState.Ignore = true;
5256   else
5257     TheCondState.Ignore = false;
5258 
5259   return false;
5260 }
5261 
5262 /// parseDirectiveEnd
5263 /// ::= .end
5264 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
5265   if (parseToken(AsmToken::EndOfStatement,
5266                  "unexpected token in '.end' directive"))
5267     return true;
5268 
5269   while (Lexer.isNot(AsmToken::Eof))
5270     Lexer.Lex();
5271 
5272   return false;
5273 }
5274 
5275 /// parseDirectiveError
5276 ///   ::= .err
5277 ///   ::= .error [string]
5278 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
5279   if (!TheCondStack.empty()) {
5280     if (TheCondStack.back().Ignore) {
5281       eatToEndOfStatement();
5282       return false;
5283     }
5284   }
5285 
5286   if (!WithMessage)
5287     return Error(L, ".err encountered");
5288 
5289   StringRef Message = ".error directive invoked in source file";
5290   if (Lexer.isNot(AsmToken::EndOfStatement)) {
5291     if (Lexer.isNot(AsmToken::String))
5292       return TokError(".error argument must be a string");
5293 
5294     Message = getTok().getStringContents();
5295     Lex();
5296   }
5297 
5298   return Error(L, Message);
5299 }
5300 
5301 /// parseDirectiveWarning
5302 ///   ::= .warning [string]
5303 bool AsmParser::parseDirectiveWarning(SMLoc L) {
5304   if (!TheCondStack.empty()) {
5305     if (TheCondStack.back().Ignore) {
5306       eatToEndOfStatement();
5307       return false;
5308     }
5309   }
5310 
5311   StringRef Message = ".warning directive invoked in source file";
5312 
5313   if (!parseOptionalToken(AsmToken::EndOfStatement)) {
5314     if (Lexer.isNot(AsmToken::String))
5315       return TokError(".warning argument must be a string");
5316 
5317     Message = getTok().getStringContents();
5318     Lex();
5319     if (parseToken(AsmToken::EndOfStatement,
5320                    "expected end of statement in '.warning' directive"))
5321       return true;
5322   }
5323 
5324   return Warning(L, Message);
5325 }
5326 
5327 /// parseDirectiveEndIf
5328 /// ::= .endif
5329 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
5330   if (parseToken(AsmToken::EndOfStatement,
5331                  "unexpected token in '.endif' directive"))
5332     return true;
5333 
5334   if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
5335     return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5336                                "an .if or .else");
5337   if (!TheCondStack.empty()) {
5338     TheCondState = TheCondStack.back();
5339     TheCondStack.pop_back();
5340   }
5341 
5342   return false;
5343 }
5344 
5345 void AsmParser::initializeDirectiveKindMap() {
5346   /* Lookup will be done with the directive
5347    * converted to lower case, so all these
5348    * keys should be lower case.
5349    * (target specific directives are handled
5350    *  elsewhere)
5351    */
5352   DirectiveKindMap[".set"] = DK_SET;
5353   DirectiveKindMap[".equ"] = DK_EQU;
5354   DirectiveKindMap[".equiv"] = DK_EQUIV;
5355   DirectiveKindMap[".ascii"] = DK_ASCII;
5356   DirectiveKindMap[".asciz"] = DK_ASCIZ;
5357   DirectiveKindMap[".string"] = DK_STRING;
5358   DirectiveKindMap[".byte"] = DK_BYTE;
5359   DirectiveKindMap[".short"] = DK_SHORT;
5360   DirectiveKindMap[".value"] = DK_VALUE;
5361   DirectiveKindMap[".2byte"] = DK_2BYTE;
5362   DirectiveKindMap[".long"] = DK_LONG;
5363   DirectiveKindMap[".int"] = DK_INT;
5364   DirectiveKindMap[".4byte"] = DK_4BYTE;
5365   DirectiveKindMap[".quad"] = DK_QUAD;
5366   DirectiveKindMap[".8byte"] = DK_8BYTE;
5367   DirectiveKindMap[".octa"] = DK_OCTA;
5368   DirectiveKindMap[".single"] = DK_SINGLE;
5369   DirectiveKindMap[".float"] = DK_FLOAT;
5370   DirectiveKindMap[".double"] = DK_DOUBLE;
5371   DirectiveKindMap[".align"] = DK_ALIGN;
5372   DirectiveKindMap[".align32"] = DK_ALIGN32;
5373   DirectiveKindMap[".balign"] = DK_BALIGN;
5374   DirectiveKindMap[".balignw"] = DK_BALIGNW;
5375   DirectiveKindMap[".balignl"] = DK_BALIGNL;
5376   DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5377   DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5378   DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5379   DirectiveKindMap[".org"] = DK_ORG;
5380   DirectiveKindMap[".fill"] = DK_FILL;
5381   DirectiveKindMap[".zero"] = DK_ZERO;
5382   DirectiveKindMap[".extern"] = DK_EXTERN;
5383   DirectiveKindMap[".globl"] = DK_GLOBL;
5384   DirectiveKindMap[".global"] = DK_GLOBAL;
5385   DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5386   DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5387   DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5388   DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5389   DirectiveKindMap[".reference"] = DK_REFERENCE;
5390   DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5391   DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5392   DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
5393   DirectiveKindMap[".cold"] = DK_COLD;
5394   DirectiveKindMap[".comm"] = DK_COMM;
5395   DirectiveKindMap[".common"] = DK_COMMON;
5396   DirectiveKindMap[".lcomm"] = DK_LCOMM;
5397   DirectiveKindMap[".abort"] = DK_ABORT;
5398   DirectiveKindMap[".include"] = DK_INCLUDE;
5399   DirectiveKindMap[".incbin"] = DK_INCBIN;
5400   DirectiveKindMap[".code16"] = DK_CODE16;
5401   DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5402   DirectiveKindMap[".rept"] = DK_REPT;
5403   DirectiveKindMap[".rep"] = DK_REPT;
5404   DirectiveKindMap[".irp"] = DK_IRP;
5405   DirectiveKindMap[".irpc"] = DK_IRPC;
5406   DirectiveKindMap[".endr"] = DK_ENDR;
5407   DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5408   DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5409   DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5410   DirectiveKindMap[".if"] = DK_IF;
5411   DirectiveKindMap[".ifeq"] = DK_IFEQ;
5412   DirectiveKindMap[".ifge"] = DK_IFGE;
5413   DirectiveKindMap[".ifgt"] = DK_IFGT;
5414   DirectiveKindMap[".ifle"] = DK_IFLE;
5415   DirectiveKindMap[".iflt"] = DK_IFLT;
5416   DirectiveKindMap[".ifne"] = DK_IFNE;
5417   DirectiveKindMap[".ifb"] = DK_IFB;
5418   DirectiveKindMap[".ifnb"] = DK_IFNB;
5419   DirectiveKindMap[".ifc"] = DK_IFC;
5420   DirectiveKindMap[".ifeqs"] = DK_IFEQS;
5421   DirectiveKindMap[".ifnc"] = DK_IFNC;
5422   DirectiveKindMap[".ifnes"] = DK_IFNES;
5423   DirectiveKindMap[".ifdef"] = DK_IFDEF;
5424   DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5425   DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5426   DirectiveKindMap[".elseif"] = DK_ELSEIF;
5427   DirectiveKindMap[".else"] = DK_ELSE;
5428   DirectiveKindMap[".end"] = DK_END;
5429   DirectiveKindMap[".endif"] = DK_ENDIF;
5430   DirectiveKindMap[".skip"] = DK_SKIP;
5431   DirectiveKindMap[".space"] = DK_SPACE;
5432   DirectiveKindMap[".file"] = DK_FILE;
5433   DirectiveKindMap[".line"] = DK_LINE;
5434   DirectiveKindMap[".loc"] = DK_LOC;
5435   DirectiveKindMap[".stabs"] = DK_STABS;
5436   DirectiveKindMap[".cv_file"] = DK_CV_FILE;
5437   DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
5438   DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5439   DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
5440   DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
5441   DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
5442   DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
5443   DirectiveKindMap[".cv_string"] = DK_CV_STRING;
5444   DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5445   DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
5446   DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
5447   DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA;
5448   DirectiveKindMap[".sleb128"] = DK_SLEB128;
5449   DirectiveKindMap[".uleb128"] = DK_ULEB128;
5450   DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5451   DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5452   DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5453   DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5454   DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5455   DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5456   DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5457   DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5458   DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5459   DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5460   DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5461   DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5462   DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5463   DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5464   DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5465   DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
5466   DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
5467   DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5468   DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5469   DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
5470   DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
5471   DirectiveKindMap[".cfi_b_key_frame"] = DK_CFI_B_KEY_FRAME;
5472   DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5473   DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5474   DirectiveKindMap[".macro"] = DK_MACRO;
5475   DirectiveKindMap[".exitm"] = DK_EXITM;
5476   DirectiveKindMap[".endm"] = DK_ENDM;
5477   DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5478   DirectiveKindMap[".purgem"] = DK_PURGEM;
5479   DirectiveKindMap[".err"] = DK_ERR;
5480   DirectiveKindMap[".error"] = DK_ERROR;
5481   DirectiveKindMap[".warning"] = DK_WARNING;
5482   DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5483   DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
5484   DirectiveKindMap[".reloc"] = DK_RELOC;
5485   DirectiveKindMap[".dc"] = DK_DC;
5486   DirectiveKindMap[".dc.a"] = DK_DC_A;
5487   DirectiveKindMap[".dc.b"] = DK_DC_B;
5488   DirectiveKindMap[".dc.d"] = DK_DC_D;
5489   DirectiveKindMap[".dc.l"] = DK_DC_L;
5490   DirectiveKindMap[".dc.s"] = DK_DC_S;
5491   DirectiveKindMap[".dc.w"] = DK_DC_W;
5492   DirectiveKindMap[".dc.x"] = DK_DC_X;
5493   DirectiveKindMap[".dcb"] = DK_DCB;
5494   DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5495   DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5496   DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5497   DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5498   DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5499   DirectiveKindMap[".dcb.x"] = DK_DCB_X;
5500   DirectiveKindMap[".ds"] = DK_DS;
5501   DirectiveKindMap[".ds.b"] = DK_DS_B;
5502   DirectiveKindMap[".ds.d"] = DK_DS_D;
5503   DirectiveKindMap[".ds.l"] = DK_DS_L;
5504   DirectiveKindMap[".ds.p"] = DK_DS_P;
5505   DirectiveKindMap[".ds.s"] = DK_DS_S;
5506   DirectiveKindMap[".ds.w"] = DK_DS_W;
5507   DirectiveKindMap[".ds.x"] = DK_DS_X;
5508   DirectiveKindMap[".print"] = DK_PRINT;
5509   DirectiveKindMap[".addrsig"] = DK_ADDRSIG;
5510   DirectiveKindMap[".addrsig_sym"] = DK_ADDRSIG_SYM;
5511 }
5512 
5513 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
5514   AsmToken EndToken, StartToken = getTok();
5515 
5516   unsigned NestLevel = 0;
5517   while (true) {
5518     // Check whether we have reached the end of the file.
5519     if (getLexer().is(AsmToken::Eof)) {
5520       printError(DirectiveLoc, "no matching '.endr' in definition");
5521       return nullptr;
5522     }
5523 
5524     if (Lexer.is(AsmToken::Identifier) &&
5525         (getTok().getIdentifier() == ".rep" ||
5526          getTok().getIdentifier() == ".rept" ||
5527          getTok().getIdentifier() == ".irp" ||
5528          getTok().getIdentifier() == ".irpc")) {
5529       ++NestLevel;
5530     }
5531 
5532     // Otherwise, check whether we have reached the .endr.
5533     if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
5534       if (NestLevel == 0) {
5535         EndToken = getTok();
5536         Lex();
5537         if (Lexer.isNot(AsmToken::EndOfStatement)) {
5538           printError(getTok().getLoc(),
5539                      "unexpected token in '.endr' directive");
5540           return nullptr;
5541         }
5542         break;
5543       }
5544       --NestLevel;
5545     }
5546 
5547     // Otherwise, scan till the end of the statement.
5548     eatToEndOfStatement();
5549   }
5550 
5551   const char *BodyStart = StartToken.getLoc().getPointer();
5552   const char *BodyEnd = EndToken.getLoc().getPointer();
5553   StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5554 
5555   // We Are Anonymous.
5556   MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
5557   return &MacroLikeBodies.back();
5558 }
5559 
5560 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
5561                                          raw_svector_ostream &OS) {
5562   OS << ".endr\n";
5563 
5564   std::unique_ptr<MemoryBuffer> Instantiation =
5565       MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
5566 
5567   // Create the macro instantiation object and add to the current macro
5568   // instantiation stack.
5569   MacroInstantiation *MI = new MacroInstantiation{
5570       DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size()};
5571   ActiveMacros.push_back(MI);
5572 
5573   // Jump to the macro instantiation and prime the lexer.
5574   CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
5575   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
5576   Lex();
5577 }
5578 
5579 /// parseDirectiveRept
5580 ///   ::= .rep | .rept count
5581 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
5582   const MCExpr *CountExpr;
5583   SMLoc CountLoc = getTok().getLoc();
5584   if (parseExpression(CountExpr))
5585     return true;
5586 
5587   int64_t Count;
5588   if (!CountExpr->evaluateAsAbsolute(Count, getStreamer().getAssemblerPtr())) {
5589     return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5590   }
5591 
5592   if (check(Count < 0, CountLoc, "Count is negative") ||
5593       parseToken(AsmToken::EndOfStatement,
5594                  "unexpected token in '" + Dir + "' directive"))
5595     return true;
5596 
5597   // Lex the rept definition.
5598   MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5599   if (!M)
5600     return true;
5601 
5602   // Macro instantiation is lexical, unfortunately. We construct a new buffer
5603   // to hold the macro body with substitutions.
5604   SmallString<256> Buf;
5605   raw_svector_ostream OS(Buf);
5606   while (Count--) {
5607     // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5608     if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
5609       return true;
5610   }
5611   instantiateMacroLikeBody(M, DirectiveLoc, OS);
5612 
5613   return false;
5614 }
5615 
5616 /// parseDirectiveIrp
5617 /// ::= .irp symbol,values
5618 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
5619   MCAsmMacroParameter Parameter;
5620   MCAsmMacroArguments A;
5621   if (check(parseIdentifier(Parameter.Name),
5622             "expected identifier in '.irp' directive") ||
5623       parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5624       parseMacroArguments(nullptr, A) ||
5625       parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
5626     return true;
5627 
5628   // Lex the irp definition.
5629   MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5630   if (!M)
5631     return true;
5632 
5633   // Macro instantiation is lexical, unfortunately. We construct a new buffer
5634   // to hold the macro body with substitutions.
5635   SmallString<256> Buf;
5636   raw_svector_ostream OS(Buf);
5637 
5638   for (const MCAsmMacroArgument &Arg : A) {
5639     // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5640     // This is undocumented, but GAS seems to support it.
5641     if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5642       return true;
5643   }
5644 
5645   instantiateMacroLikeBody(M, DirectiveLoc, OS);
5646 
5647   return false;
5648 }
5649 
5650 /// parseDirectiveIrpc
5651 /// ::= .irpc symbol,values
5652 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
5653   MCAsmMacroParameter Parameter;
5654   MCAsmMacroArguments A;
5655 
5656   if (check(parseIdentifier(Parameter.Name),
5657             "expected identifier in '.irpc' directive") ||
5658       parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5659       parseMacroArguments(nullptr, A))
5660     return true;
5661 
5662   if (A.size() != 1 || A.front().size() != 1)
5663     return TokError("unexpected token in '.irpc' directive");
5664 
5665   // Eat the end of statement.
5666   if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5667     return true;
5668 
5669   // Lex the irpc definition.
5670   MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5671   if (!M)
5672     return true;
5673 
5674   // Macro instantiation is lexical, unfortunately. We construct a new buffer
5675   // to hold the macro body with substitutions.
5676   SmallString<256> Buf;
5677   raw_svector_ostream OS(Buf);
5678 
5679   StringRef Values = A.front().front().getString();
5680   for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
5681     MCAsmMacroArgument Arg;
5682     Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
5683 
5684     // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5685     // This is undocumented, but GAS seems to support it.
5686     if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5687       return true;
5688   }
5689 
5690   instantiateMacroLikeBody(M, DirectiveLoc, OS);
5691 
5692   return false;
5693 }
5694 
5695 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
5696   if (ActiveMacros.empty())
5697     return TokError("unmatched '.endr' directive");
5698 
5699   // The only .repl that should get here are the ones created by
5700   // instantiateMacroLikeBody.
5701   assert(getLexer().is(AsmToken::EndOfStatement));
5702 
5703   handleMacroExit();
5704   return false;
5705 }
5706 
5707 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
5708                                      size_t Len) {
5709   const MCExpr *Value;
5710   SMLoc ExprLoc = getLexer().getLoc();
5711   if (parseExpression(Value))
5712     return true;
5713   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5714   if (!MCE)
5715     return Error(ExprLoc, "unexpected expression in _emit");
5716   uint64_t IntValue = MCE->getValue();
5717   if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
5718     return Error(ExprLoc, "literal value out of range for directive");
5719 
5720   Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
5721   return false;
5722 }
5723 
5724 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
5725   const MCExpr *Value;
5726   SMLoc ExprLoc = getLexer().getLoc();
5727   if (parseExpression(Value))
5728     return true;
5729   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5730   if (!MCE)
5731     return Error(ExprLoc, "unexpected expression in align");
5732   uint64_t IntValue = MCE->getValue();
5733   if (!isPowerOf2_64(IntValue))
5734     return Error(ExprLoc, "literal value not a power of two greater then zero");
5735 
5736   Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
5737   return false;
5738 }
5739 
5740 bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
5741   const AsmToken StrTok = getTok();
5742   Lex();
5743   if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
5744     return Error(DirectiveLoc, "expected double quoted string after .print");
5745   if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5746     return true;
5747   llvm::outs() << StrTok.getStringContents() << '\n';
5748   return false;
5749 }
5750 
5751 bool AsmParser::parseDirectiveAddrsig() {
5752   getStreamer().emitAddrsig();
5753   return false;
5754 }
5755 
5756 bool AsmParser::parseDirectiveAddrsigSym() {
5757   StringRef Name;
5758   if (check(parseIdentifier(Name),
5759             "expected identifier in '.addrsig_sym' directive"))
5760     return true;
5761   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
5762   getStreamer().emitAddrsigSym(Sym);
5763   return false;
5764 }
5765 
5766 // We are comparing pointers, but the pointers are relative to a single string.
5767 // Thus, this should always be deterministic.
5768 static int rewritesSort(const AsmRewrite *AsmRewriteA,
5769                         const AsmRewrite *AsmRewriteB) {
5770   if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5771     return -1;
5772   if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5773     return 1;
5774 
5775   // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5776   // rewrite to the same location.  Make sure the SizeDirective rewrite is
5777   // performed first, then the Imm/ImmPrefix and finally the Input/Output.  This
5778   // ensures the sort algorithm is stable.
5779   if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5780       AsmRewritePrecedence[AsmRewriteB->Kind])
5781     return -1;
5782 
5783   if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5784       AsmRewritePrecedence[AsmRewriteB->Kind])
5785     return 1;
5786   llvm_unreachable("Unstable rewrite sort.");
5787 }
5788 
5789 bool AsmParser::parseMSInlineAsm(
5790     void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
5791     unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
5792     SmallVectorImpl<std::string> &Constraints,
5793     SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5794     const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
5795   SmallVector<void *, 4> InputDecls;
5796   SmallVector<void *, 4> OutputDecls;
5797   SmallVector<bool, 4> InputDeclsAddressOf;
5798   SmallVector<bool, 4> OutputDeclsAddressOf;
5799   SmallVector<std::string, 4> InputConstraints;
5800   SmallVector<std::string, 4> OutputConstraints;
5801   SmallVector<unsigned, 4> ClobberRegs;
5802 
5803   SmallVector<AsmRewrite, 4> AsmStrRewrites;
5804 
5805   // Prime the lexer.
5806   Lex();
5807 
5808   // While we have input, parse each statement.
5809   unsigned InputIdx = 0;
5810   unsigned OutputIdx = 0;
5811   while (getLexer().isNot(AsmToken::Eof)) {
5812     // Parse curly braces marking block start/end
5813     if (parseCurlyBlockScope(AsmStrRewrites))
5814       continue;
5815 
5816     ParseStatementInfo Info(&AsmStrRewrites);
5817     bool StatementErr = parseStatement(Info, &SI);
5818 
5819     if (StatementErr || Info.ParseError) {
5820       // Emit pending errors if any exist.
5821       printPendingErrors();
5822       return true;
5823     }
5824 
5825     // No pending error should exist here.
5826     assert(!hasPendingError() && "unexpected error from parseStatement");
5827 
5828     if (Info.Opcode == ~0U)
5829       continue;
5830 
5831     const MCInstrDesc &Desc = MII->get(Info.Opcode);
5832 
5833     // Build the list of clobbers, outputs and inputs.
5834     for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
5835       MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
5836 
5837       // Register operand.
5838       if (Operand.isReg() && !Operand.needAddressOf() &&
5839           !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
5840         unsigned NumDefs = Desc.getNumDefs();
5841         // Clobber.
5842         if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5843           ClobberRegs.push_back(Operand.getReg());
5844         continue;
5845       }
5846 
5847       // Expr/Input or Output.
5848       StringRef SymName = Operand.getSymName();
5849       if (SymName.empty())
5850         continue;
5851 
5852       void *OpDecl = Operand.getOpDecl();
5853       if (!OpDecl)
5854         continue;
5855 
5856       StringRef Constraint = Operand.getConstraint();
5857       if (Operand.isImm()) {
5858         // Offset as immediate
5859         if (Operand.isOffsetOfLocal())
5860           Constraint = "r";
5861         else
5862           Constraint = "i";
5863       }
5864 
5865       bool isOutput = (i == 1) && Desc.mayStore();
5866       SMLoc Start = SMLoc::getFromPointer(SymName.data());
5867       if (isOutput) {
5868         ++InputIdx;
5869         OutputDecls.push_back(OpDecl);
5870         OutputDeclsAddressOf.push_back(Operand.needAddressOf());
5871         OutputConstraints.push_back(("=" + Constraint).str());
5872         AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
5873       } else {
5874         InputDecls.push_back(OpDecl);
5875         InputDeclsAddressOf.push_back(Operand.needAddressOf());
5876         InputConstraints.push_back(Constraint.str());
5877         if (Desc.OpInfo[i - 1].isBranchTarget())
5878           AsmStrRewrites.emplace_back(AOK_CallInput, Start, SymName.size());
5879         else
5880           AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
5881       }
5882     }
5883 
5884     // Consider implicit defs to be clobbers.  Think of cpuid and push.
5885     ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5886                                 Desc.getNumImplicitDefs());
5887     ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
5888   }
5889 
5890   // Set the number of Outputs and Inputs.
5891   NumOutputs = OutputDecls.size();
5892   NumInputs = InputDecls.size();
5893 
5894   // Set the unique clobbers.
5895   array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5896   ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5897                     ClobberRegs.end());
5898   Clobbers.assign(ClobberRegs.size(), std::string());
5899   for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5900     raw_string_ostream OS(Clobbers[I]);
5901     IP->printRegName(OS, ClobberRegs[I]);
5902   }
5903 
5904   // Merge the various outputs and inputs.  Output are expected first.
5905   if (NumOutputs || NumInputs) {
5906     unsigned NumExprs = NumOutputs + NumInputs;
5907     OpDecls.resize(NumExprs);
5908     Constraints.resize(NumExprs);
5909     for (unsigned i = 0; i < NumOutputs; ++i) {
5910       OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
5911       Constraints[i] = OutputConstraints[i];
5912     }
5913     for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
5914       OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
5915       Constraints[j] = InputConstraints[i];
5916     }
5917   }
5918 
5919   // Build the IR assembly string.
5920   std::string AsmStringIR;
5921   raw_string_ostream OS(AsmStringIR);
5922   StringRef ASMString =
5923       SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5924   const char *AsmStart = ASMString.begin();
5925   const char *AsmEnd = ASMString.end();
5926   array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
5927   for (auto it = AsmStrRewrites.begin(); it != AsmStrRewrites.end(); ++it) {
5928     const AsmRewrite &AR = *it;
5929     // Check if this has already been covered by another rewrite...
5930     if (AR.Done)
5931       continue;
5932     AsmRewriteKind Kind = AR.Kind;
5933 
5934     const char *Loc = AR.Loc.getPointer();
5935     assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
5936 
5937     // Emit everything up to the immediate/expression.
5938     if (unsigned Len = Loc - AsmStart)
5939       OS << StringRef(AsmStart, Len);
5940 
5941     // Skip the original expression.
5942     if (Kind == AOK_Skip) {
5943       AsmStart = Loc + AR.Len;
5944       continue;
5945     }
5946 
5947     unsigned AdditionalSkip = 0;
5948     // Rewrite expressions in $N notation.
5949     switch (Kind) {
5950     default:
5951       break;
5952     case AOK_IntelExpr:
5953       assert(AR.IntelExp.isValid() && "cannot write invalid intel expression");
5954       if (AR.IntelExp.NeedBracs)
5955         OS << "[";
5956       if (AR.IntelExp.hasBaseReg())
5957         OS << AR.IntelExp.BaseReg;
5958       if (AR.IntelExp.hasIndexReg())
5959         OS << (AR.IntelExp.hasBaseReg() ? " + " : "")
5960            << AR.IntelExp.IndexReg;
5961       if (AR.IntelExp.Scale > 1)
5962         OS << " * $$" << AR.IntelExp.Scale;
5963       if (AR.IntelExp.hasOffset()) {
5964         if (AR.IntelExp.hasRegs())
5965           OS << " + ";
5966         // Fuse this rewrite with a rewrite of the offset name, if present.
5967         StringRef OffsetName = AR.IntelExp.OffsetName;
5968         SMLoc OffsetLoc = SMLoc::getFromPointer(AR.IntelExp.OffsetName.data());
5969         size_t OffsetLen = OffsetName.size();
5970         auto rewrite_it = std::find_if(
5971             it, AsmStrRewrites.end(), [&](const AsmRewrite &FusingAR) {
5972               return FusingAR.Loc == OffsetLoc && FusingAR.Len == OffsetLen &&
5973                      (FusingAR.Kind == AOK_Input ||
5974                       FusingAR.Kind == AOK_CallInput);
5975             });
5976         if (rewrite_it == AsmStrRewrites.end()) {
5977           OS << "offset " << OffsetName;
5978         } else if (rewrite_it->Kind == AOK_CallInput) {
5979           OS << "${" << InputIdx++ << ":P}";
5980           rewrite_it->Done = true;
5981         } else {
5982           OS << '$' << InputIdx++;
5983           rewrite_it->Done = true;
5984         }
5985       }
5986       if (AR.IntelExp.Imm || AR.IntelExp.emitImm())
5987         OS << (AR.IntelExp.emitImm() ? "$$" : " + $$") << AR.IntelExp.Imm;
5988       if (AR.IntelExp.NeedBracs)
5989         OS << "]";
5990       break;
5991     case AOK_Label:
5992       OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
5993       break;
5994     case AOK_Input:
5995       OS << '$' << InputIdx++;
5996       break;
5997     case AOK_CallInput:
5998       OS << "${" << InputIdx++ << ":P}";
5999       break;
6000     case AOK_Output:
6001       OS << '$' << OutputIdx++;
6002       break;
6003     case AOK_SizeDirective:
6004       switch (AR.Val) {
6005       default: break;
6006       case 8:  OS << "byte ptr "; break;
6007       case 16: OS << "word ptr "; break;
6008       case 32: OS << "dword ptr "; break;
6009       case 64: OS << "qword ptr "; break;
6010       case 80: OS << "xword ptr "; break;
6011       case 128: OS << "xmmword ptr "; break;
6012       case 256: OS << "ymmword ptr "; break;
6013       }
6014       break;
6015     case AOK_Emit:
6016       OS << ".byte";
6017       break;
6018     case AOK_Align: {
6019       // MS alignment directives are measured in bytes. If the native assembler
6020       // measures alignment in bytes, we can pass it straight through.
6021       OS << ".align";
6022       if (getContext().getAsmInfo()->getAlignmentIsInBytes())
6023         break;
6024 
6025       // Alignment is in log2 form, so print that instead and skip the original
6026       // immediate.
6027       unsigned Val = AR.Val;
6028       OS << ' ' << Val;
6029       assert(Val < 10 && "Expected alignment less then 2^10.");
6030       AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
6031       break;
6032     }
6033     case AOK_EVEN:
6034       OS << ".even";
6035       break;
6036     case AOK_EndOfStatement:
6037       OS << "\n\t";
6038       break;
6039     }
6040 
6041     // Skip the original expression.
6042     AsmStart = Loc + AR.Len + AdditionalSkip;
6043   }
6044 
6045   // Emit the remainder of the asm string.
6046   if (AsmStart != AsmEnd)
6047     OS << StringRef(AsmStart, AsmEnd - AsmStart);
6048 
6049   AsmString = OS.str();
6050   return false;
6051 }
6052 
6053 namespace llvm {
6054 namespace MCParserUtils {
6055 
6056 /// Returns whether the given symbol is used anywhere in the given expression,
6057 /// or subexpressions.
6058 static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
6059   switch (Value->getKind()) {
6060   case MCExpr::Binary: {
6061     const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
6062     return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
6063            isSymbolUsedInExpression(Sym, BE->getRHS());
6064   }
6065   case MCExpr::Target:
6066   case MCExpr::Constant:
6067     return false;
6068   case MCExpr::SymbolRef: {
6069     const MCSymbol &S =
6070         static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
6071     if (S.isVariable())
6072       return isSymbolUsedInExpression(Sym, S.getVariableValue());
6073     return &S == Sym;
6074   }
6075   case MCExpr::Unary:
6076     return isSymbolUsedInExpression(
6077         Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
6078   }
6079 
6080   llvm_unreachable("Unknown expr kind!");
6081 }
6082 
6083 bool parseAssignmentExpression(StringRef Name, bool allow_redef,
6084                                MCAsmParser &Parser, MCSymbol *&Sym,
6085                                const MCExpr *&Value) {
6086 
6087   // FIXME: Use better location, we should use proper tokens.
6088   SMLoc EqualLoc = Parser.getTok().getLoc();
6089   if (Parser.parseExpression(Value))
6090     return Parser.TokError("missing expression");
6091 
6092   // Note: we don't count b as used in "a = b". This is to allow
6093   // a = b
6094   // b = c
6095 
6096   if (Parser.parseToken(AsmToken::EndOfStatement))
6097     return true;
6098 
6099   // Validate that the LHS is allowed to be a variable (either it has not been
6100   // used as a symbol, or it is an absolute symbol).
6101   Sym = Parser.getContext().lookupSymbol(Name);
6102   if (Sym) {
6103     // Diagnose assignment to a label.
6104     //
6105     // FIXME: Diagnostics. Note the location of the definition as a label.
6106     // FIXME: Diagnose assignment to protected identifier (e.g., register name).
6107     if (isSymbolUsedInExpression(Sym, Value))
6108       return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
6109     else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
6110              !Sym->isVariable())
6111       ; // Allow redefinitions of undefined symbols only used in directives.
6112     else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
6113       ; // Allow redefinitions of variables that haven't yet been used.
6114     else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
6115       return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
6116     else if (!Sym->isVariable())
6117       return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
6118     else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
6119       return Parser.Error(EqualLoc,
6120                           "invalid reassignment of non-absolute variable '" +
6121                               Name + "'");
6122   } else if (Name == ".") {
6123     Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
6124     return false;
6125   } else
6126     Sym = Parser.getContext().getOrCreateSymbol(Name);
6127 
6128   Sym->setRedefinable(allow_redef);
6129 
6130   return false;
6131 }
6132 
6133 } // end namespace MCParserUtils
6134 } // end namespace llvm
6135 
6136 /// Create an MCAsmParser instance.
6137 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
6138                                      MCStreamer &Out, const MCAsmInfo &MAI,
6139                                      unsigned CB) {
6140   return new AsmParser(SM, C, Out, MAI, CB);
6141 }
6142