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