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