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