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