AsmParser: Add support for .ifc and .ifnc directives.
[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/MCParser/AsmCond.h"
23 #include "llvm/MC/MCParser/AsmLexer.h"
24 #include "llvm/MC/MCParser/MCAsmParser.h"
25 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
26 #include "llvm/MC/MCRegisterInfo.h"
27 #include "llvm/MC/MCSectionMachO.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/MC/MCTargetAsmParser.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <cctype>
38 #include <vector>
39 using namespace llvm;
40
41 static cl::opt<bool>
42 FatalAssemblerWarnings("fatal-assembler-warnings",
43                        cl::desc("Consider warnings as error"));
44
45 namespace {
46
47 /// \brief Helper class for tracking macro definitions.
48 struct Macro {
49   StringRef Name;
50   StringRef Body;
51   std::vector<StringRef> Parameters;
52
53 public:
54   Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
55     Name(N), Body(B), Parameters(P) {}
56 };
57
58 /// \brief Helper class for storing information about an active macro
59 /// instantiation.
60 struct MacroInstantiation {
61   /// The macro being instantiated.
62   const Macro *TheMacro;
63
64   /// The macro instantiation with substitutions.
65   MemoryBuffer *Instantiation;
66
67   /// The location of the instantiation.
68   SMLoc InstantiationLoc;
69
70   /// The location where parsing should resume upon instantiation completion.
71   SMLoc ExitLoc;
72
73 public:
74   MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
75                      MemoryBuffer *I);
76 };
77
78 /// \brief The concrete assembly parser instance.
79 class AsmParser : public MCAsmParser {
80   friend class GenericAsmParser;
81
82   AsmParser(const AsmParser &);   // DO NOT IMPLEMENT
83   void operator=(const AsmParser &);  // DO NOT IMPLEMENT
84 private:
85   AsmLexer Lexer;
86   MCContext &Ctx;
87   MCStreamer &Out;
88   const MCAsmInfo &MAI;
89   SourceMgr &SrcMgr;
90   SourceMgr::DiagHandlerTy SavedDiagHandler;
91   void *SavedDiagContext;
92   MCAsmParserExtension *GenericParser;
93   MCAsmParserExtension *PlatformParser;
94
95   /// This is the current buffer index we're lexing from as managed by the
96   /// SourceMgr object.
97   int CurBuffer;
98
99   AsmCond TheCondState;
100   std::vector<AsmCond> TheCondStack;
101
102   /// DirectiveMap - This is a table handlers for directives.  Each handler is
103   /// invoked after the directive identifier is read and is responsible for
104   /// parsing and validating the rest of the directive.  The handler is passed
105   /// in the directive name and the location of the directive keyword.
106   StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
107
108   /// MacroMap - Map of currently defined macros.
109   StringMap<Macro*> MacroMap;
110
111   /// ActiveMacros - Stack of active macro instantiations.
112   std::vector<MacroInstantiation*> ActiveMacros;
113
114   /// Boolean tracking whether macro substitution is enabled.
115   unsigned MacrosEnabled : 1;
116
117   /// Flag tracking whether any errors have been encountered.
118   unsigned HadError : 1;
119
120   /// The values from the last parsed cpp hash file line comment if any.
121   StringRef CppHashFilename;
122   int64_t CppHashLineNumber;
123   SMLoc CppHashLoc;
124
125   /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
126   unsigned AssemblerDialect;
127
128 public:
129   AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
130             const MCAsmInfo &MAI);
131   ~AsmParser();
132
133   virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
134
135   void AddDirectiveHandler(MCAsmParserExtension *Object,
136                            StringRef Directive,
137                            DirectiveHandler Handler) {
138     DirectiveMap[Directive] = std::make_pair(Object, Handler);
139   }
140
141 public:
142   /// @name MCAsmParser Interface
143   /// {
144
145   virtual SourceMgr &getSourceManager() { return SrcMgr; }
146   virtual MCAsmLexer &getLexer() { return Lexer; }
147   virtual MCContext &getContext() { return Ctx; }
148   virtual MCStreamer &getStreamer() { return Out; }
149   virtual unsigned getAssemblerDialect() { 
150     if (AssemblerDialect == ~0U)
151       return MAI.getAssemblerDialect(); 
152     else
153       return AssemblerDialect;
154   }
155   virtual void setAssemblerDialect(unsigned i) {
156     AssemblerDialect = i;
157   }
158
159   virtual bool Warning(SMLoc L, const Twine &Msg,
160                        ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
161   virtual bool Error(SMLoc L, const Twine &Msg,
162                      ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
163
164   const AsmToken &Lex();
165
166   bool ParseExpression(const MCExpr *&Res);
167   virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
168   virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
169   virtual bool ParseAbsoluteExpression(int64_t &Res);
170
171   /// }
172
173 private:
174   void CheckForValidSection();
175
176   bool ParseStatement();
177   void EatToEndOfLine();
178   bool ParseCppHashLineFilenameComment(const SMLoc &L);
179
180   bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
181   bool expandMacro(SmallString<256> &Buf, StringRef Body,
182                    const std::vector<StringRef> &Parameters,
183                    const std::vector<std::vector<AsmToken> > &A,
184                    const SMLoc &L);
185   void HandleMacroExit();
186
187   void PrintMacroInstantiations();
188   void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
189                     ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
190     SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
191   }
192   static void DiagHandler(const SMDiagnostic &Diag, void *Context);
193
194   /// EnterIncludeFile - Enter the specified file. This returns true on failure.
195   bool EnterIncludeFile(const std::string &Filename);
196   /// ProcessIncbinFile - Process the specified file for the .incbin directive.
197   /// This returns true on failure.
198   bool ProcessIncbinFile(const std::string &Filename);
199
200   /// \brief Reset the current lexer position to that given by \arg Loc. The
201   /// current token is not set; clients should ensure Lex() is called
202   /// subsequently.
203   void JumpToLoc(SMLoc Loc);
204
205   void EatToEndOfStatement();
206
207   /// \brief Parse up to the end of statement and a return the contents from the
208   /// current token until the end of the statement; the current token on exit
209   /// will be either the EndOfStatement or EOF.
210   StringRef ParseStringToEndOfStatement();
211
212   /// \brief Parse until the end of a statement or a comma is encountered,
213   /// return the contents from the current token up to the end or comma.
214   StringRef ParseStringToComma();
215
216   bool ParseAssignment(StringRef Name, bool allow_redef);
217
218   bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
219   bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
220   bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
221   bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
222
223   /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
224   /// and set \arg Res to the identifier contents.
225   bool ParseIdentifier(StringRef &Res);
226
227   // Directive Parsing.
228
229  // ".ascii", ".asciiz", ".string"
230   bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
231   bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
232   bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
233   bool ParseDirectiveFill(); // ".fill"
234   bool ParseDirectiveSpace(); // ".space"
235   bool ParseDirectiveZero(); // ".zero"
236   bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
237   bool ParseDirectiveOrg(); // ".org"
238   // ".align{,32}", ".p2align{,w,l}"
239   bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
240
241   /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
242   /// accepts a single symbol (which should be a label or an external).
243   bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
244
245   bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
246
247   bool ParseDirectiveAbort(); // ".abort"
248   bool ParseDirectiveInclude(); // ".include"
249   bool ParseDirectiveIncbin(); // ".incbin"
250
251   bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
252   // ".ifb" or ".ifnb", depending on ExpectBlank.
253   bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
254   // ".ifc" or ".ifnc", depending on ExpectEqual.
255   bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
256   // ".ifdef" or ".ifndef", depending on expect_defined
257   bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
258   bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
259   bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
260   bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
261
262   /// ParseEscapedString - Parse the current token as a string which may include
263   /// escaped characters and return the string contents.
264   bool ParseEscapedString(std::string &Data);
265
266   const MCExpr *ApplyModifierToExpr(const MCExpr *E,
267                                     MCSymbolRefExpr::VariantKind Variant);
268 };
269
270 /// \brief Generic implementations of directive handling, etc. which is shared
271 /// (or the default, at least) for all assembler parser.
272 class GenericAsmParser : public MCAsmParserExtension {
273   template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
274   void AddDirectiveHandler(StringRef Directive) {
275     getParser().AddDirectiveHandler(this, Directive,
276                                     HandleDirective<GenericAsmParser, Handler>);
277   }
278 public:
279   GenericAsmParser() {}
280
281   AsmParser &getParser() {
282     return (AsmParser&) this->MCAsmParserExtension::getParser();
283   }
284
285   virtual void Initialize(MCAsmParser &Parser) {
286     // Call the base implementation.
287     this->MCAsmParserExtension::Initialize(Parser);
288
289     // Debugging directives.
290     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
291     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
292     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
293     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
294
295     // CFI directives.
296     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
297                                                                ".cfi_sections");
298     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
299                                                               ".cfi_startproc");
300     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
301                                                                 ".cfi_endproc");
302     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
303                                                          ".cfi_def_cfa");
304     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
305                                                          ".cfi_def_cfa_offset");
306     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
307                                                       ".cfi_adjust_cfa_offset");
308     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
309                                                        ".cfi_def_cfa_register");
310     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
311                                                                  ".cfi_offset");
312     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
313                                                              ".cfi_rel_offset");
314     AddDirectiveHandler<
315      &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
316     AddDirectiveHandler<
317             &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
318     AddDirectiveHandler<
319       &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
320     AddDirectiveHandler<
321       &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
322     AddDirectiveHandler<
323       &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
324     AddDirectiveHandler<
325       &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
326     AddDirectiveHandler<
327       &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
328     AddDirectiveHandler<
329       &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
330
331     // Macro directives.
332     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
333       ".macros_on");
334     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
335       ".macros_off");
336     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
337     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
338     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
339
340     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
341     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
342   }
343
344   bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
345
346   bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
347   bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
348   bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
349   bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
350   bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
351   bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
352   bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
353   bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
354   bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
355   bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
356   bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
357   bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
358   bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
359   bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
360   bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
361   bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
362   bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
363   bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
364   bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
365   bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
366
367   bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
368   bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
369   bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
370
371   bool ParseDirectiveLEB128(StringRef, SMLoc);
372 };
373
374 }
375
376 namespace llvm {
377
378 extern MCAsmParserExtension *createDarwinAsmParser();
379 extern MCAsmParserExtension *createELFAsmParser();
380 extern MCAsmParserExtension *createCOFFAsmParser();
381
382 }
383
384 enum { DEFAULT_ADDRSPACE = 0 };
385
386 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
387                      MCStreamer &_Out, const MCAsmInfo &_MAI)
388   : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
389     GenericParser(new GenericAsmParser), PlatformParser(0),
390     CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0), 
391     AssemblerDialect(~0U) {
392   // Save the old handler.
393   SavedDiagHandler = SrcMgr.getDiagHandler();
394   SavedDiagContext = SrcMgr.getDiagContext();
395   // Set our own handler which calls the saved handler.
396   SrcMgr.setDiagHandler(DiagHandler, this);
397   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
398
399   // Initialize the generic parser.
400   GenericParser->Initialize(*this);
401
402   // Initialize the platform / file format parser.
403   //
404   // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
405   // created.
406   if (_MAI.hasMicrosoftFastStdCallMangling()) {
407     PlatformParser = createCOFFAsmParser();
408     PlatformParser->Initialize(*this);
409   } else if (_MAI.hasSubsectionsViaSymbols()) {
410     PlatformParser = createDarwinAsmParser();
411     PlatformParser->Initialize(*this);
412   } else {
413     PlatformParser = createELFAsmParser();
414     PlatformParser->Initialize(*this);
415   }
416 }
417
418 AsmParser::~AsmParser() {
419   assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
420
421   // Destroy any macros.
422   for (StringMap<Macro*>::iterator it = MacroMap.begin(),
423          ie = MacroMap.end(); it != ie; ++it)
424     delete it->getValue();
425
426   delete PlatformParser;
427   delete GenericParser;
428 }
429
430 void AsmParser::PrintMacroInstantiations() {
431   // Print the active macro instantiation stack.
432   for (std::vector<MacroInstantiation*>::const_reverse_iterator
433          it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
434     PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
435                  "while in macro instantiation");
436 }
437
438 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
439   if (FatalAssemblerWarnings)
440     return Error(L, Msg, Ranges);
441   PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
442   PrintMacroInstantiations();
443   return false;
444 }
445
446 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
447   HadError = true;
448   PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
449   PrintMacroInstantiations();
450   return true;
451 }
452
453 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
454   std::string IncludedFile;
455   int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
456   if (NewBuf == -1)
457     return true;
458
459   CurBuffer = NewBuf;
460
461   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
462
463   return false;
464 }
465
466 /// Process the specified .incbin file by seaching for it in the include paths
467 /// then just emiting the byte contents of the file to the streamer. This 
468 /// returns true on failure.
469 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
470   std::string IncludedFile;
471   int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
472   if (NewBuf == -1)
473     return true;
474
475   // Pick up the bytes from the file and emit them.
476   getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
477                           DEFAULT_ADDRSPACE);
478   return false;
479 }
480
481 void AsmParser::JumpToLoc(SMLoc Loc) {
482   CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
483   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
484 }
485
486 const AsmToken &AsmParser::Lex() {
487   const AsmToken *tok = &Lexer.Lex();
488
489   if (tok->is(AsmToken::Eof)) {
490     // If this is the end of an included file, pop the parent file off the
491     // include stack.
492     SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
493     if (ParentIncludeLoc != SMLoc()) {
494       JumpToLoc(ParentIncludeLoc);
495       tok = &Lexer.Lex();
496     }
497   }
498
499   if (tok->is(AsmToken::Error))
500     Error(Lexer.getErrLoc(), Lexer.getErr());
501
502   return *tok;
503 }
504
505 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
506   // Create the initial section, if requested.
507   if (!NoInitialTextSection)
508     Out.InitSections();
509
510   // Prime the lexer.
511   Lex();
512
513   HadError = false;
514   AsmCond StartingCondState = TheCondState;
515
516   // If we are generating dwarf for assembly source files save the initial text
517   // section and generate a .file directive.
518   if (getContext().getGenDwarfForAssembly()) {
519     getContext().setGenDwarfSection(getStreamer().getCurrentSection());
520     MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
521     getStreamer().EmitLabel(SectionStartSym);
522     getContext().setGenDwarfSectionStartSym(SectionStartSym);
523     getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
524       StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
525   }
526
527   // While we have input, parse each statement.
528   while (Lexer.isNot(AsmToken::Eof)) {
529     if (!ParseStatement()) continue;
530
531     // We had an error, validate that one was emitted and recover by skipping to
532     // the next line.
533     assert(HadError && "Parse statement returned an error, but none emitted!");
534     EatToEndOfStatement();
535   }
536
537   if (TheCondState.TheCond != StartingCondState.TheCond ||
538       TheCondState.Ignore != StartingCondState.Ignore)
539     return TokError("unmatched .ifs or .elses");
540
541   // Check to see there are no empty DwarfFile slots.
542   const std::vector<MCDwarfFile *> &MCDwarfFiles =
543     getContext().getMCDwarfFiles();
544   for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
545     if (!MCDwarfFiles[i])
546       TokError("unassigned file number: " + Twine(i) + " for .file directives");
547   }
548
549   // Check to see that all assembler local symbols were actually defined.
550   // Targets that don't do subsections via symbols may not want this, though,
551   // so conservatively exclude them. Only do this if we're finalizing, though,
552   // as otherwise we won't necessarilly have seen everything yet.
553   if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
554     const MCContext::SymbolTable &Symbols = getContext().getSymbols();
555     for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
556          e = Symbols.end();
557          i != e; ++i) {
558       MCSymbol *Sym = i->getValue();
559       // Variable symbols may not be marked as defined, so check those
560       // explicitly. If we know it's a variable, we have a definition for
561       // the purposes of this check.
562       if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
563         // FIXME: We would really like to refer back to where the symbol was
564         // first referenced for a source location. We need to add something
565         // to track that. Currently, we just point to the end of the file.
566         PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
567                      "assembler local symbol '" + Sym->getName() +
568                      "' not defined");
569     }
570   }
571
572
573   // Finalize the output stream if there are no errors and if the client wants
574   // us to.
575   if (!HadError && !NoFinalize)
576     Out.Finish();
577
578   return HadError;
579 }
580
581 void AsmParser::CheckForValidSection() {
582   if (!getStreamer().getCurrentSection()) {
583     TokError("expected section directive before assembly directive");
584     Out.SwitchSection(Ctx.getMachOSection(
585                         "__TEXT", "__text",
586                         MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
587                         0, SectionKind::getText()));
588   }
589 }
590
591 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
592 void AsmParser::EatToEndOfStatement() {
593   while (Lexer.isNot(AsmToken::EndOfStatement) &&
594          Lexer.isNot(AsmToken::Eof))
595     Lex();
596
597   // Eat EOL.
598   if (Lexer.is(AsmToken::EndOfStatement))
599     Lex();
600 }
601
602 StringRef AsmParser::ParseStringToEndOfStatement() {
603   const char *Start = getTok().getLoc().getPointer();
604
605   while (Lexer.isNot(AsmToken::EndOfStatement) &&
606          Lexer.isNot(AsmToken::Eof))
607     Lex();
608
609   const char *End = getTok().getLoc().getPointer();
610   return StringRef(Start, End - Start);
611 }
612
613 StringRef AsmParser::ParseStringToComma() {
614   const char *Start = getTok().getLoc().getPointer();
615
616   while (Lexer.isNot(AsmToken::EndOfStatement) &&
617          Lexer.isNot(AsmToken::Comma) &&
618          Lexer.isNot(AsmToken::Eof))
619     Lex();
620
621   const char *End = getTok().getLoc().getPointer();
622   return StringRef(Start, End - Start);
623 }
624
625 /// ParseParenExpr - Parse a paren expression and return it.
626 /// NOTE: This assumes the leading '(' has already been consumed.
627 ///
628 /// parenexpr ::= expr)
629 ///
630 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
631   if (ParseExpression(Res)) return true;
632   if (Lexer.isNot(AsmToken::RParen))
633     return TokError("expected ')' in parentheses expression");
634   EndLoc = Lexer.getLoc();
635   Lex();
636   return false;
637 }
638
639 /// ParseBracketExpr - Parse a bracket expression and return it.
640 /// NOTE: This assumes the leading '[' has already been consumed.
641 ///
642 /// bracketexpr ::= expr]
643 ///
644 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
645   if (ParseExpression(Res)) return true;
646   if (Lexer.isNot(AsmToken::RBrac))
647     return TokError("expected ']' in brackets expression");
648   EndLoc = Lexer.getLoc();
649   Lex();
650   return false;
651 }
652
653 /// ParsePrimaryExpr - Parse a primary expression and return it.
654 ///  primaryexpr ::= (parenexpr
655 ///  primaryexpr ::= symbol
656 ///  primaryexpr ::= number
657 ///  primaryexpr ::= '.'
658 ///  primaryexpr ::= ~,+,- primaryexpr
659 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
660   switch (Lexer.getKind()) {
661   default:
662     return TokError("unknown token in expression");
663   // If we have an error assume that we've already handled it.
664   case AsmToken::Error:
665     return true;
666   case AsmToken::Exclaim:
667     Lex(); // Eat the operator.
668     if (ParsePrimaryExpr(Res, EndLoc))
669       return true;
670     Res = MCUnaryExpr::CreateLNot(Res, getContext());
671     return false;
672   case AsmToken::Dollar:
673   case AsmToken::String:
674   case AsmToken::Identifier: {
675     EndLoc = Lexer.getLoc();
676
677     StringRef Identifier;
678     if (ParseIdentifier(Identifier))
679       return true;
680
681     // This is a symbol reference.
682     std::pair<StringRef, StringRef> Split = Identifier.split('@');
683     MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
684
685     // Lookup the symbol variant if used.
686     MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
687     if (Split.first.size() != Identifier.size()) {
688       Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
689       if (Variant == MCSymbolRefExpr::VK_Invalid) {
690         Variant = MCSymbolRefExpr::VK_None;
691         return TokError("invalid variant '" + Split.second + "'");
692       }
693     }
694
695     // If this is an absolute variable reference, substitute it now to preserve
696     // semantics in the face of reassignment.
697     if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
698       if (Variant)
699         return Error(EndLoc, "unexpected modifier on variable reference");
700
701       Res = Sym->getVariableValue();
702       return false;
703     }
704
705     // Otherwise create a symbol ref.
706     Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
707     return false;
708   }
709   case AsmToken::Integer: {
710     SMLoc Loc = getTok().getLoc();
711     int64_t IntVal = getTok().getIntVal();
712     Res = MCConstantExpr::Create(IntVal, getContext());
713     EndLoc = Lexer.getLoc();
714     Lex(); // Eat token.
715     // Look for 'b' or 'f' following an Integer as a directional label
716     if (Lexer.getKind() == AsmToken::Identifier) {
717       StringRef IDVal = getTok().getString();
718       if (IDVal == "f" || IDVal == "b"){
719         MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
720                                                       IDVal == "f" ? 1 : 0);
721         Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
722                                       getContext());
723         if(IDVal == "b" && Sym->isUndefined())
724           return Error(Loc, "invalid reference to undefined symbol");
725         EndLoc = Lexer.getLoc();
726         Lex(); // Eat identifier.
727       }
728     }
729     return false;
730   }
731   case AsmToken::Real: {
732     APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
733     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
734     Res = MCConstantExpr::Create(IntVal, getContext());
735     Lex(); // Eat token.
736     return false;
737   }
738   case AsmToken::Dot: {
739     // This is a '.' reference, which references the current PC.  Emit a
740     // temporary label to the streamer and refer to it.
741     MCSymbol *Sym = Ctx.CreateTempSymbol();
742     Out.EmitLabel(Sym);
743     Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
744     EndLoc = Lexer.getLoc();
745     Lex(); // Eat identifier.
746     return false;
747   }
748   case AsmToken::LParen:
749     Lex(); // Eat the '('.
750     return ParseParenExpr(Res, EndLoc);
751   case AsmToken::LBrac:
752     if (!PlatformParser->HasBracketExpressions())
753       return TokError("brackets expression not supported on this target");
754     Lex(); // Eat the '['.
755     return ParseBracketExpr(Res, EndLoc);
756   case AsmToken::Minus:
757     Lex(); // Eat the operator.
758     if (ParsePrimaryExpr(Res, EndLoc))
759       return true;
760     Res = MCUnaryExpr::CreateMinus(Res, getContext());
761     return false;
762   case AsmToken::Plus:
763     Lex(); // Eat the operator.
764     if (ParsePrimaryExpr(Res, EndLoc))
765       return true;
766     Res = MCUnaryExpr::CreatePlus(Res, getContext());
767     return false;
768   case AsmToken::Tilde:
769     Lex(); // Eat the operator.
770     if (ParsePrimaryExpr(Res, EndLoc))
771       return true;
772     Res = MCUnaryExpr::CreateNot(Res, getContext());
773     return false;
774   }
775 }
776
777 bool AsmParser::ParseExpression(const MCExpr *&Res) {
778   SMLoc EndLoc;
779   return ParseExpression(Res, EndLoc);
780 }
781
782 const MCExpr *
783 AsmParser::ApplyModifierToExpr(const MCExpr *E,
784                                MCSymbolRefExpr::VariantKind Variant) {
785   // Recurse over the given expression, rebuilding it to apply the given variant
786   // if there is exactly one symbol.
787   switch (E->getKind()) {
788   case MCExpr::Target:
789   case MCExpr::Constant:
790     return 0;
791
792   case MCExpr::SymbolRef: {
793     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
794
795     if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
796       TokError("invalid variant on expression '" +
797                getTok().getIdentifier() + "' (already modified)");
798       return E;
799     }
800
801     return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
802   }
803
804   case MCExpr::Unary: {
805     const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
806     const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
807     if (!Sub)
808       return 0;
809     return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
810   }
811
812   case MCExpr::Binary: {
813     const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
814     const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
815     const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
816
817     if (!LHS && !RHS)
818       return 0;
819
820     if (!LHS) LHS = BE->getLHS();
821     if (!RHS) RHS = BE->getRHS();
822
823     return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
824   }
825   }
826
827   llvm_unreachable("Invalid expression kind!");
828 }
829
830 /// ParseExpression - Parse an expression and return it.
831 ///
832 ///  expr ::= expr &&,|| expr               -> lowest.
833 ///  expr ::= expr |,^,&,! expr
834 ///  expr ::= expr ==,!=,<>,<,<=,>,>= expr
835 ///  expr ::= expr <<,>> expr
836 ///  expr ::= expr +,- expr
837 ///  expr ::= expr *,/,% expr               -> highest.
838 ///  expr ::= primaryexpr
839 ///
840 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
841   // Parse the expression.
842   Res = 0;
843   if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
844     return true;
845
846   // As a special case, we support 'a op b @ modifier' by rewriting the
847   // expression to include the modifier. This is inefficient, but in general we
848   // expect users to use 'a@modifier op b'.
849   if (Lexer.getKind() == AsmToken::At) {
850     Lex();
851
852     if (Lexer.isNot(AsmToken::Identifier))
853       return TokError("unexpected symbol modifier following '@'");
854
855     MCSymbolRefExpr::VariantKind Variant =
856       MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
857     if (Variant == MCSymbolRefExpr::VK_Invalid)
858       return TokError("invalid variant '" + getTok().getIdentifier() + "'");
859
860     const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
861     if (!ModifiedRes) {
862       return TokError("invalid modifier '" + getTok().getIdentifier() +
863                       "' (no symbols present)");
864     }
865
866     Res = ModifiedRes;
867     Lex();
868   }
869
870   // Try to constant fold it up front, if possible.
871   int64_t Value;
872   if (Res->EvaluateAsAbsolute(Value))
873     Res = MCConstantExpr::Create(Value, getContext());
874
875   return false;
876 }
877
878 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
879   Res = 0;
880   return ParseParenExpr(Res, EndLoc) ||
881          ParseBinOpRHS(1, Res, EndLoc);
882 }
883
884 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
885   const MCExpr *Expr;
886
887   SMLoc StartLoc = Lexer.getLoc();
888   if (ParseExpression(Expr))
889     return true;
890
891   if (!Expr->EvaluateAsAbsolute(Res))
892     return Error(StartLoc, "expected absolute expression");
893
894   return false;
895 }
896
897 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
898                                    MCBinaryExpr::Opcode &Kind) {
899   switch (K) {
900   default:
901     return 0;    // not a binop.
902
903     // Lowest Precedence: &&, ||
904   case AsmToken::AmpAmp:
905     Kind = MCBinaryExpr::LAnd;
906     return 1;
907   case AsmToken::PipePipe:
908     Kind = MCBinaryExpr::LOr;
909     return 1;
910
911
912     // Low Precedence: |, &, ^
913     //
914     // FIXME: gas seems to support '!' as an infix operator?
915   case AsmToken::Pipe:
916     Kind = MCBinaryExpr::Or;
917     return 2;
918   case AsmToken::Caret:
919     Kind = MCBinaryExpr::Xor;
920     return 2;
921   case AsmToken::Amp:
922     Kind = MCBinaryExpr::And;
923     return 2;
924
925     // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
926   case AsmToken::EqualEqual:
927     Kind = MCBinaryExpr::EQ;
928     return 3;
929   case AsmToken::ExclaimEqual:
930   case AsmToken::LessGreater:
931     Kind = MCBinaryExpr::NE;
932     return 3;
933   case AsmToken::Less:
934     Kind = MCBinaryExpr::LT;
935     return 3;
936   case AsmToken::LessEqual:
937     Kind = MCBinaryExpr::LTE;
938     return 3;
939   case AsmToken::Greater:
940     Kind = MCBinaryExpr::GT;
941     return 3;
942   case AsmToken::GreaterEqual:
943     Kind = MCBinaryExpr::GTE;
944     return 3;
945
946     // Intermediate Precedence: <<, >>
947   case AsmToken::LessLess:
948     Kind = MCBinaryExpr::Shl;
949     return 4;
950   case AsmToken::GreaterGreater:
951     Kind = MCBinaryExpr::Shr;
952     return 4;
953
954     // High Intermediate Precedence: +, -
955   case AsmToken::Plus:
956     Kind = MCBinaryExpr::Add;
957     return 5;
958   case AsmToken::Minus:
959     Kind = MCBinaryExpr::Sub;
960     return 5;
961
962     // Highest Precedence: *, /, %
963   case AsmToken::Star:
964     Kind = MCBinaryExpr::Mul;
965     return 6;
966   case AsmToken::Slash:
967     Kind = MCBinaryExpr::Div;
968     return 6;
969   case AsmToken::Percent:
970     Kind = MCBinaryExpr::Mod;
971     return 6;
972   }
973 }
974
975
976 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
977 /// Res contains the LHS of the expression on input.
978 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
979                               SMLoc &EndLoc) {
980   while (1) {
981     MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
982     unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
983
984     // If the next token is lower precedence than we are allowed to eat, return
985     // successfully with what we ate already.
986     if (TokPrec < Precedence)
987       return false;
988
989     Lex();
990
991     // Eat the next primary expression.
992     const MCExpr *RHS;
993     if (ParsePrimaryExpr(RHS, EndLoc)) return true;
994
995     // If BinOp binds less tightly with RHS than the operator after RHS, let
996     // the pending operator take RHS as its LHS.
997     MCBinaryExpr::Opcode Dummy;
998     unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
999     if (TokPrec < NextTokPrec) {
1000       if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1001     }
1002
1003     // Merge LHS and RHS according to operator.
1004     Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1005   }
1006 }
1007
1008
1009
1010
1011 /// ParseStatement:
1012 ///   ::= EndOfStatement
1013 ///   ::= Label* Directive ...Operands... EndOfStatement
1014 ///   ::= Label* Identifier OperandList* EndOfStatement
1015 bool AsmParser::ParseStatement() {
1016   if (Lexer.is(AsmToken::EndOfStatement)) {
1017     Out.AddBlankLine();
1018     Lex();
1019     return false;
1020   }
1021
1022   // Statements always start with an identifier or are a full line comment.
1023   AsmToken ID = getTok();
1024   SMLoc IDLoc = ID.getLoc();
1025   StringRef IDVal;
1026   int64_t LocalLabelVal = -1;
1027   // A full line comment is a '#' as the first token.
1028   if (Lexer.is(AsmToken::Hash))
1029     return ParseCppHashLineFilenameComment(IDLoc);
1030
1031   // Allow an integer followed by a ':' as a directional local label.
1032   if (Lexer.is(AsmToken::Integer)) {
1033     LocalLabelVal = getTok().getIntVal();
1034     if (LocalLabelVal < 0) {
1035       if (!TheCondState.Ignore)
1036         return TokError("unexpected token at start of statement");
1037       IDVal = "";
1038     }
1039     else {
1040       IDVal = getTok().getString();
1041       Lex(); // Consume the integer token to be used as an identifier token.
1042       if (Lexer.getKind() != AsmToken::Colon) {
1043         if (!TheCondState.Ignore)
1044           return TokError("unexpected token at start of statement");
1045       }
1046     }
1047
1048   } else if (Lexer.is(AsmToken::Dot)) {
1049     // Treat '.' as a valid identifier in this context.
1050     Lex();
1051     IDVal = ".";
1052
1053   } else if (ParseIdentifier(IDVal)) {
1054     if (!TheCondState.Ignore)
1055       return TokError("unexpected token at start of statement");
1056     IDVal = "";
1057   }
1058
1059
1060   // Handle conditional assembly here before checking for skipping.  We
1061   // have to do this so that .endif isn't skipped in a ".if 0" block for
1062   // example.
1063   if (IDVal == ".if")
1064     return ParseDirectiveIf(IDLoc);
1065   if (IDVal == ".ifb")
1066     return ParseDirectiveIfb(IDLoc, true);
1067   if (IDVal == ".ifnb")
1068     return ParseDirectiveIfb(IDLoc, false);
1069   if (IDVal == ".ifc")
1070     return ParseDirectiveIfc(IDLoc, true);
1071   if (IDVal == ".ifnc")
1072     return ParseDirectiveIfc(IDLoc, false);
1073   if (IDVal == ".ifdef")
1074     return ParseDirectiveIfdef(IDLoc, true);
1075   if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1076     return ParseDirectiveIfdef(IDLoc, false);
1077   if (IDVal == ".elseif")
1078     return ParseDirectiveElseIf(IDLoc);
1079   if (IDVal == ".else")
1080     return ParseDirectiveElse(IDLoc);
1081   if (IDVal == ".endif")
1082     return ParseDirectiveEndIf(IDLoc);
1083
1084   // If we are in a ".if 0" block, ignore this statement.
1085   if (TheCondState.Ignore) {
1086     EatToEndOfStatement();
1087     return false;
1088   }
1089
1090   // FIXME: Recurse on local labels?
1091
1092   // See what kind of statement we have.
1093   switch (Lexer.getKind()) {
1094   case AsmToken::Colon: {
1095     CheckForValidSection();
1096
1097     // identifier ':'   -> Label.
1098     Lex();
1099
1100     // Diagnose attempt to use '.' as a label.
1101     if (IDVal == ".")
1102       return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1103
1104     // Diagnose attempt to use a variable as a label.
1105     //
1106     // FIXME: Diagnostics. Note the location of the definition as a label.
1107     // FIXME: This doesn't diagnose assignment to a symbol which has been
1108     // implicitly marked as external.
1109     MCSymbol *Sym;
1110     if (LocalLabelVal == -1)
1111       Sym = getContext().GetOrCreateSymbol(IDVal);
1112     else
1113       Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1114     if (!Sym->isUndefined() || Sym->isVariable())
1115       return Error(IDLoc, "invalid symbol redefinition");
1116
1117     // Emit the label.
1118     Out.EmitLabel(Sym);
1119
1120     // If we are generating dwarf for assembly source files then gather the
1121     // info to make a dwarf label entry for this label if needed.
1122     if (getContext().getGenDwarfForAssembly())
1123       MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1124                                  IDLoc);
1125
1126     // Consume any end of statement token, if present, to avoid spurious
1127     // AddBlankLine calls().
1128     if (Lexer.is(AsmToken::EndOfStatement)) {
1129       Lex();
1130       if (Lexer.is(AsmToken::Eof))
1131         return false;
1132     }
1133
1134     return ParseStatement();
1135   }
1136
1137   case AsmToken::Equal:
1138     // identifier '=' ... -> assignment statement
1139     Lex();
1140
1141     return ParseAssignment(IDVal, true);
1142
1143   default: // Normal instruction or directive.
1144     break;
1145   }
1146
1147   // If macros are enabled, check to see if this is a macro instantiation.
1148   if (MacrosEnabled)
1149     if (const Macro *M = MacroMap.lookup(IDVal))
1150       return HandleMacroEntry(IDVal, IDLoc, M);
1151
1152   // Otherwise, we have a normal instruction or directive.
1153   if (IDVal[0] == '.' && IDVal != ".") {
1154     // Assembler features
1155     if (IDVal == ".set" || IDVal == ".equ")
1156       return ParseDirectiveSet(IDVal, true);
1157     if (IDVal == ".equiv")
1158       return ParseDirectiveSet(IDVal, false);
1159
1160     // Data directives
1161
1162     if (IDVal == ".ascii")
1163       return ParseDirectiveAscii(IDVal, false);
1164     if (IDVal == ".asciz" || IDVal == ".string")
1165       return ParseDirectiveAscii(IDVal, true);
1166
1167     if (IDVal == ".byte")
1168       return ParseDirectiveValue(1);
1169     if (IDVal == ".short")
1170       return ParseDirectiveValue(2);
1171     if (IDVal == ".value")
1172       return ParseDirectiveValue(2);
1173     if (IDVal == ".2byte")
1174       return ParseDirectiveValue(2);
1175     if (IDVal == ".long")
1176       return ParseDirectiveValue(4);
1177     if (IDVal == ".int")
1178       return ParseDirectiveValue(4);
1179     if (IDVal == ".4byte")
1180       return ParseDirectiveValue(4);
1181     if (IDVal == ".quad")
1182       return ParseDirectiveValue(8);
1183     if (IDVal == ".8byte")
1184       return ParseDirectiveValue(8);
1185     if (IDVal == ".single" || IDVal == ".float")
1186       return ParseDirectiveRealValue(APFloat::IEEEsingle);
1187     if (IDVal == ".double")
1188       return ParseDirectiveRealValue(APFloat::IEEEdouble);
1189
1190     if (IDVal == ".align") {
1191       bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1192       return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1193     }
1194     if (IDVal == ".align32") {
1195       bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1196       return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1197     }
1198     if (IDVal == ".balign")
1199       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1200     if (IDVal == ".balignw")
1201       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1202     if (IDVal == ".balignl")
1203       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1204     if (IDVal == ".p2align")
1205       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1206     if (IDVal == ".p2alignw")
1207       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1208     if (IDVal == ".p2alignl")
1209       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1210
1211     if (IDVal == ".org")
1212       return ParseDirectiveOrg();
1213
1214     if (IDVal == ".fill")
1215       return ParseDirectiveFill();
1216     if (IDVal == ".space" || IDVal == ".skip")
1217       return ParseDirectiveSpace();
1218     if (IDVal == ".zero")
1219       return ParseDirectiveZero();
1220
1221     // Symbol attribute directives
1222
1223     if (IDVal == ".globl" || IDVal == ".global")
1224       return ParseDirectiveSymbolAttribute(MCSA_Global);
1225     if (IDVal == ".indirect_symbol")
1226       return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1227     if (IDVal == ".lazy_reference")
1228       return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1229     if (IDVal == ".no_dead_strip")
1230       return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1231     if (IDVal == ".symbol_resolver")
1232       return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1233     if (IDVal == ".private_extern")
1234       return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1235     if (IDVal == ".reference")
1236       return ParseDirectiveSymbolAttribute(MCSA_Reference);
1237     if (IDVal == ".weak_definition")
1238       return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1239     if (IDVal == ".weak_reference")
1240       return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1241     if (IDVal == ".weak_def_can_be_hidden")
1242       return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1243
1244     if (IDVal == ".comm" || IDVal == ".common")
1245       return ParseDirectiveComm(/*IsLocal=*/false);
1246     if (IDVal == ".lcomm")
1247       return ParseDirectiveComm(/*IsLocal=*/true);
1248
1249     if (IDVal == ".abort")
1250       return ParseDirectiveAbort();
1251     if (IDVal == ".include")
1252       return ParseDirectiveInclude();
1253     if (IDVal == ".incbin")
1254       return ParseDirectiveIncbin();
1255
1256     if (IDVal == ".code16")
1257       return TokError(Twine(IDVal) + " not supported yet");
1258
1259     // Look up the handler in the handler table.
1260     std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1261       DirectiveMap.lookup(IDVal);
1262     if (Handler.first)
1263       return (*Handler.second)(Handler.first, IDVal, IDLoc);
1264
1265     // Target hook for parsing target specific directives.
1266     if (!getTargetParser().ParseDirective(ID))
1267       return false;
1268
1269     return Error(IDLoc, "unknown directive");
1270   }
1271
1272   CheckForValidSection();
1273
1274   // Canonicalize the opcode to lower case.
1275   SmallString<128> Opcode;
1276   for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1277     Opcode.push_back(tolower(IDVal[i]));
1278
1279   SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1280   bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1281                                                      ParsedOperands);
1282
1283   // Dump the parsed representation, if requested.
1284   if (getShowParsedOperands()) {
1285     SmallString<256> Str;
1286     raw_svector_ostream OS(Str);
1287     OS << "parsed instruction: [";
1288     for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1289       if (i != 0)
1290         OS << ", ";
1291       ParsedOperands[i]->print(OS);
1292     }
1293     OS << "]";
1294
1295     PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1296   }
1297
1298   // If we are generating dwarf for assembly source files and the current
1299   // section is the initial text section then generate a .loc directive for
1300   // the instruction.
1301   if (!HadError && getContext().getGenDwarfForAssembly() &&
1302       getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1303     getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1304                                         SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1305                                         0, DWARF2_LINE_DEFAULT_IS_STMT ?
1306                                         DWARF2_FLAG_IS_STMT : 0, 0, 0,
1307                                         StringRef());
1308   }
1309
1310   // If parsing succeeded, match the instruction.
1311   if (!HadError)
1312     HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1313                                                          Out);
1314
1315   // Free any parsed operands.
1316   for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1317     delete ParsedOperands[i];
1318
1319   // Don't skip the rest of the line, the instruction parser is responsible for
1320   // that.
1321   return false;
1322 }
1323
1324 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1325 /// since they may not be able to be tokenized to get to the end of line token.
1326 void AsmParser::EatToEndOfLine() {
1327   if (!Lexer.is(AsmToken::EndOfStatement))
1328     Lexer.LexUntilEndOfLine();
1329  // Eat EOL.
1330  Lex();
1331 }
1332
1333 /// ParseCppHashLineFilenameComment as this:
1334 ///   ::= # number "filename"
1335 /// or just as a full line comment if it doesn't have a number and a string.
1336 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1337   Lex(); // Eat the hash token.
1338
1339   if (getLexer().isNot(AsmToken::Integer)) {
1340     // Consume the line since in cases it is not a well-formed line directive,
1341     // as if were simply a full line comment.
1342     EatToEndOfLine();
1343     return false;
1344   }
1345
1346   int64_t LineNumber = getTok().getIntVal();
1347   Lex();
1348
1349   if (getLexer().isNot(AsmToken::String)) {
1350     EatToEndOfLine();
1351     return false;
1352   }
1353
1354   StringRef Filename = getTok().getString();
1355   // Get rid of the enclosing quotes.
1356   Filename = Filename.substr(1, Filename.size()-2);
1357
1358   // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1359   CppHashLoc = L;
1360   CppHashFilename = Filename;
1361   CppHashLineNumber = LineNumber;
1362
1363   // Ignore any trailing characters, they're just comment.
1364   EatToEndOfLine();
1365   return false;
1366 }
1367
1368 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1369 /// for the Filename and LineNo if any in the diagnostic.
1370 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1371   const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1372   raw_ostream &OS = errs();
1373
1374   const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1375   const SMLoc &DiagLoc = Diag.getLoc();
1376   int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1377   int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1378
1379   // Like SourceMgr::PrintMessage() we need to print the include stack if any
1380   // before printing the message.
1381   int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1382   if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1383      SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1384      DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1385   }
1386
1387   // If we have not parsed a cpp hash line filename comment or the source 
1388   // manager changed or buffer changed (like in a nested include) then just
1389   // print the normal diagnostic using its Filename and LineNo.
1390   if (!Parser->CppHashLineNumber ||
1391       &DiagSrcMgr != &Parser->SrcMgr ||
1392       DiagBuf != CppHashBuf) {
1393     if (Parser->SavedDiagHandler)
1394       Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1395     else
1396       Diag.print(0, OS);
1397     return;
1398   }
1399
1400   // Use the CppHashFilename and calculate a line number based on the 
1401   // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1402   // the diagnostic.
1403   const std::string Filename = Parser->CppHashFilename;
1404
1405   int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1406   int CppHashLocLineNo =
1407       Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1408   int LineNo = Parser->CppHashLineNumber - 1 +
1409                (DiagLocLineNo - CppHashLocLineNo);
1410
1411   SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1412                        Filename, LineNo, Diag.getColumnNo(),
1413                        Diag.getKind(), Diag.getMessage(),
1414                        Diag.getLineContents(), Diag.getRanges());
1415
1416   if (Parser->SavedDiagHandler)
1417     Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1418   else
1419     NewDiag.print(0, OS);
1420 }
1421
1422 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1423                             const std::vector<StringRef> &Parameters,
1424                             const std::vector<std::vector<AsmToken> > &A,
1425                             const SMLoc &L) {
1426   raw_svector_ostream OS(Buf);
1427   unsigned NParameters = Parameters.size();
1428   if (NParameters != 0 && NParameters != A.size())
1429     return Error(L, "Wrong number of arguments");
1430
1431   while (!Body.empty()) {
1432     // Scan for the next substitution.
1433     std::size_t End = Body.size(), Pos = 0;
1434     for (; Pos != End; ++Pos) {
1435       // Check for a substitution or escape.
1436       if (!NParameters) {
1437         // This macro has no parameters, look for $0, $1, etc.
1438         if (Body[Pos] != '$' || Pos + 1 == End)
1439           continue;
1440
1441         char Next = Body[Pos + 1];
1442         if (Next == '$' || Next == 'n' || isdigit(Next))
1443           break;
1444       } else {
1445         // This macro has parameters, look for \foo, \bar, etc.
1446         if (Body[Pos] == '\\' && Pos + 1 != End)
1447           break;
1448       }
1449     }
1450
1451     // Add the prefix.
1452     OS << Body.slice(0, Pos);
1453
1454     // Check if we reached the end.
1455     if (Pos == End)
1456       break;
1457
1458     if (!NParameters) {
1459       switch (Body[Pos+1]) {
1460         // $$ => $
1461       case '$':
1462         OS << '$';
1463         break;
1464
1465         // $n => number of arguments
1466       case 'n':
1467         OS << A.size();
1468         break;
1469
1470         // $[0-9] => argument
1471       default: {
1472         // Missing arguments are ignored.
1473         unsigned Index = Body[Pos+1] - '0';
1474         if (Index >= A.size())
1475           break;
1476
1477         // Otherwise substitute with the token values, with spaces eliminated.
1478         for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1479                ie = A[Index].end(); it != ie; ++it)
1480           OS << it->getString();
1481         break;
1482       }
1483       }
1484       Pos += 2;
1485     } else {
1486       unsigned I = Pos + 1;
1487       while (isalnum(Body[I]) && I + 1 != End)
1488         ++I;
1489
1490       const char *Begin = Body.data() + Pos +1;
1491       StringRef Argument(Begin, I - (Pos +1));
1492       unsigned Index = 0;
1493       for (; Index < NParameters; ++Index)
1494         if (Parameters[Index] == Argument)
1495           break;
1496
1497       // FIXME: We should error at the macro definition.
1498       if (Index == NParameters)
1499         return Error(L, "Parameter not found");
1500
1501       for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1502              ie = A[Index].end(); it != ie; ++it)
1503         OS << it->getString();
1504
1505       Pos += 1 + Argument.size();
1506     }
1507     // Update the scan point.
1508     Body = Body.substr(Pos);
1509   }
1510
1511   // We include the .endmacro in the buffer as our queue to exit the macro
1512   // instantiation.
1513   OS << ".endmacro\n";
1514   return false;
1515 }
1516
1517 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1518                                        MemoryBuffer *I)
1519   : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1520 {
1521 }
1522
1523 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1524                                  const Macro *M) {
1525   // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1526   // this, although we should protect against infinite loops.
1527   if (ActiveMacros.size() == 20)
1528     return TokError("macros cannot be nested more than 20 levels deep");
1529
1530   // Parse the macro instantiation arguments.
1531   std::vector<std::vector<AsmToken> > MacroArguments;
1532   MacroArguments.push_back(std::vector<AsmToken>());
1533   unsigned ParenLevel = 0;
1534   for (;;) {
1535     if (Lexer.is(AsmToken::Eof))
1536       return TokError("unexpected token in macro instantiation");
1537     if (Lexer.is(AsmToken::EndOfStatement))
1538       break;
1539
1540     // If we aren't inside parentheses and this is a comma, start a new token
1541     // list.
1542     if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1543       MacroArguments.push_back(std::vector<AsmToken>());
1544     } else {
1545       // Adjust the current parentheses level.
1546       if (Lexer.is(AsmToken::LParen))
1547         ++ParenLevel;
1548       else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1549         --ParenLevel;
1550
1551       // Append the token to the current argument list.
1552       MacroArguments.back().push_back(getTok());
1553     }
1554     Lex();
1555   }
1556   // If the last argument didn't end up with any tokens, it's not a real
1557   // argument and we should remove it from the list. This happens with either
1558   // a tailing comma or an empty argument list.
1559   if (MacroArguments.back().empty())
1560     MacroArguments.pop_back();
1561
1562   // Macro instantiation is lexical, unfortunately. We construct a new buffer
1563   // to hold the macro body with substitutions.
1564   SmallString<256> Buf;
1565   StringRef Body = M->Body;
1566
1567   if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1568     return true;
1569
1570   MemoryBuffer *Instantiation =
1571     MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1572
1573   // Create the macro instantiation object and add to the current macro
1574   // instantiation stack.
1575   MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1576                                                   getTok().getLoc(),
1577                                                   Instantiation);
1578   ActiveMacros.push_back(MI);
1579
1580   // Jump to the macro instantiation and prime the lexer.
1581   CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1582   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1583   Lex();
1584
1585   return false;
1586 }
1587
1588 void AsmParser::HandleMacroExit() {
1589   // Jump to the EndOfStatement we should return to, and consume it.
1590   JumpToLoc(ActiveMacros.back()->ExitLoc);
1591   Lex();
1592
1593   // Pop the instantiation entry.
1594   delete ActiveMacros.back();
1595   ActiveMacros.pop_back();
1596 }
1597
1598 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1599   switch (Value->getKind()) {
1600   case MCExpr::Binary: {
1601     const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1602     return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1603     break;
1604   }
1605   case MCExpr::Target:
1606   case MCExpr::Constant:
1607     return false;
1608   case MCExpr::SymbolRef: {
1609     const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1610     if (S.isVariable())
1611       return IsUsedIn(Sym, S.getVariableValue());
1612     return &S == Sym;
1613   }
1614   case MCExpr::Unary:
1615     return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1616   }
1617
1618   llvm_unreachable("Unknown expr kind!");
1619 }
1620
1621 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1622   // FIXME: Use better location, we should use proper tokens.
1623   SMLoc EqualLoc = Lexer.getLoc();
1624
1625   const MCExpr *Value;
1626   if (ParseExpression(Value))
1627     return true;
1628
1629   // Note: we don't count b as used in "a = b". This is to allow
1630   // a = b
1631   // b = c
1632
1633   if (Lexer.isNot(AsmToken::EndOfStatement))
1634     return TokError("unexpected token in assignment");
1635
1636   // Error on assignment to '.'.
1637   if (Name == ".") {
1638     return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1639                             "(use '.space' or '.org').)"));
1640   }
1641
1642   // Eat the end of statement marker.
1643   Lex();
1644
1645   // Validate that the LHS is allowed to be a variable (either it has not been
1646   // used as a symbol, or it is an absolute symbol).
1647   MCSymbol *Sym = getContext().LookupSymbol(Name);
1648   if (Sym) {
1649     // Diagnose assignment to a label.
1650     //
1651     // FIXME: Diagnostics. Note the location of the definition as a label.
1652     // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1653     if (IsUsedIn(Sym, Value))
1654       return Error(EqualLoc, "Recursive use of '" + Name + "'");
1655     else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1656       ; // Allow redefinitions of undefined symbols only used in directives.
1657     else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1658       ; // Allow redefinitions of variables that haven't yet been used.
1659     else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1660       return Error(EqualLoc, "redefinition of '" + Name + "'");
1661     else if (!Sym->isVariable())
1662       return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1663     else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1664       return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1665                    Name + "'");
1666
1667     // Don't count these checks as uses.
1668     Sym->setUsed(false);
1669   } else
1670     Sym = getContext().GetOrCreateSymbol(Name);
1671
1672   // FIXME: Handle '.'.
1673
1674   // Do the assignment.
1675   Out.EmitAssignment(Sym, Value);
1676
1677   return false;
1678 }
1679
1680 /// ParseIdentifier:
1681 ///   ::= identifier
1682 ///   ::= string
1683 bool AsmParser::ParseIdentifier(StringRef &Res) {
1684   // The assembler has relaxed rules for accepting identifiers, in particular we
1685   // allow things like '.globl $foo', which would normally be separate
1686   // tokens. At this level, we have already lexed so we cannot (currently)
1687   // handle this as a context dependent token, instead we detect adjacent tokens
1688   // and return the combined identifier.
1689   if (Lexer.is(AsmToken::Dollar)) {
1690     SMLoc DollarLoc = getLexer().getLoc();
1691
1692     // Consume the dollar sign, and check for a following identifier.
1693     Lex();
1694     if (Lexer.isNot(AsmToken::Identifier))
1695       return true;
1696
1697     // We have a '$' followed by an identifier, make sure they are adjacent.
1698     if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1699       return true;
1700
1701     // Construct the joined identifier and consume the token.
1702     Res = StringRef(DollarLoc.getPointer(),
1703                     getTok().getIdentifier().size() + 1);
1704     Lex();
1705     return false;
1706   }
1707
1708   if (Lexer.isNot(AsmToken::Identifier) &&
1709       Lexer.isNot(AsmToken::String))
1710     return true;
1711
1712   Res = getTok().getIdentifier();
1713
1714   Lex(); // Consume the identifier token.
1715
1716   return false;
1717 }
1718
1719 /// ParseDirectiveSet:
1720 ///   ::= .equ identifier ',' expression
1721 ///   ::= .equiv identifier ',' expression
1722 ///   ::= .set identifier ',' expression
1723 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1724   StringRef Name;
1725
1726   if (ParseIdentifier(Name))
1727     return TokError("expected identifier after '" + Twine(IDVal) + "'");
1728
1729   if (getLexer().isNot(AsmToken::Comma))
1730     return TokError("unexpected token in '" + Twine(IDVal) + "'");
1731   Lex();
1732
1733   return ParseAssignment(Name, allow_redef);
1734 }
1735
1736 bool AsmParser::ParseEscapedString(std::string &Data) {
1737   assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1738
1739   Data = "";
1740   StringRef Str = getTok().getStringContents();
1741   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1742     if (Str[i] != '\\') {
1743       Data += Str[i];
1744       continue;
1745     }
1746
1747     // Recognize escaped characters. Note that this escape semantics currently
1748     // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1749     ++i;
1750     if (i == e)
1751       return TokError("unexpected backslash at end of string");
1752
1753     // Recognize octal sequences.
1754     if ((unsigned) (Str[i] - '0') <= 7) {
1755       // Consume up to three octal characters.
1756       unsigned Value = Str[i] - '0';
1757
1758       if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1759         ++i;
1760         Value = Value * 8 + (Str[i] - '0');
1761
1762         if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1763           ++i;
1764           Value = Value * 8 + (Str[i] - '0');
1765         }
1766       }
1767
1768       if (Value > 255)
1769         return TokError("invalid octal escape sequence (out of range)");
1770
1771       Data += (unsigned char) Value;
1772       continue;
1773     }
1774
1775     // Otherwise recognize individual escapes.
1776     switch (Str[i]) {
1777     default:
1778       // Just reject invalid escape sequences for now.
1779       return TokError("invalid escape sequence (unrecognized character)");
1780
1781     case 'b': Data += '\b'; break;
1782     case 'f': Data += '\f'; break;
1783     case 'n': Data += '\n'; break;
1784     case 'r': Data += '\r'; break;
1785     case 't': Data += '\t'; break;
1786     case '"': Data += '"'; break;
1787     case '\\': Data += '\\'; break;
1788     }
1789   }
1790
1791   return false;
1792 }
1793
1794 /// ParseDirectiveAscii:
1795 ///   ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1796 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1797   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1798     CheckForValidSection();
1799
1800     for (;;) {
1801       if (getLexer().isNot(AsmToken::String))
1802         return TokError("expected string in '" + Twine(IDVal) + "' directive");
1803
1804       std::string Data;
1805       if (ParseEscapedString(Data))
1806         return true;
1807
1808       getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1809       if (ZeroTerminated)
1810         getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1811
1812       Lex();
1813
1814       if (getLexer().is(AsmToken::EndOfStatement))
1815         break;
1816
1817       if (getLexer().isNot(AsmToken::Comma))
1818         return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1819       Lex();
1820     }
1821   }
1822
1823   Lex();
1824   return false;
1825 }
1826
1827 /// ParseDirectiveValue
1828 ///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
1829 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1830   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1831     CheckForValidSection();
1832
1833     for (;;) {
1834       const MCExpr *Value;
1835       SMLoc ExprLoc = getLexer().getLoc();
1836       if (ParseExpression(Value))
1837         return true;
1838
1839       // Special case constant expressions to match code generator.
1840       if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1841         assert(Size <= 8 && "Invalid size");
1842         uint64_t IntValue = MCE->getValue();
1843         if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1844           return Error(ExprLoc, "literal value out of range for directive");
1845         getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1846       } else
1847         getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1848
1849       if (getLexer().is(AsmToken::EndOfStatement))
1850         break;
1851
1852       // FIXME: Improve diagnostic.
1853       if (getLexer().isNot(AsmToken::Comma))
1854         return TokError("unexpected token in directive");
1855       Lex();
1856     }
1857   }
1858
1859   Lex();
1860   return false;
1861 }
1862
1863 /// ParseDirectiveRealValue
1864 ///  ::= (.single | .double) [ expression (, expression)* ]
1865 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1866   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1867     CheckForValidSection();
1868
1869     for (;;) {
1870       // We don't truly support arithmetic on floating point expressions, so we
1871       // have to manually parse unary prefixes.
1872       bool IsNeg = false;
1873       if (getLexer().is(AsmToken::Minus)) {
1874         Lex();
1875         IsNeg = true;
1876       } else if (getLexer().is(AsmToken::Plus))
1877         Lex();
1878
1879       if (getLexer().isNot(AsmToken::Integer) &&
1880           getLexer().isNot(AsmToken::Real) &&
1881           getLexer().isNot(AsmToken::Identifier))
1882         return TokError("unexpected token in directive");
1883
1884       // Convert to an APFloat.
1885       APFloat Value(Semantics);
1886       StringRef IDVal = getTok().getString();
1887       if (getLexer().is(AsmToken::Identifier)) {
1888         if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1889           Value = APFloat::getInf(Semantics);
1890         else if (!IDVal.compare_lower("nan"))
1891           Value = APFloat::getNaN(Semantics, false, ~0);
1892         else
1893           return TokError("invalid floating point literal");
1894       } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1895           APFloat::opInvalidOp)
1896         return TokError("invalid floating point literal");
1897       if (IsNeg)
1898         Value.changeSign();
1899
1900       // Consume the numeric token.
1901       Lex();
1902
1903       // Emit the value as an integer.
1904       APInt AsInt = Value.bitcastToAPInt();
1905       getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1906                                  AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1907
1908       if (getLexer().is(AsmToken::EndOfStatement))
1909         break;
1910
1911       if (getLexer().isNot(AsmToken::Comma))
1912         return TokError("unexpected token in directive");
1913       Lex();
1914     }
1915   }
1916
1917   Lex();
1918   return false;
1919 }
1920
1921 /// ParseDirectiveSpace
1922 ///  ::= .space expression [ , expression ]
1923 bool AsmParser::ParseDirectiveSpace() {
1924   CheckForValidSection();
1925
1926   int64_t NumBytes;
1927   if (ParseAbsoluteExpression(NumBytes))
1928     return true;
1929
1930   int64_t FillExpr = 0;
1931   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1932     if (getLexer().isNot(AsmToken::Comma))
1933       return TokError("unexpected token in '.space' directive");
1934     Lex();
1935
1936     if (ParseAbsoluteExpression(FillExpr))
1937       return true;
1938
1939     if (getLexer().isNot(AsmToken::EndOfStatement))
1940       return TokError("unexpected token in '.space' directive");
1941   }
1942
1943   Lex();
1944
1945   if (NumBytes <= 0)
1946     return TokError("invalid number of bytes in '.space' directive");
1947
1948   // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1949   getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1950
1951   return false;
1952 }
1953
1954 /// ParseDirectiveZero
1955 ///  ::= .zero expression
1956 bool AsmParser::ParseDirectiveZero() {
1957   CheckForValidSection();
1958
1959   int64_t NumBytes;
1960   if (ParseAbsoluteExpression(NumBytes))
1961     return true;
1962
1963   int64_t Val = 0;
1964   if (getLexer().is(AsmToken::Comma)) {
1965     Lex();
1966     if (ParseAbsoluteExpression(Val))
1967       return true;
1968   }
1969
1970   if (getLexer().isNot(AsmToken::EndOfStatement))
1971     return TokError("unexpected token in '.zero' directive");
1972
1973   Lex();
1974
1975   getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1976
1977   return false;
1978 }
1979
1980 /// ParseDirectiveFill
1981 ///  ::= .fill expression , expression , expression
1982 bool AsmParser::ParseDirectiveFill() {
1983   CheckForValidSection();
1984
1985   int64_t NumValues;
1986   if (ParseAbsoluteExpression(NumValues))
1987     return true;
1988
1989   if (getLexer().isNot(AsmToken::Comma))
1990     return TokError("unexpected token in '.fill' directive");
1991   Lex();
1992
1993   int64_t FillSize;
1994   if (ParseAbsoluteExpression(FillSize))
1995     return true;
1996
1997   if (getLexer().isNot(AsmToken::Comma))
1998     return TokError("unexpected token in '.fill' directive");
1999   Lex();
2000
2001   int64_t FillExpr;
2002   if (ParseAbsoluteExpression(FillExpr))
2003     return true;
2004
2005   if (getLexer().isNot(AsmToken::EndOfStatement))
2006     return TokError("unexpected token in '.fill' directive");
2007
2008   Lex();
2009
2010   if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2011     return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2012
2013   for (uint64_t i = 0, e = NumValues; i != e; ++i)
2014     getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2015
2016   return false;
2017 }
2018
2019 /// ParseDirectiveOrg
2020 ///  ::= .org expression [ , expression ]
2021 bool AsmParser::ParseDirectiveOrg() {
2022   CheckForValidSection();
2023
2024   const MCExpr *Offset;
2025   SMLoc Loc = getTok().getLoc();
2026   if (ParseExpression(Offset))
2027     return true;
2028
2029   // Parse optional fill expression.
2030   int64_t FillExpr = 0;
2031   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2032     if (getLexer().isNot(AsmToken::Comma))
2033       return TokError("unexpected token in '.org' directive");
2034     Lex();
2035
2036     if (ParseAbsoluteExpression(FillExpr))
2037       return true;
2038
2039     if (getLexer().isNot(AsmToken::EndOfStatement))
2040       return TokError("unexpected token in '.org' directive");
2041   }
2042
2043   Lex();
2044
2045   // Only limited forms of relocatable expressions are accepted here, it
2046   // has to be relative to the current section. The streamer will return
2047   // 'true' if the expression wasn't evaluatable.
2048   if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2049     return Error(Loc, "expected assembly-time absolute expression");
2050
2051   return false;
2052 }
2053
2054 /// ParseDirectiveAlign
2055 ///  ::= {.align, ...} expression [ , expression [ , expression ]]
2056 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2057   CheckForValidSection();
2058
2059   SMLoc AlignmentLoc = getLexer().getLoc();
2060   int64_t Alignment;
2061   if (ParseAbsoluteExpression(Alignment))
2062     return true;
2063
2064   SMLoc MaxBytesLoc;
2065   bool HasFillExpr = false;
2066   int64_t FillExpr = 0;
2067   int64_t MaxBytesToFill = 0;
2068   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2069     if (getLexer().isNot(AsmToken::Comma))
2070       return TokError("unexpected token in directive");
2071     Lex();
2072
2073     // The fill expression can be omitted while specifying a maximum number of
2074     // alignment bytes, e.g:
2075     //  .align 3,,4
2076     if (getLexer().isNot(AsmToken::Comma)) {
2077       HasFillExpr = true;
2078       if (ParseAbsoluteExpression(FillExpr))
2079         return true;
2080     }
2081
2082     if (getLexer().isNot(AsmToken::EndOfStatement)) {
2083       if (getLexer().isNot(AsmToken::Comma))
2084         return TokError("unexpected token in directive");
2085       Lex();
2086
2087       MaxBytesLoc = getLexer().getLoc();
2088       if (ParseAbsoluteExpression(MaxBytesToFill))
2089         return true;
2090
2091       if (getLexer().isNot(AsmToken::EndOfStatement))
2092         return TokError("unexpected token in directive");
2093     }
2094   }
2095
2096   Lex();
2097
2098   if (!HasFillExpr)
2099     FillExpr = 0;
2100
2101   // Compute alignment in bytes.
2102   if (IsPow2) {
2103     // FIXME: Diagnose overflow.
2104     if (Alignment >= 32) {
2105       Error(AlignmentLoc, "invalid alignment value");
2106       Alignment = 31;
2107     }
2108
2109     Alignment = 1ULL << Alignment;
2110   }
2111
2112   // Diagnose non-sensical max bytes to align.
2113   if (MaxBytesLoc.isValid()) {
2114     if (MaxBytesToFill < 1) {
2115       Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2116             "many bytes, ignoring maximum bytes expression");
2117       MaxBytesToFill = 0;
2118     }
2119
2120     if (MaxBytesToFill >= Alignment) {
2121       Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2122               "has no effect");
2123       MaxBytesToFill = 0;
2124     }
2125   }
2126
2127   // Check whether we should use optimal code alignment for this .align
2128   // directive.
2129   bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2130   if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2131       ValueSize == 1 && UseCodeAlign) {
2132     getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2133   } else {
2134     // FIXME: Target specific behavior about how the "extra" bytes are filled.
2135     getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2136                                        MaxBytesToFill);
2137   }
2138
2139   return false;
2140 }
2141
2142 /// ParseDirectiveSymbolAttribute
2143 ///  ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2144 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2145   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2146     for (;;) {
2147       StringRef Name;
2148       SMLoc Loc = getTok().getLoc();
2149
2150       if (ParseIdentifier(Name))
2151         return Error(Loc, "expected identifier in directive");
2152
2153       MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2154
2155       // Assembler local symbols don't make any sense here. Complain loudly.
2156       if (Sym->isTemporary())
2157         return Error(Loc, "non-local symbol required in directive");
2158
2159       getStreamer().EmitSymbolAttribute(Sym, Attr);
2160
2161       if (getLexer().is(AsmToken::EndOfStatement))
2162         break;
2163
2164       if (getLexer().isNot(AsmToken::Comma))
2165         return TokError("unexpected token in directive");
2166       Lex();
2167     }
2168   }
2169
2170   Lex();
2171   return false;
2172 }
2173
2174 /// ParseDirectiveComm
2175 ///  ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2176 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2177   CheckForValidSection();
2178
2179   SMLoc IDLoc = getLexer().getLoc();
2180   StringRef Name;
2181   if (ParseIdentifier(Name))
2182     return TokError("expected identifier in directive");
2183
2184   // Handle the identifier as the key symbol.
2185   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2186
2187   if (getLexer().isNot(AsmToken::Comma))
2188     return TokError("unexpected token in directive");
2189   Lex();
2190
2191   int64_t Size;
2192   SMLoc SizeLoc = getLexer().getLoc();
2193   if (ParseAbsoluteExpression(Size))
2194     return true;
2195
2196   int64_t Pow2Alignment = 0;
2197   SMLoc Pow2AlignmentLoc;
2198   if (getLexer().is(AsmToken::Comma)) {
2199     Lex();
2200     Pow2AlignmentLoc = getLexer().getLoc();
2201     if (ParseAbsoluteExpression(Pow2Alignment))
2202       return true;
2203
2204     // If this target takes alignments in bytes (not log) validate and convert.
2205     if (Lexer.getMAI().getAlignmentIsInBytes()) {
2206       if (!isPowerOf2_64(Pow2Alignment))
2207         return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2208       Pow2Alignment = Log2_64(Pow2Alignment);
2209     }
2210   }
2211
2212   if (getLexer().isNot(AsmToken::EndOfStatement))
2213     return TokError("unexpected token in '.comm' or '.lcomm' directive");
2214
2215   Lex();
2216
2217   // NOTE: a size of zero for a .comm should create a undefined symbol
2218   // but a size of .lcomm creates a bss symbol of size zero.
2219   if (Size < 0)
2220     return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2221                  "be less than zero");
2222
2223   // NOTE: The alignment in the directive is a power of 2 value, the assembler
2224   // may internally end up wanting an alignment in bytes.
2225   // FIXME: Diagnose overflow.
2226   if (Pow2Alignment < 0)
2227     return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2228                  "alignment, can't be less than zero");
2229
2230   if (!Sym->isUndefined())
2231     return Error(IDLoc, "invalid symbol redefinition");
2232
2233   // '.lcomm' is equivalent to '.zerofill'.
2234   // Create the Symbol as a common or local common with Size and Pow2Alignment
2235   if (IsLocal) {
2236     getStreamer().EmitZerofill(Ctx.getMachOSection(
2237                                  "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2238                                  0, SectionKind::getBSS()),
2239                                Sym, Size, 1 << Pow2Alignment);
2240     return false;
2241   }
2242
2243   getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2244   return false;
2245 }
2246
2247 /// ParseDirectiveAbort
2248 ///  ::= .abort [... message ...]
2249 bool AsmParser::ParseDirectiveAbort() {
2250   // FIXME: Use loc from directive.
2251   SMLoc Loc = getLexer().getLoc();
2252
2253   StringRef Str = ParseStringToEndOfStatement();
2254   if (getLexer().isNot(AsmToken::EndOfStatement))
2255     return TokError("unexpected token in '.abort' directive");
2256
2257   Lex();
2258
2259   if (Str.empty())
2260     Error(Loc, ".abort detected. Assembly stopping.");
2261   else
2262     Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2263   // FIXME: Actually abort assembly here.
2264
2265   return false;
2266 }
2267
2268 /// ParseDirectiveInclude
2269 ///  ::= .include "filename"
2270 bool AsmParser::ParseDirectiveInclude() {
2271   if (getLexer().isNot(AsmToken::String))
2272     return TokError("expected string in '.include' directive");
2273
2274   std::string Filename = getTok().getString();
2275   SMLoc IncludeLoc = getLexer().getLoc();
2276   Lex();
2277
2278   if (getLexer().isNot(AsmToken::EndOfStatement))
2279     return TokError("unexpected token in '.include' directive");
2280
2281   // Strip the quotes.
2282   Filename = Filename.substr(1, Filename.size()-2);
2283
2284   // Attempt to switch the lexer to the included file before consuming the end
2285   // of statement to avoid losing it when we switch.
2286   if (EnterIncludeFile(Filename)) {
2287     Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2288     return true;
2289   }
2290
2291   return false;
2292 }
2293
2294 /// ParseDirectiveIncbin
2295 ///  ::= .incbin "filename"
2296 bool AsmParser::ParseDirectiveIncbin() {
2297   if (getLexer().isNot(AsmToken::String))
2298     return TokError("expected string in '.incbin' directive");
2299
2300   std::string Filename = getTok().getString();
2301   SMLoc IncbinLoc = getLexer().getLoc();
2302   Lex();
2303
2304   if (getLexer().isNot(AsmToken::EndOfStatement))
2305     return TokError("unexpected token in '.incbin' directive");
2306
2307   // Strip the quotes.
2308   Filename = Filename.substr(1, Filename.size()-2);
2309
2310   // Attempt to process the included file.
2311   if (ProcessIncbinFile(Filename)) {
2312     Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2313     return true;
2314   }
2315
2316   return false;
2317 }
2318
2319 /// ParseDirectiveIf
2320 /// ::= .if expression
2321 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2322   TheCondStack.push_back(TheCondState);
2323   TheCondState.TheCond = AsmCond::IfCond;
2324   if(TheCondState.Ignore) {
2325     EatToEndOfStatement();
2326   }
2327   else {
2328     int64_t ExprValue;
2329     if (ParseAbsoluteExpression(ExprValue))
2330       return true;
2331
2332     if (getLexer().isNot(AsmToken::EndOfStatement))
2333       return TokError("unexpected token in '.if' directive");
2334
2335     Lex();
2336
2337     TheCondState.CondMet = ExprValue;
2338     TheCondState.Ignore = !TheCondState.CondMet;
2339   }
2340
2341   return false;
2342 }
2343
2344 /// ParseDirectiveIfb
2345 /// ::= .ifb string
2346 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2347   TheCondStack.push_back(TheCondState);
2348   TheCondState.TheCond = AsmCond::IfCond;
2349
2350   if(TheCondState.Ignore) {
2351     EatToEndOfStatement();
2352   } else {
2353     StringRef Str = ParseStringToEndOfStatement();
2354
2355     if (getLexer().isNot(AsmToken::EndOfStatement))
2356       return TokError("unexpected token in '.ifb' directive");
2357
2358     Lex();
2359
2360     TheCondState.CondMet = ExpectBlank == Str.empty();
2361     TheCondState.Ignore = !TheCondState.CondMet;
2362   }
2363
2364   return false;
2365 }
2366
2367 /// ParseDirectiveIfc
2368 /// ::= .ifc string1, string2
2369 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2370   TheCondStack.push_back(TheCondState);
2371   TheCondState.TheCond = AsmCond::IfCond;
2372
2373   if(TheCondState.Ignore) {
2374     EatToEndOfStatement();
2375   } else {
2376     StringRef Str1 = ParseStringToComma();
2377
2378     if (getLexer().isNot(AsmToken::Comma))
2379       return TokError("unexpected token in '.ifc' directive");
2380
2381     Lex();
2382
2383     StringRef Str2 = ParseStringToEndOfStatement();
2384
2385     if (getLexer().isNot(AsmToken::EndOfStatement))
2386       return TokError("unexpected token in '.ifc' directive");
2387
2388     Lex();
2389
2390     TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2391     TheCondState.Ignore = !TheCondState.CondMet;
2392   }
2393
2394   return false;
2395 }
2396
2397 /// ParseDirectiveIfdef
2398 /// ::= .ifdef symbol
2399 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2400   StringRef Name;
2401   TheCondStack.push_back(TheCondState);
2402   TheCondState.TheCond = AsmCond::IfCond;
2403
2404   if (TheCondState.Ignore) {
2405     EatToEndOfStatement();
2406   } else {
2407     if (ParseIdentifier(Name))
2408       return TokError("expected identifier after '.ifdef'");
2409
2410     Lex();
2411
2412     MCSymbol *Sym = getContext().LookupSymbol(Name);
2413
2414     if (expect_defined)
2415       TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2416     else
2417       TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2418     TheCondState.Ignore = !TheCondState.CondMet;
2419   }
2420
2421   return false;
2422 }
2423
2424 /// ParseDirectiveElseIf
2425 /// ::= .elseif expression
2426 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2427   if (TheCondState.TheCond != AsmCond::IfCond &&
2428       TheCondState.TheCond != AsmCond::ElseIfCond)
2429       Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2430                           " an .elseif");
2431   TheCondState.TheCond = AsmCond::ElseIfCond;
2432
2433   bool LastIgnoreState = false;
2434   if (!TheCondStack.empty())
2435       LastIgnoreState = TheCondStack.back().Ignore;
2436   if (LastIgnoreState || TheCondState.CondMet) {
2437     TheCondState.Ignore = true;
2438     EatToEndOfStatement();
2439   }
2440   else {
2441     int64_t ExprValue;
2442     if (ParseAbsoluteExpression(ExprValue))
2443       return true;
2444
2445     if (getLexer().isNot(AsmToken::EndOfStatement))
2446       return TokError("unexpected token in '.elseif' directive");
2447
2448     Lex();
2449     TheCondState.CondMet = ExprValue;
2450     TheCondState.Ignore = !TheCondState.CondMet;
2451   }
2452
2453   return false;
2454 }
2455
2456 /// ParseDirectiveElse
2457 /// ::= .else
2458 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2459   if (getLexer().isNot(AsmToken::EndOfStatement))
2460     return TokError("unexpected token in '.else' directive");
2461
2462   Lex();
2463
2464   if (TheCondState.TheCond != AsmCond::IfCond &&
2465       TheCondState.TheCond != AsmCond::ElseIfCond)
2466       Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2467                           ".elseif");
2468   TheCondState.TheCond = AsmCond::ElseCond;
2469   bool LastIgnoreState = false;
2470   if (!TheCondStack.empty())
2471     LastIgnoreState = TheCondStack.back().Ignore;
2472   if (LastIgnoreState || TheCondState.CondMet)
2473     TheCondState.Ignore = true;
2474   else
2475     TheCondState.Ignore = false;
2476
2477   return false;
2478 }
2479
2480 /// ParseDirectiveEndIf
2481 /// ::= .endif
2482 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2483   if (getLexer().isNot(AsmToken::EndOfStatement))
2484     return TokError("unexpected token in '.endif' directive");
2485
2486   Lex();
2487
2488   if ((TheCondState.TheCond == AsmCond::NoCond) ||
2489       TheCondStack.empty())
2490     Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2491                         ".else");
2492   if (!TheCondStack.empty()) {
2493     TheCondState = TheCondStack.back();
2494     TheCondStack.pop_back();
2495   }
2496
2497   return false;
2498 }
2499
2500 /// ParseDirectiveFile
2501 /// ::= .file [number] filename
2502 /// ::= .file number directory filename
2503 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2504   // FIXME: I'm not sure what this is.
2505   int64_t FileNumber = -1;
2506   SMLoc FileNumberLoc = getLexer().getLoc();
2507   if (getLexer().is(AsmToken::Integer)) {
2508     FileNumber = getTok().getIntVal();
2509     Lex();
2510
2511     if (FileNumber < 1)
2512       return TokError("file number less than one");
2513   }
2514
2515   if (getLexer().isNot(AsmToken::String))
2516     return TokError("unexpected token in '.file' directive");
2517
2518   // Usually the directory and filename together, otherwise just the directory.
2519   StringRef Path = getTok().getString();
2520   Path = Path.substr(1, Path.size()-2);
2521   Lex();
2522
2523   StringRef Directory;
2524   StringRef Filename;
2525   if (getLexer().is(AsmToken::String)) {
2526     if (FileNumber == -1)
2527       return TokError("explicit path specified, but no file number");
2528     Filename = getTok().getString();
2529     Filename = Filename.substr(1, Filename.size()-2);
2530     Directory = Path;
2531     Lex();
2532   } else {
2533     Filename = Path;
2534   }
2535
2536   if (getLexer().isNot(AsmToken::EndOfStatement))
2537     return TokError("unexpected token in '.file' directive");
2538
2539   if (FileNumber == -1)
2540     getStreamer().EmitFileDirective(Filename);
2541   else {
2542     if (getContext().getGenDwarfForAssembly() == true)
2543       Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2544                         "used to generate dwarf debug info for assembly code");
2545
2546     if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2547       Error(FileNumberLoc, "file number already allocated");
2548   }
2549
2550   return false;
2551 }
2552
2553 /// ParseDirectiveLine
2554 /// ::= .line [number]
2555 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2556   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2557     if (getLexer().isNot(AsmToken::Integer))
2558       return TokError("unexpected token in '.line' directive");
2559
2560     int64_t LineNumber = getTok().getIntVal();
2561     (void) LineNumber;
2562     Lex();
2563
2564     // FIXME: Do something with the .line.
2565   }
2566
2567   if (getLexer().isNot(AsmToken::EndOfStatement))
2568     return TokError("unexpected token in '.line' directive");
2569
2570   return false;
2571 }
2572
2573
2574 /// ParseDirectiveLoc
2575 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2576 ///                                [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2577 /// The first number is a file number, must have been previously assigned with
2578 /// a .file directive, the second number is the line number and optionally the
2579 /// third number is a column position (zero if not specified).  The remaining
2580 /// optional items are .loc sub-directives.
2581 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2582
2583   if (getLexer().isNot(AsmToken::Integer))
2584     return TokError("unexpected token in '.loc' directive");
2585   int64_t FileNumber = getTok().getIntVal();
2586   if (FileNumber < 1)
2587     return TokError("file number less than one in '.loc' directive");
2588   if (!getContext().isValidDwarfFileNumber(FileNumber))
2589     return TokError("unassigned file number in '.loc' directive");
2590   Lex();
2591
2592   int64_t LineNumber = 0;
2593   if (getLexer().is(AsmToken::Integer)) {
2594     LineNumber = getTok().getIntVal();
2595     if (LineNumber < 1)
2596       return TokError("line number less than one in '.loc' directive");
2597     Lex();
2598   }
2599
2600   int64_t ColumnPos = 0;
2601   if (getLexer().is(AsmToken::Integer)) {
2602     ColumnPos = getTok().getIntVal();
2603     if (ColumnPos < 0)
2604       return TokError("column position less than zero in '.loc' directive");
2605     Lex();
2606   }
2607
2608   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2609   unsigned Isa = 0;
2610   int64_t Discriminator = 0;
2611   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2612     for (;;) {
2613       if (getLexer().is(AsmToken::EndOfStatement))
2614         break;
2615
2616       StringRef Name;
2617       SMLoc Loc = getTok().getLoc();
2618       if (getParser().ParseIdentifier(Name))
2619         return TokError("unexpected token in '.loc' directive");
2620
2621       if (Name == "basic_block")
2622         Flags |= DWARF2_FLAG_BASIC_BLOCK;
2623       else if (Name == "prologue_end")
2624         Flags |= DWARF2_FLAG_PROLOGUE_END;
2625       else if (Name == "epilogue_begin")
2626         Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2627       else if (Name == "is_stmt") {
2628         SMLoc Loc = getTok().getLoc();
2629         const MCExpr *Value;
2630         if (getParser().ParseExpression(Value))
2631           return true;
2632         // The expression must be the constant 0 or 1.
2633         if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2634           int Value = MCE->getValue();
2635           if (Value == 0)
2636             Flags &= ~DWARF2_FLAG_IS_STMT;
2637           else if (Value == 1)
2638             Flags |= DWARF2_FLAG_IS_STMT;
2639           else
2640             return Error(Loc, "is_stmt value not 0 or 1");
2641         }
2642         else {
2643           return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2644         }
2645       }
2646       else if (Name == "isa") {
2647         SMLoc Loc = getTok().getLoc();
2648         const MCExpr *Value;
2649         if (getParser().ParseExpression(Value))
2650           return true;
2651         // The expression must be a constant greater or equal to 0.
2652         if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2653           int Value = MCE->getValue();
2654           if (Value < 0)
2655             return Error(Loc, "isa number less than zero");
2656           Isa = Value;
2657         }
2658         else {
2659           return Error(Loc, "isa number not a constant value");
2660         }
2661       }
2662       else if (Name == "discriminator") {
2663         if (getParser().ParseAbsoluteExpression(Discriminator))
2664           return true;
2665       }
2666       else {
2667         return Error(Loc, "unknown sub-directive in '.loc' directive");
2668       }
2669
2670       if (getLexer().is(AsmToken::EndOfStatement))
2671         break;
2672     }
2673   }
2674
2675   getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2676                                       Isa, Discriminator, StringRef());
2677
2678   return false;
2679 }
2680
2681 /// ParseDirectiveStabs
2682 /// ::= .stabs string, number, number, number
2683 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2684                                            SMLoc DirectiveLoc) {
2685   return TokError("unsupported directive '" + Directive + "'");
2686 }
2687
2688 /// ParseDirectiveCFISections
2689 /// ::= .cfi_sections section [, section]
2690 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2691                                                  SMLoc DirectiveLoc) {
2692   StringRef Name;
2693   bool EH = false;
2694   bool Debug = false;
2695
2696   if (getParser().ParseIdentifier(Name))
2697     return TokError("Expected an identifier");
2698
2699   if (Name == ".eh_frame")
2700     EH = true;
2701   else if (Name == ".debug_frame")
2702     Debug = true;
2703
2704   if (getLexer().is(AsmToken::Comma)) {
2705     Lex();
2706
2707     if (getParser().ParseIdentifier(Name))
2708       return TokError("Expected an identifier");
2709
2710     if (Name == ".eh_frame")
2711       EH = true;
2712     else if (Name == ".debug_frame")
2713       Debug = true;
2714   }
2715
2716   getStreamer().EmitCFISections(EH, Debug);
2717
2718   return false;
2719 }
2720
2721 /// ParseDirectiveCFIStartProc
2722 /// ::= .cfi_startproc
2723 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2724                                                   SMLoc DirectiveLoc) {
2725   getStreamer().EmitCFIStartProc();
2726   return false;
2727 }
2728
2729 /// ParseDirectiveCFIEndProc
2730 /// ::= .cfi_endproc
2731 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2732   getStreamer().EmitCFIEndProc();
2733   return false;
2734 }
2735
2736 /// ParseRegisterOrRegisterNumber - parse register name or number.
2737 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2738                                                      SMLoc DirectiveLoc) {
2739   unsigned RegNo;
2740
2741   if (getLexer().isNot(AsmToken::Integer)) {
2742     if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2743       DirectiveLoc))
2744       return true;
2745     Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2746   } else
2747     return getParser().ParseAbsoluteExpression(Register);
2748
2749   return false;
2750 }
2751
2752 /// ParseDirectiveCFIDefCfa
2753 /// ::= .cfi_def_cfa register,  offset
2754 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2755                                                SMLoc DirectiveLoc) {
2756   int64_t Register = 0;
2757   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2758     return true;
2759
2760   if (getLexer().isNot(AsmToken::Comma))
2761     return TokError("unexpected token in directive");
2762   Lex();
2763
2764   int64_t Offset = 0;
2765   if (getParser().ParseAbsoluteExpression(Offset))
2766     return true;
2767
2768   getStreamer().EmitCFIDefCfa(Register, Offset);
2769   return false;
2770 }
2771
2772 /// ParseDirectiveCFIDefCfaOffset
2773 /// ::= .cfi_def_cfa_offset offset
2774 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2775                                                      SMLoc DirectiveLoc) {
2776   int64_t Offset = 0;
2777   if (getParser().ParseAbsoluteExpression(Offset))
2778     return true;
2779
2780   getStreamer().EmitCFIDefCfaOffset(Offset);
2781   return false;
2782 }
2783
2784 /// ParseDirectiveCFIAdjustCfaOffset
2785 /// ::= .cfi_adjust_cfa_offset adjustment
2786 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2787                                                         SMLoc DirectiveLoc) {
2788   int64_t Adjustment = 0;
2789   if (getParser().ParseAbsoluteExpression(Adjustment))
2790     return true;
2791
2792   getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2793   return false;
2794 }
2795
2796 /// ParseDirectiveCFIDefCfaRegister
2797 /// ::= .cfi_def_cfa_register register
2798 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2799                                                        SMLoc DirectiveLoc) {
2800   int64_t Register = 0;
2801   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2802     return true;
2803
2804   getStreamer().EmitCFIDefCfaRegister(Register);
2805   return false;
2806 }
2807
2808 /// ParseDirectiveCFIOffset
2809 /// ::= .cfi_offset register, offset
2810 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2811   int64_t Register = 0;
2812   int64_t Offset = 0;
2813
2814   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2815     return true;
2816
2817   if (getLexer().isNot(AsmToken::Comma))
2818     return TokError("unexpected token in directive");
2819   Lex();
2820
2821   if (getParser().ParseAbsoluteExpression(Offset))
2822     return true;
2823
2824   getStreamer().EmitCFIOffset(Register, Offset);
2825   return false;
2826 }
2827
2828 /// ParseDirectiveCFIRelOffset
2829 /// ::= .cfi_rel_offset register, offset
2830 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2831                                                   SMLoc DirectiveLoc) {
2832   int64_t Register = 0;
2833
2834   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2835     return true;
2836
2837   if (getLexer().isNot(AsmToken::Comma))
2838     return TokError("unexpected token in directive");
2839   Lex();
2840
2841   int64_t Offset = 0;
2842   if (getParser().ParseAbsoluteExpression(Offset))
2843     return true;
2844
2845   getStreamer().EmitCFIRelOffset(Register, Offset);
2846   return false;
2847 }
2848
2849 static bool isValidEncoding(int64_t Encoding) {
2850   if (Encoding & ~0xff)
2851     return false;
2852
2853   if (Encoding == dwarf::DW_EH_PE_omit)
2854     return true;
2855
2856   const unsigned Format = Encoding & 0xf;
2857   if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2858       Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2859       Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2860       Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2861     return false;
2862
2863   const unsigned Application = Encoding & 0x70;
2864   if (Application != dwarf::DW_EH_PE_absptr &&
2865       Application != dwarf::DW_EH_PE_pcrel)
2866     return false;
2867
2868   return true;
2869 }
2870
2871 /// ParseDirectiveCFIPersonalityOrLsda
2872 /// ::= .cfi_personality encoding, [symbol_name]
2873 /// ::= .cfi_lsda encoding, [symbol_name]
2874 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2875                                                     SMLoc DirectiveLoc) {
2876   int64_t Encoding = 0;
2877   if (getParser().ParseAbsoluteExpression(Encoding))
2878     return true;
2879   if (Encoding == dwarf::DW_EH_PE_omit)
2880     return false;
2881
2882   if (!isValidEncoding(Encoding))
2883     return TokError("unsupported encoding.");
2884
2885   if (getLexer().isNot(AsmToken::Comma))
2886     return TokError("unexpected token in directive");
2887   Lex();
2888
2889   StringRef Name;
2890   if (getParser().ParseIdentifier(Name))
2891     return TokError("expected identifier in directive");
2892
2893   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2894
2895   if (IDVal == ".cfi_personality")
2896     getStreamer().EmitCFIPersonality(Sym, Encoding);
2897   else {
2898     assert(IDVal == ".cfi_lsda");
2899     getStreamer().EmitCFILsda(Sym, Encoding);
2900   }
2901   return false;
2902 }
2903
2904 /// ParseDirectiveCFIRememberState
2905 /// ::= .cfi_remember_state
2906 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2907                                                       SMLoc DirectiveLoc) {
2908   getStreamer().EmitCFIRememberState();
2909   return false;
2910 }
2911
2912 /// ParseDirectiveCFIRestoreState
2913 /// ::= .cfi_remember_state
2914 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2915                                                      SMLoc DirectiveLoc) {
2916   getStreamer().EmitCFIRestoreState();
2917   return false;
2918 }
2919
2920 /// ParseDirectiveCFISameValue
2921 /// ::= .cfi_same_value register
2922 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2923                                                   SMLoc DirectiveLoc) {
2924   int64_t Register = 0;
2925
2926   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2927     return true;
2928
2929   getStreamer().EmitCFISameValue(Register);
2930
2931   return false;
2932 }
2933
2934 /// ParseDirectiveCFIRestore
2935 /// ::= .cfi_restore register
2936 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
2937                                                 SMLoc DirectiveLoc) {
2938   int64_t Register = 0;
2939   if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2940     return true;
2941
2942   getStreamer().EmitCFIRestore(Register);
2943
2944   return false;
2945 }
2946
2947 /// ParseDirectiveCFIEscape
2948 /// ::= .cfi_escape expression[,...]
2949 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
2950                                                SMLoc DirectiveLoc) {
2951   std::string Values;
2952   int64_t CurrValue;
2953   if (getParser().ParseAbsoluteExpression(CurrValue))
2954     return true;
2955
2956   Values.push_back((uint8_t)CurrValue);
2957
2958   while (getLexer().is(AsmToken::Comma)) {
2959     Lex();
2960
2961     if (getParser().ParseAbsoluteExpression(CurrValue))
2962       return true;
2963
2964     Values.push_back((uint8_t)CurrValue);
2965   }
2966
2967   getStreamer().EmitCFIEscape(Values);
2968   return false;
2969 }
2970
2971 /// ParseDirectiveCFISignalFrame
2972 /// ::= .cfi_signal_frame
2973 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
2974                                                     SMLoc DirectiveLoc) {
2975   if (getLexer().isNot(AsmToken::EndOfStatement))
2976     return Error(getLexer().getLoc(),
2977                  "unexpected token in '" + Directive + "' directive");
2978
2979   getStreamer().EmitCFISignalFrame();
2980
2981   return false;
2982 }
2983
2984 /// ParseDirectiveMacrosOnOff
2985 /// ::= .macros_on
2986 /// ::= .macros_off
2987 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2988                                                  SMLoc DirectiveLoc) {
2989   if (getLexer().isNot(AsmToken::EndOfStatement))
2990     return Error(getLexer().getLoc(),
2991                  "unexpected token in '" + Directive + "' directive");
2992
2993   getParser().MacrosEnabled = Directive == ".macros_on";
2994
2995   return false;
2996 }
2997
2998 /// ParseDirectiveMacro
2999 /// ::= .macro name [parameters]
3000 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3001                                            SMLoc DirectiveLoc) {
3002   StringRef Name;
3003   if (getParser().ParseIdentifier(Name))
3004     return TokError("expected identifier in directive");
3005
3006   std::vector<StringRef> Parameters;
3007   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3008     for(;;) {
3009       StringRef Parameter;
3010       if (getParser().ParseIdentifier(Parameter))
3011         return TokError("expected identifier in directive");
3012       Parameters.push_back(Parameter);
3013
3014       if (getLexer().isNot(AsmToken::Comma))
3015         break;
3016       Lex();
3017     }
3018   }
3019
3020   if (getLexer().isNot(AsmToken::EndOfStatement))
3021     return TokError("unexpected token in '.macro' directive");
3022
3023   // Eat the end of statement.
3024   Lex();
3025
3026   AsmToken EndToken, StartToken = getTok();
3027
3028   // Lex the macro definition.
3029   for (;;) {
3030     // Check whether we have reached the end of the file.
3031     if (getLexer().is(AsmToken::Eof))
3032       return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3033
3034     // Otherwise, check whether we have reach the .endmacro.
3035     if (getLexer().is(AsmToken::Identifier) &&
3036         (getTok().getIdentifier() == ".endm" ||
3037          getTok().getIdentifier() == ".endmacro")) {
3038       EndToken = getTok();
3039       Lex();
3040       if (getLexer().isNot(AsmToken::EndOfStatement))
3041         return TokError("unexpected token in '" + EndToken.getIdentifier() +
3042                         "' directive");
3043       break;
3044     }
3045
3046     // Otherwise, scan til the end of the statement.
3047     getParser().EatToEndOfStatement();
3048   }
3049
3050   if (getParser().MacroMap.lookup(Name)) {
3051     return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3052   }
3053
3054   const char *BodyStart = StartToken.getLoc().getPointer();
3055   const char *BodyEnd = EndToken.getLoc().getPointer();
3056   StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3057   getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3058   return false;
3059 }
3060
3061 /// ParseDirectiveEndMacro
3062 /// ::= .endm
3063 /// ::= .endmacro
3064 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3065                                            SMLoc DirectiveLoc) {
3066   if (getLexer().isNot(AsmToken::EndOfStatement))
3067     return TokError("unexpected token in '" + Directive + "' directive");
3068
3069   // If we are inside a macro instantiation, terminate the current
3070   // instantiation.
3071   if (!getParser().ActiveMacros.empty()) {
3072     getParser().HandleMacroExit();
3073     return false;
3074   }
3075
3076   // Otherwise, this .endmacro is a stray entry in the file; well formed
3077   // .endmacro directives are handled during the macro definition parsing.
3078   return TokError("unexpected '" + Directive + "' in file, "
3079                   "no current macro definition");
3080 }
3081
3082 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3083   getParser().CheckForValidSection();
3084
3085   const MCExpr *Value;
3086
3087   if (getParser().ParseExpression(Value))
3088     return true;
3089
3090   if (getLexer().isNot(AsmToken::EndOfStatement))
3091     return TokError("unexpected token in directive");
3092
3093   if (DirName[1] == 's')
3094     getStreamer().EmitSLEB128Value(Value);
3095   else
3096     getStreamer().EmitULEB128Value(Value);
3097
3098   return false;
3099 }
3100
3101
3102 /// \brief Create an MCAsmParser instance.
3103 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3104                                      MCContext &C, MCStreamer &Out,
3105                                      const MCAsmInfo &MAI) {
3106   return new AsmParser(SM, C, Out, MAI);
3107 }