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