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