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