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