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