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