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