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