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