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