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