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