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