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