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