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