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