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