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