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